[SCM] root-system: CERN's ROOT Data Analysis Framework branch, master, updated. upstream/5.34.00_rc1-25-gbcd9604

Lifeng Sun lifongsun at gmail.com
Tue Jun 19 02:25:12 UTC 2012


The following commit has been merged in the master branch:
commit a95335165fe6bcaa94966229ccdb09fb9a6f08e7
Author: Lifeng Sun <lifongsun at gmail.com>
Date:   Thu Jun 7 09:59:58 2012 +0800

    Imported Upstream version 5.34.00

diff --git a/CMakeLists.txt b/CMakeLists.txt
index 3d506f3..06c79b3 100644
--- a/CMakeLists.txt
+++ b/CMakeLists.txt
@@ -29,6 +29,7 @@ set_property(GLOBAL PROPERTY USE_FOLDERS ON)
 
 #---Load some basic macros which are needed later for the confiuration and build----------------
 include(RootNewMacros)
+include(RootBuildOptions)
 include(CheckCompiler)
 include(MacroEnsureVersion)
 
@@ -37,8 +38,6 @@ include(MacroEnsureVersion)
 #---Check if the user wants to build the project in the source directory------------------------
 ROOT_CHECK_OUT_OF_SOURCE_BUILD()
 
-#---Here we declare the required build options--------------------------------------------------
-include(RootBuildOptions)
 #---Here we look for installed software and switch on and of the different build options--------
 include(SearchInstalledSoftware)
 ROOT_SHOW_OPTIONS()
diff --git a/build/version_number b/build/version_number
index 2f82b20..ac1acc7 100644
--- a/build/version_number
+++ b/build/version_number
@@ -1 +1 @@
-5.34/00-rc1
+5.34/00
diff --git a/cint/reflex/python/genreflex/gendict.py b/cint/reflex/python/genreflex/gendict.py
index 7c0b02c..419d432 100644
--- a/cint/reflex/python/genreflex/gendict.py
+++ b/cint/reflex/python/genreflex/gendict.py
@@ -2326,12 +2326,16 @@ class genDictionary(object) :
         if opname == 'new []':
           if len(sems) == 1 and self.genTypeName(sems[0]['type']) in ('size_t',): opnewa = 1
           if len(sems) == 2 and self.genTypeName(sems[0]['type']) in ('size_t',) and self.genTypeName(sems[1]['type']) in ('void*',): plopnewa = 1
-    newc = ''
-    newa = ''
+    newc,newa = '',''
     if opnewc and not plopnewc: newc = '_np'
     elif not opnewc and plopnewc : newc = '_p'
     if opnewa and not plopnewa: newa = '_np'
     elif not opnewa and plopnewa : newa = '_p'
+    # go to base classes eventually
+    if (newc,newa) == ('','') :
+      for b in self.getBases(cid):
+        newc,newa = self.checkOperators(b['type'])
+        if (newc,newa) != ('','') : break
     return (newc, newa)
 #----Constructor/Destructor stuff--------------------------------------------------------
   def genGetNewDelFunctionsDecl( self, attrs, args ) :
diff --git a/cint/reflex/test/implementation/legacy/dictionary_generator.cpp b/cint/reflex/test/implementation/legacy/dictionary_generator.cpp
index a444ff1..4b5f71c 100644
--- a/cint/reflex/test/implementation/legacy/dictionary_generator.cpp
+++ b/cint/reflex/test/implementation/legacy/dictionary_generator.cpp
@@ -1,4 +1,4 @@
-// @(#)root/reflex:$Id: dictionary_generator.cpp 26196 2008-11-14 14:56:58Z axel $
+// @(#)root/reflex:$Id: dictionary_generator.cpp 44182 2012-05-08 15:52:28Z moneta $
 
 #include "Reflex/DictionaryGenerator.h"
 
diff --git a/cint/reflex/test/implementation/legacy/test_ReflexBuilder_unit.cxx b/cint/reflex/test/implementation/legacy/test_ReflexBuilder_unit.cxx
index 45b9ede..c028f83 100644
--- a/cint/reflex/test/implementation/legacy/test_ReflexBuilder_unit.cxx
+++ b/cint/reflex/test/implementation/legacy/test_ReflexBuilder_unit.cxx
@@ -1,4 +1,4 @@
-// @(#)root/reflex:$Id: test_ReflexBuilder_unit.cxx 42896 2012-02-07 10:29:57Z axel $
+// @(#)root/reflex:$Id: test_ReflexBuilder_unit.cxx 44182 2012-05-08 15:52:28Z moneta $
 // Author: Stefan Roiser 2004
 
 // CppUnit include file
diff --git a/cint/reflex/test/implementation/legacy/test_Reflex_generate.cxx b/cint/reflex/test/implementation/legacy/test_Reflex_generate.cxx
index 56ec547..dc74828 100644
--- a/cint/reflex/test/implementation/legacy/test_Reflex_generate.cxx
+++ b/cint/reflex/test/implementation/legacy/test_Reflex_generate.cxx
@@ -1,4 +1,4 @@
-// @(#)root/reflex:$Id: test_Reflex_generate.cxx 29288 2009-07-01 13:03:35Z axel $
+// @(#)root/reflex:$Id: test_Reflex_generate.cxx 44182 2012-05-08 15:52:28Z moneta $
 // Author: Stefan Roiser 2004
 
 #include "Reflex/Reflex.h"
diff --git a/cint/reflex/test/implementation/legacy/test_Reflex_lookup.cxx b/cint/reflex/test/implementation/legacy/test_Reflex_lookup.cxx
index ab91176..bdd7495 100644
--- a/cint/reflex/test/implementation/legacy/test_Reflex_lookup.cxx
+++ b/cint/reflex/test/implementation/legacy/test_Reflex_lookup.cxx
@@ -1,4 +1,4 @@
-// @(#)root/reflex:$Id: test_Reflex_lookup.cxx 29288 2009-07-01 13:03:35Z axel $
+// @(#)root/reflex:$Id: test_Reflex_lookup.cxx 44182 2012-05-08 15:52:28Z moneta $
 // Author: Stefan Roiser 2004
 
 // CppUnit include file
diff --git a/cint/reflex/test/implementation/legacy/test_Reflex_plugins.cxx b/cint/reflex/test/implementation/legacy/test_Reflex_plugins.cxx
index 2b2903a..84431fd 100644
--- a/cint/reflex/test/implementation/legacy/test_Reflex_plugins.cxx
+++ b/cint/reflex/test/implementation/legacy/test_Reflex_plugins.cxx
@@ -1,4 +1,4 @@
-// @(#)root/reflex:$Id: test_Reflex_plugins.cxx 29288 2009-07-01 13:03:35Z axel $
+// @(#)root/reflex:$Id: test_Reflex_plugins.cxx 44182 2012-05-08 15:52:28Z moneta $
 // Author: Pere Mato 2006
 
 // CppUnit include file
diff --git a/cint/reflex/test/implementation/legacy/test_Reflex_simple1.cxx b/cint/reflex/test/implementation/legacy/test_Reflex_simple1.cxx
index cb6a093..d428e44 100644
--- a/cint/reflex/test/implementation/legacy/test_Reflex_simple1.cxx
+++ b/cint/reflex/test/implementation/legacy/test_Reflex_simple1.cxx
@@ -1,4 +1,4 @@
-// @(#)root/reflex:$Id: test_Reflex_simple1.cxx 44089 2012-05-03 14:06:52Z axel $
+// @(#)root/reflex:$Id: test_Reflex_simple1.cxx 44182 2012-05-08 15:52:28Z moneta $
 // Author: Stefan Roiser 2004
 
 // CppUnit include file
diff --git a/cint/reflex/test/implementation/legacy/test_Reflex_simple2.cxx b/cint/reflex/test/implementation/legacy/test_Reflex_simple2.cxx
index dab3727..2972c99 100644
--- a/cint/reflex/test/implementation/legacy/test_Reflex_simple2.cxx
+++ b/cint/reflex/test/implementation/legacy/test_Reflex_simple2.cxx
@@ -1,4 +1,4 @@
-// @(#)root/reflex:$Id: test_Reflex_simple2.cxx 34633 2010-07-28 10:03:15Z axel $
+// @(#)root/reflex:$Id: test_Reflex_simple2.cxx 44182 2012-05-08 15:52:28Z moneta $
 // Author: Stefan Roiser 2004
 
 // CppUnit include file
diff --git a/cint/reflex/test/implementation/legacy/test_Reflex_unit.cxx b/cint/reflex/test/implementation/legacy/test_Reflex_unit.cxx
index 54979e5..0f923b3 100644
--- a/cint/reflex/test/implementation/legacy/test_Reflex_unit.cxx
+++ b/cint/reflex/test/implementation/legacy/test_Reflex_unit.cxx
@@ -1,4 +1,4 @@
-// @(#)root/reflex:$Id: test_Reflex_unit.cxx 29288 2009-07-01 13:03:35Z axel $
+// @(#)root/reflex:$Id: test_Reflex_unit.cxx 44182 2012-05-08 15:52:28Z moneta $
 // Author: Stefan Roiser 2004
 
 // CppUnit include file
diff --git a/cmake/modules/CheckCXXCompilerFlag.cmake b/cmake/modules/CheckCXXCompilerFlag.cmake
new file mode 100644
index 0000000..3618b71
--- /dev/null
+++ b/cmake/modules/CheckCXXCompilerFlag.cmake
@@ -0,0 +1,48 @@
+# - Check whether the CXX compiler supports a given flag.
+# CHECK_CXX_COMPILER_FLAG(<flag> <var>)
+#  <flag> - the compiler flag
+#  <var>  - variable to store the result
+# This internally calls the check_cxx_source_compiles macro.  See help
+# for CheckCXXSourceCompiles for a listing of variables that can
+# modify the build.
+
+#=============================================================================
+# Copyright 2006-2010 Kitware, Inc.
+# Copyright 2006 Alexander Neundorf <neundorf at kde.org>
+# Copyright 2011 Matthias Kretz <kretz at kde.org>
+#
+# Distributed under the OSI-approved BSD License (the "License");
+# see accompanying file Copyright.txt for details.
+#
+# This software is distributed WITHOUT ANY WARRANTY; without even the
+# implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
+# See the License for more information.
+#=============================================================================
+# (To distribute this file outside of CMake, substitute the full
+#  License text for the above reference.)
+
+INCLUDE(CheckCXXSourceCompiles)
+
+MACRO (CHECK_CXX_COMPILER_FLAG _FLAG _RESULT)
+   SET(SAFE_CMAKE_REQUIRED_DEFINITIONS "${CMAKE_REQUIRED_DEFINITIONS}")
+   SET(CMAKE_REQUIRED_DEFINITIONS "${_FLAG}")
+   CHECK_CXX_SOURCE_COMPILES("int main() { return 0;}" ${_RESULT}
+     # Some compilers do not fail with a bad flag
+     FAIL_REGEX "command line option .* is valid for .* but not for C\\\\+\\\\+" # GNU
+     FAIL_REGEX "unrecognized .*option"                     # GNU
+     FAIL_REGEX "unknown .*option"                          # Clang
+     FAIL_REGEX "invalid value"                             # Clang 
+     FAIL_REGEX "ignoring unknown option"                   # MSVC
+     FAIL_REGEX "warning D9002"                             # MSVC, any lang
+     FAIL_REGEX "option.*not supported"                     # Intel
+     FAIL_REGEX "invalid argument .*option"                 # Intel
+     FAIL_REGEX "ignoring option .*argument required"       # Intel
+     FAIL_REGEX "[Uu]nknown option"                         # HP
+     FAIL_REGEX "[Ww]arning: [Oo]ption"                     # SunPro
+     FAIL_REGEX "command option .* is not recognized"       # XL
+     FAIL_REGEX "not supported in this configuration; ignored"       # AIX
+     FAIL_REGEX "File with unknown suffix passed to linker" # PGI
+     FAIL_REGEX "WARNING: unknown flag:"                    # Open64
+     )
+   SET (CMAKE_REQUIRED_DEFINITIONS "${SAFE_CMAKE_REQUIRED_DEFINITIONS}")
+ENDMACRO (CHECK_CXX_COMPILER_FLAG)
diff --git a/cmake/modules/CheckCompiler.cmake b/cmake/modules/CheckCompiler.cmake
index 64c10fb..60f440e 100644
--- a/cmake/modules/CheckCompiler.cmake
+++ b/cmake/modules/CheckCompiler.cmake
@@ -25,9 +25,19 @@ endif()
 #---Obtain the major and minor version of the GNU compiler-------------------------------------------
 if (CMAKE_COMPILER_IS_GNUCXX)
   exec_program(${CMAKE_C_COMPILER} ARGS "-dumpversion" OUTPUT_VARIABLE _gcc_version_info)
-  string(REGEX REPLACE "^([0-9]+)\\.[0-9]+\\.[0-9]" "\\1" GCC_MAJOR "${_gcc_version_info}")
-  string(REGEX REPLACE "^[0-9]+\\.([0-9]+)\\.[0-9]" "\\1" GCC_MINOR "${_gcc_version_info}")
-  string(REGEX REPLACE "^[0-9]+\\.[0-9]+\\.([0-9])" "\\1" GCC_PATCH "${_gcc_version_info}")
+  string(REGEX REPLACE "^([0-9]+).*$"                   "\\1" GCC_MAJOR ${_gcc_version_info})
+  string(REGEX REPLACE "^[0-9]+\\.([0-9]+).*$"          "\\1" GCC_MINOR ${_gcc_version_info})
+  string(REGEX REPLACE "^[0-9]+\\.[0-9]+\\.([0-9]+).*$" "\\1" GCC_PATCH ${_gcc_version_info})
+
+  if(GCC_PATCH MATCHES "\\.+")
+    set(GCC_PATCH "")
+  endif()
+  if(GCC_MINOR MATCHES "\\.+")
+    set(GCC_MINOR "")
+  endif()
+  if(GCC_MAJOR MATCHES "\\.+")
+    set(GCC_MAJOR "")
+  endif()
   message(STATUS "Found GCC. Major version ${GCC_MAJOR}, minor version ${GCC_MINOR}")
   set(COMPILER_VERSION gcc${GCC_MAJOR}${GCC_MINOR}${GCC_PATCH})
 else()
@@ -41,6 +51,16 @@ if(NOT CMAKE_BUILD_TYPE)
 endif()
 message(STATUS "CMAKE_BUILD_TYPE: ${CMAKE_BUILD_TYPE}")
 
+#---Check for c++11 option------------------------------------------------------------
+if(c++11)
+  include(CheckCXXCompilerFlag)
+  CHECK_CXX_COMPILER_FLAG("-std=c++11" HAS_CXX11)
+  if(NOT HAS_CXX11)
+    message(STATUS "Current compiler does not suppport -std=c++11 option. Switching OFF c++11 option")
+    set(c++11 OFF CACHE BOOL "" FORCE)
+  endif()
+endif()
+
 #---Need to locate thead libraries and options to set properly some compilation flags---------------- 
 find_package(Threads)
 
@@ -53,6 +73,10 @@ elseif(WIN32)
   include(SetupWindows)
 endif()
 
+if(c++11)
+    set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -std=c++11 -Wno-deprecated-declaration")
+endif()
+
 #---Print the final compiler flags--------------------------------------------------------------------
 message(STATUS "ROOT Platform: ${ROOT_PLATFORM}")
 message(STATUS "ROOT Architecture: ${ROOT_ARCHITECTURE}")
diff --git a/cmake/modules/FindPythia8.cmake b/cmake/modules/FindPythia8.cmake
index 9fd8562..d391d72 100644
--- a/cmake/modules/FindPythia8.cmake
+++ b/cmake/modules/FindPythia8.cmake
@@ -17,7 +17,7 @@ find_path(PYTHIA8_INCLUDE_DIR Pythia.h
   DOC "Specify the directory containing Pythia.h."
 )
 
-find_library(PYTHIA8_LIBRARY NAMES libPythia8 PATHS
+find_library(PYTHIA8_LIBRARY NAMES Pythia8 libPythia8 PATHS
   $ENV{PYTHIA8_DIR}/lib
   /opt/pythia8/lib
   /usr/local/lib
diff --git a/cmake/modules/RootBuildOptions.cmake b/cmake/modules/RootBuildOptions.cmake
index c5348a7..d8ce468 100644
--- a/cmake/modules/RootBuildOptions.cmake
+++ b/cmake/modules/RootBuildOptions.cmake
@@ -55,78 +55,80 @@ else()
   set(explicitlink_defvalue ON)
 endif()
 
-ROOT_BUILD_OPTION(afs OFF "AFS support, requires AFS libs and objects")                 
-ROOT_BUILD_OPTION(alien ON "AliEn support, requires libgapiUI from ALICE")               
-ROOT_BUILD_OPTION(asimage ON "Image processing support, requires libAfterImage")             
+ROOT_BUILD_OPTION(afdsmgrd OFF "Dataset manager for PROOF-based analysis facilities")
+ROOT_BUILD_OPTION(afs OFF "AFS support, requires AFS libs and objects")
+ROOT_BUILD_OPTION(alien ON "AliEn support, requires libgapiUI from ALICE")
+ROOT_BUILD_OPTION(asimage ON "Image processing support, requires libAfterImage")
 ROOT_BUILD_OPTION(astiff ON "Include tiff support in image processing")
-ROOT_BUILD_OPTION(bonjour ON "Bonjour support, requires libdns_sd and/or Avahi")            
+ROOT_BUILD_OPTION(bonjour ON "Bonjour support, requires libdns_sd and/or Avahi")
 ROOT_BUILD_OPTION(builtin_afterimage OFF "Built included libAfterImage, or use system libAfterImage")
-ROOT_BUILD_OPTION(builtin_ftgl ON "Built included libFTGL, or use system libftgl")        
-ROOT_BUILD_OPTION(builtin_freetype OFF "Built included libfreetype, or use system libfreetype")   
+ROOT_BUILD_OPTION(builtin_ftgl ON "Built included libFTGL, or use system libftgl")
+ROOT_BUILD_OPTION(builtin_freetype OFF "Built included libfreetype, or use system libfreetype")
 ROOT_BUILD_OPTION(builtin_glew ON "Built included libGLEW, or use system libGLEW")
-ROOT_BUILD_OPTION(builtin_pcre OFF "Built included libpcre, or use system libpcre")        
-ROOT_BUILD_OPTION(builtin_zlib OFF "Built included libz, or use system libz")  
-ROOT_BUILD_OPTION(builtin_lzma OFF "Built included liblzma, or use system liblzma")  
-ROOT_BUILD_OPTION(builtin_gsl OFF "Built the GSL library internally (downloading tarfile from the Web)")        
-ROOT_BUILD_OPTION(builtin_cfitsio OFF "Built the FITSIO library internally (downloading tarfile from the Web)")        
-ROOT_BUILD_OPTION(builtin_xrootd OFF "Built the XROOTD internally (downloading tarfile from the Web)")        
-ROOT_BUILD_OPTION(castor ON "CASTOR support, requires libshift from CASTOR >= 1.5.2")             
-ROOT_BUILD_OPTION(chirp ON "Chirp support (Condor remote I/O), requires libchirp_client")               
-ROOT_BUILD_OPTION(cintex ON "Build the libCintex Reflex interface library")              
+ROOT_BUILD_OPTION(builtin_pcre OFF "Built included libpcre, or use system libpcre")
+ROOT_BUILD_OPTION(builtin_zlib OFF "Built included libz, or use system libz")
+ROOT_BUILD_OPTION(builtin_lzma OFF "Built included liblzma, or use system liblzma")
+ROOT_BUILD_OPTION(builtin_gsl OFF "Built the GSL library internally (downloading tarfile from the Web)")
+ROOT_BUILD_OPTION(builtin_cfitsio OFF "Built the FITSIO library internally (downloading tarfile from the Web)")
+ROOT_BUILD_OPTION(builtin_xrootd OFF "Built the XROOTD internally (downloading tarfile from the Web)")
+ROOT_BUILD_OPTION(c++11 OFF "Build using C++11 compatible mode, requires gcc > 4.7.x or clang")
+ROOT_BUILD_OPTION(castor ON "CASTOR support, requires libshift from CASTOR >= 1.5.2")
+ROOT_BUILD_OPTION(chirp ON "Chirp support (Condor remote I/O), requires libchirp_client")
+ROOT_BUILD_OPTION(cintex ON "Build the libCintex Reflex interface library")
 ROOT_BUILD_OPTION(clarens ON "Clarens RPC support, optionally used by PROOF")
 ROOT_BUILD_OPTION(cling ON "Enable new CLING C++ interpreter")
-ROOT_BUILD_OPTION(cocoa OFF "Use native Cocoa/Quartz graphics backend (MacOS X only)")            
-ROOT_BUILD_OPTION(dcache ON "dCache support, requires libdcap from DESY")              
-ROOT_BUILD_OPTION(exceptions ON "Turn on compiler exception handling capability")         
-ROOT_BUILD_OPTION(explicitlink ${explicitlink_defvalue} "Explicitly link with all dependent libraries")      
-ROOT_BUILD_OPTION(fftw3 ON "Fast Fourier Transform support, requires libfftw3") 
-ROOT_BUILD_OPTION(fitsio ON "Read images and data from FITS files, requires cfitsio")                
-ROOT_BUILD_OPTION(gviz ON "Graphs visualization support, requires graphviz")                
-ROOT_BUILD_OPTION(gdml OFF "GDML writer and reader")                
-ROOT_BUILD_OPTION(genvector ON "Build the new libGenVector library" )            
-ROOT_BUILD_OPTION(gfal ON "GFAL support, requires libgfal")        
-ROOT_BUILD_OPTION(glite ON "gLite support, requires libglite-api-wrapper v.3 from GSI (https://subversion.gsi.de/trac/dgrid/wiki)")              
-ROOT_BUILD_OPTION(globus OFF "Globus authentication support, requires Globus toolkit")              
+ROOT_BUILD_OPTION(cocoa OFF "Use native Cocoa/Quartz graphics backend (MacOS X only)")
+ROOT_BUILD_OPTION(dcache ON "dCache support, requires libdcap from DESY")
+ROOT_BUILD_OPTION(exceptions ON "Turn on compiler exception handling capability")
+ROOT_BUILD_OPTION(explicitlink ${explicitlink_defvalue} "Explicitly link with all dependent libraries")
+ROOT_BUILD_OPTION(fftw3 ON "Fast Fourier Transform support, requires libfftw3")
+ROOT_BUILD_OPTION(fitsio ON "Read images and data from FITS files, requires cfitsio")
+ROOT_BUILD_OPTION(gviz ON "Graphs visualization support, requires graphviz")
+ROOT_BUILD_OPTION(gdml OFF "GDML writer and reader")
+ROOT_BUILD_OPTION(genvector ON "Build the new libGenVector library")
+ROOT_BUILD_OPTION(gfal ON "GFAL support, requires libgfal")
+ROOT_BUILD_OPTION(glite ON "gLite support, requires libglite-api-wrapper v.3 from GSI (https://subversion.gsi.de/trac/dgrid/wiki)")
+ROOT_BUILD_OPTION(globus OFF "Globus authentication support, requires Globus toolkit")
 ROOT_BUILD_OPTION(gsl_shared OFF "Enable linking against shared libraries for GSL (default no)")
-ROOT_BUILD_OPTION(hdfs ON "HDFS support; requires libhdfs from HDFS >= 0.19.1")         
-ROOT_BUILD_OPTION(krb5 ON "Kerberos5 support, requires Kerberos libs")               
-ROOT_BUILD_OPTION(ldap ON "LDAP support, requires (Open)LDAP libs")                
-ROOT_BUILD_OPTION(mathmore ON "Build the new libMathMore extended math library, requires GSL (vers. >= 1.8)")            
-ROOT_BUILD_OPTION(memstat ${memstat_defvalue} "A memory statistics utility, helps to detect memory leaks")    
-ROOT_BUILD_OPTION(minuit2 OFF "Build the new libMinuit2 minimizer library")            
-ROOT_BUILD_OPTION(monalisa ON "Monalisa monitoring support, requires libapmoncpp")        
-ROOT_BUILD_OPTION(mysql ON "MySQL support, requires libmysqlclient")              
-ROOT_BUILD_OPTION(odbc ON "ODBC support, requires libiodbc or libodbc")                
-ROOT_BUILD_OPTION(opengl ON "OpenGL support, requires libGL and libGLU")              
-ROOT_BUILD_OPTION(oracle ON "Oracle support, requires libocci")              
-ROOT_BUILD_OPTION(pch ON)   
-ROOT_BUILD_OPTION(peac ON "PEAC, PROOF Enabled Analysis Center, requires Clarens")       
-ROOT_BUILD_OPTION(pgsql ON "PostgreSQL support, requires libpq")               
-ROOT_BUILD_OPTION(pythia6 ON "Pythia6 EG support, requires libPythia6")            
-ROOT_BUILD_OPTION(pythia8 ON "Pythia8 EG support, requires libPythia8")             
-ROOT_BUILD_OPTION(python ON "Python ROOT bindings, requires python >= 2.2")              
-ROOT_BUILD_OPTION(qt OFF "Qt graphics backend, requires libqt >= 4.x")                
-ROOT_BUILD_OPTION(qtgsi OFF "GSI's Qt integration, requires libqt >= 3")               
-ROOT_BUILD_OPTION(reflex ON "Build the libReflex dictionary library")              
-ROOT_BUILD_OPTION(roofit OFF "Build the libRooFit advanced fitting package")              
-ROOT_BUILD_OPTION(ruby OFF "Ruby ROOT bindings, requires ruby >= 1.8")                
-ROOT_BUILD_OPTION(rfio ON "RFIO support, requires libshift from CASTOR >= 1.5.2")                
-ROOT_BUILD_OPTION(rpath OFF "Set run-time library load path on executables and shared libraries (at installation area)")              
-ROOT_BUILD_OPTION(sapdb ON "MaxDB/SapDB support, requires libsqlod and libsqlrte")              
-ROOT_BUILD_OPTION(shadowpw ON "Shadow password support")           
-ROOT_BUILD_OPTION(shared ON "Use shared 3rd party libraries if possible")              
-ROOT_BUILD_OPTION(soversion OFF "Set version number in sonames (recommended)")           
-ROOT_BUILD_OPTION(srp ON "SRP support, requires SRP source tree")       
-ROOT_BUILD_OPTION(ssl ON "SSL encryption support, requires openssl")                
-ROOT_BUILD_OPTION(table OFF "Build libTable contrib library")             
-ROOT_BUILD_OPTION(tmva ON "Build TMVA multi variate analysis library")             
-ROOT_BUILD_OPTION(unuran OFF "UNURAN - package for generating non-uniform random numbers")              
-ROOT_BUILD_OPTION(winrtdebug OFF "Link against the Windows debug runtime library")         
-ROOT_BUILD_OPTION(xft ON "Xft support (X11 antialiased fonts)")                
+ROOT_BUILD_OPTION(hdfs ON "HDFS support; requires libhdfs from HDFS >= 0.19.1")
+ROOT_BUILD_OPTION(krb5 ON "Kerberos5 support, requires Kerberos libs")
+ROOT_BUILD_OPTION(ldap ON "LDAP support, requires (Open)LDAP libs")
+ROOT_BUILD_OPTION(mathmore ON "Build the new libMathMore extended math library, requires GSL (vers. >= 1.8)")
+ROOT_BUILD_OPTION(memstat ${memstat_defvalue} "A memory statistics utility, helps to detect memory leaks")
+ROOT_BUILD_OPTION(minuit2 OFF "Build the new libMinuit2 minimizer library")
+ROOT_BUILD_OPTION(monalisa ON "Monalisa monitoring support, requires libapmoncpp")
+ROOT_BUILD_OPTION(mysql ON "MySQL support, requires libmysqlclient")
+ROOT_BUILD_OPTION(odbc ON "ODBC support, requires libiodbc or libodbc")
+ROOT_BUILD_OPTION(opengl ON "OpenGL support, requires libGL and libGLU")
+ROOT_BUILD_OPTION(oracle ON "Oracle support, requires libocci")
+ROOT_BUILD_OPTION(pch ON)
+ROOT_BUILD_OPTION(peac ON "PEAC, PROOF Enabled Analysis Center, requires Clarens")
+ROOT_BUILD_OPTION(pgsql ON "PostgreSQL support, requires libpq")
+ROOT_BUILD_OPTION(pythia6 ON "Pythia6 EG support, requires libPythia6")
+ROOT_BUILD_OPTION(pythia8 ON "Pythia8 EG support, requires libPythia8")
+ROOT_BUILD_OPTION(python ON "Python ROOT bindings, requires python >= 2.2")
+ROOT_BUILD_OPTION(qt OFF "Qt graphics backend, requires libqt >= 4.x")
+ROOT_BUILD_OPTION(qtgsi OFF "GSI's Qt integration, requires libqt >= 3")
+ROOT_BUILD_OPTION(reflex ON "Build the libReflex dictionary library")
+ROOT_BUILD_OPTION(roofit OFF "Build the libRooFit advanced fitting package")
+ROOT_BUILD_OPTION(ruby OFF "Ruby ROOT bindings, requires ruby >= 1.8")
+ROOT_BUILD_OPTION(rfio ON "RFIO support, requires libshift from CASTOR >= 1.5.2")
+ROOT_BUILD_OPTION(rpath OFF "Set run-time library load path on executables and shared libraries (at installation area)")
+ROOT_BUILD_OPTION(sapdb ON "MaxDB/SapDB support, requires libsqlod and libsqlrte")
+ROOT_BUILD_OPTION(shadowpw ON "Shadow password support")
+ROOT_BUILD_OPTION(shared ON "Use shared 3rd party libraries if possible")
+ROOT_BUILD_OPTION(soversion OFF "Set version number in sonames (recommended)")
+ROOT_BUILD_OPTION(srp ON "SRP support, requires SRP source tree")
+ROOT_BUILD_OPTION(ssl ON "SSL encryption support, requires openssl")
+ROOT_BUILD_OPTION(table OFF "Build libTable contrib library")
+ROOT_BUILD_OPTION(tmva ON "Build TMVA multi variate analysis library")
+ROOT_BUILD_OPTION(unuran OFF "UNURAN - package for generating non-uniform random numbers")
+ROOT_BUILD_OPTION(winrtdebug OFF "Link against the Windows debug runtime library")
+ROOT_BUILD_OPTION(xft ON "Xft support (X11 antialiased fonts)")
 ROOT_BUILD_OPTION(xml ON "XML parser interface")
 ROOT_BUILD_OPTION(x11 ${x11_defvalue} "X11 support")
 ROOT_BUILD_OPTION(xrootd ON "Build xrootd file server and its client (if supported)")
-  
+
 option(fail-on-missing "Fail the configure step if a required external package is missing" OFF)
 option(minimal "Do not automatically search for support libraries" OFF)
 option(gminimal "Do not automatically search for support libraries, but include X11" OFF)
diff --git a/cmake/modules/RootConfiguration.cmake b/cmake/modules/RootConfiguration.cmake
index 4127b80..1129345 100644
--- a/cmake/modules/RootConfiguration.cmake
+++ b/cmake/modules/RootConfiguration.cmake
@@ -325,6 +325,7 @@ set(hasxft ${has${xft}})
 set(hascling ${has${cling}})
 set(haslzmacompression ${has${lzma}})
 set(hascocoa ${has${cocoa}})
+set(usec++11 ${has${c++11}})
 
 #---root-config----------------------------------------------------------------------------------------------
 ROOT_SHOW_OPTIONS(features)
diff --git a/config/Makefile.depend b/config/Makefile.depend
index c350939..9e784e8 100644
--- a/config/Makefile.depend
+++ b/config/Makefile.depend
@@ -490,16 +490,16 @@ ALIENLIBEXTRA           = -Llib -lXMLIO -lNetx -lTree -lProof -lProofPlayer \
 ROOFITCORELIBEXTRA      = -Llib -lHist -lGraf -lMatrix -lTree -lMinuit -lRIO \
                           -lMathCore -lFoam
 ROOFITLIBEXTRA          = -Llib -lRooFitCore -lTree -lRIO -lMatrix -lMathCore
-ifeq ($(BUILDMATHMORE),yes)
-ROOFITLIBEXTRA         += -lMathMore
-ROOSTATSLIBEXTRA       += -lMathMore
-HISTFACTORYLIBEXTRA    += -lMathMore
-endif
 ROOSTATSLIBEXTRA        = -Llib -lRooFit -lRooFitCore -lTree -lRIO -lHist \
                           -lMatrix -lMathCore -lMinuit -lFoam -lGraf -lGpad
 HISTFACTORYLIBEXTRA     = -Llib -lRooFit -lRooFitCore -lTree -lRIO -lHist \
                           -lMatrix -lMathCore -lMinuit -lFoam -lGraf -lGpad \
                           -lRooStats -lXMLParser
+ifeq ($(BUILDMATHMORE),yes)
+ROOFITLIBEXTRA         += -lMathMore
+ROOSTATSLIBEXTRA       += -lMathMore
+HISTFACTORYLIBEXTRA    += -lMathMore
+endif
 CINTEXLIBEXTRA          = -Llib -lReflex
 REFLEXDICTLIBEXTRA      = -Llib -lReflex
 RAUTHLIBEXTRA           = -Llib -lNet -lRIO
diff --git a/config/Makefile.in b/config/Makefile.in
index 291c433..ff8d066 100644
--- a/config/Makefile.in
+++ b/config/Makefile.in
@@ -59,6 +59,8 @@ XFTLIB         := @enable_xft@
 
 BUILDCOCOA     := @buildcocoa@
 
+CXX11          := @c++11@
+
 EXPLICITLINK   := @explicitlink@
 
 ENABLETHREAD   := @enable_thread@
diff --git a/config/Makefile.linux b/config/Makefile.linux
index 20544d5..53b3246 100644
--- a/config/Makefile.linux
+++ b/config/Makefile.linux
@@ -13,18 +13,18 @@ else
 OPT           = $(OPTFLAGS)
 NOOPT         =
 endif
-ifeq (c++11,$(findstring c++11,$(ROOTBUILD)))
-CXX11         = -std=c++11
+ifeq ($(CXX11),yes)
+CXX11FLAGS    = -std=c++11 -Wno-deprecated-declarations
 endif
 
 # Compiler:
 CXX           = g++
 CC            = gcc
 CXXFLAGS      = -pipe -m32 -Wall -W -Woverloaded-virtual \
-                -fPIC $(EXTRA_CXXFLAGS) $(CXX11)
+                -fPIC $(EXTRA_CXXFLAGS) $(CXX11FLAGS)
 CFLAGS        = -pipe -m32 -Wall -W -fPIC $(EXTRA_CFLAGS)
 CINTCXXFLAGS  = -pipe -m32 -Wall -W -Woverloaded-virtual \
-                -fPIC $(EXTRA_CXXFLAGS) $(CXX11) \
+                -fPIC $(EXTRA_CXXFLAGS) $(CXX11FLAGS) \
                 -DG__REGEXP -DG__UNIX -DG__SHAREDLIB \
                 -DG__OSFDLL -DG__ROOT -DG__REDIRECTIO \
                 -DG__STD_EXCEPTION
diff --git a/config/Makefile.linuxx8664gcc b/config/Makefile.linuxx8664gcc
index 6601892..f2f483c 100644
--- a/config/Makefile.linuxx8664gcc
+++ b/config/Makefile.linuxx8664gcc
@@ -16,18 +16,18 @@ else
 OPT           = $(OPTFLAGS)
 NOOPT         =
 endif
-ifeq (c++11,$(findstring c++11,$(ROOTBUILD)))
-CXX11         = -std=c++11
+ifeq ($(CXX11),yes)
+CXX11FLAGS    = -std=c++11 -Wno-deprecated-declarations
 endif
 
 # Compiler:
 CXX           = g++
 CC            = gcc
 CXXFLAGS      = -pipe -m64 -Wshadow -Wall -W -Woverloaded-virtual \
-                -fPIC $(EXTRA_CXXFLAGS) $(CXX11)
+                -fPIC $(EXTRA_CXXFLAGS) $(CXX11FLAGS)
 CFLAGS        = -pipe -m64 -Wshadow -Wall -W -fPIC $(EXTRA_CFLAGS)
 CINTCXXFLAGS  = -pipe -m64 -Wall -W -Woverloaded-virtual \
-                -fPIC $(EXTRA_CXXFLAGS) $(CXX11) \
+                -fPIC $(EXTRA_CXXFLAGS) $(CXX11FLAGS) \
                 -DG__REGEXP -DG__UNIX -DG__SHAREDLIB \
                 -DG__OSFDLL -DG__ROOT -DG__REDIRECTIO \
                 -DG__STD_EXCEPTION -DG__64BIT
diff --git a/config/Makefile.macosx b/config/Makefile.macosx
index 5f52d6f..2c882d4 100644
--- a/config/Makefile.macosx
+++ b/config/Makefile.macosx
@@ -38,8 +38,8 @@ endif
 ifeq ($(subst $(APPLE_CLANG),,12),12)
 CXX           = clang++
 CC            = clang
-ifeq (c++11,$(findstring c++11,$(ROOTBUILD)))
-CXX11         = -std=c++11
+ifeq ($(CXX11),yes)
+CXX11FLAGS    = -std=c++11
 endif
 else
 CXX           = g++
@@ -47,14 +47,14 @@ CC            = gcc
 endif
 CXXFLAGS      = -m32 -pipe -Wshadow -W -Wall -Woverloaded-virtual \
                 -fsigned-char -fno-common $(EXTRA_CXXFLAGS) $(FINK_CXXFLAGS) \
-                $(TARGETFLAGS)
+                $(TARGETFLAGS) $(CXX11FLAGS)
 CFLAGS        = -m32 -pipe -Wshadow -W -Wall -fsigned-char -fno-common \
                 $(EXTRA_CFLAGS) $(FINK_CFLAGS) $(TARGETFLAGS)
 CINTCXXFLAGS  = -m32 -pipe -W -Wall -Woverloaded-virtual \
                 -fsigned-char -fno-common $(EXTRA_CXXFLAGS) $(FINK_CXXFLAGS) \
                 -DG__REGEXP -DG__UNIX -DG__SHAREDLIB \
                 -DG__ROOT -DG__REDIRECTIO -DG__OSFDLL \
-                -DG__STD_EXCEPTION $(TARGETFLAGS)
+                -DG__STD_EXCEPTION $(TARGETFLAGS) $(CXX11FLAGS)
 CINTCFLAGS    = -m32 -pipe -W -Wall -fsigned-char -fno-common \
                 $(EXTRA_CFLAGS) $(FINK_CFLAGS) \
                 -DG__REGEXP -DG__UNIX -DG__SHAREDLIB \
diff --git a/config/Makefile.macosx64 b/config/Makefile.macosx64
index 5e0762e..83bedeb 100644
--- a/config/Makefile.macosx64
+++ b/config/Makefile.macosx64
@@ -38,8 +38,8 @@ endif
 ifeq ($(subst $(APPLE_CLANG),,12),12)
 CXX           = clang++
 CC            = clang
-ifeq (c++11,$(findstring c++11,$(ROOTBUILD)))
-CXX11         = -std=c++11
+ifeq ($(CXX11),yes)
+CXX11FLAGS    = -std=c++11
 endif
 else
 CXX           = g++
@@ -47,14 +47,14 @@ CC            = gcc
 endif
 CXXFLAGS      = -m64 -pipe -Wshadow -W -Wall -Woverloaded-virtual \
                 -fsigned-char -fno-common $(EXTRA_CXXFLAGS) $(FINK_CXXFLAGS) \
-                $(TARGETFLAGS) $(CXX11)
+                $(TARGETFLAGS) $(CXX11FLAGS)
 CFLAGS        = -m64 -pipe -Wshadow -W -Wall -fsigned-char -fno-common \
                 $(EXTRA_CFLAGS) $(FINK_CFLAGS) $(TARGETFLAGS)
 CINTCXXFLAGS  = -m64 -pipe -W -Wall -Woverloaded-virtual \
                 -fsigned-char -fno-common $(EXTRA_CXXFLAGS) $(FINK_CXXFLAGS) \
                 -DG__REGEXP -DG__UNIX -DG__SHAREDLIB \
                 -DG__ROOT -DG__REDIRECTIO -DG__OSFDLL \
-                -DG__STD_EXCEPTION $(TARGETFLAGS) $(CXX11)
+                -DG__STD_EXCEPTION $(TARGETFLAGS) $(CXX11FLAGS)
 CINTCFLAGS    = -m64 -pipe -W -Wall -fsigned-char -fno-common \
                 $(EXTRA_CFLAGS) $(FINK_CFLAGS) \
                 -DG__REGEXP -DG__UNIX -DG__SHAREDLIB \
diff --git a/config/RConfigure.in b/config/RConfigure.in
index 1a46b84..3c92561 100644
--- a/config/RConfigure.in
+++ b/config/RConfigure.in
@@ -24,5 +24,6 @@
 #@hasxft@ R__HAS_XFT    /**/
 #@hascling@ R__HAS_CLING   /**/
 #@hascocoa@ R__HAS_COCOA    /**/
+#@usec++11@ R__USE_CXX11    /**/
 
 #endif
diff --git a/config/root-config.in b/config/root-config.in
index 5618305..a1dd9dd 100755
--- a/config/root-config.in
+++ b/config/root-config.in
@@ -445,10 +445,10 @@ freebsd* | openbsd* | linux*)
       if test "x$f" = "xrpath" ; then
          auxlibs="-Wl,-rpath,$libdir $auxlibs"
       fi
+      if test "x$f" = "xcxx11" ; then
+         auxcflags="-std=c++11 -Wno-deprecated-declarations $auxcflags"
+      fi
    done
-   if echo $configargs | grep 'c++11' > /dev/null 2>& 1 ; then
-      auxcflags="-std=c++11 $auxcflags"
-   fi
    ;;
 macosx*)
    for f in $features ; do
@@ -466,10 +466,10 @@ macosx*)
             auxlibs="-Wl,-rpath,$libdir $auxlibs"
          fi
       fi
+      if test "x$f" = "xcxx11" ; then
+         auxcflags="-std=c++11 $auxcflags"
+      fi
    done
-   if echo $configargs | grep 'c++11' > /dev/null 2>& 1 ; then
-      auxcflags="-std=c++11 $auxcflags"
-   fi
    ;;
 hpuxacc | hpuxia64acc)
    for f in $features ; do
diff --git a/configure b/configure
index 40ac87d..769ee8a 100755
--- a/configure
+++ b/configure
@@ -50,6 +50,7 @@ options="                    \
    enable_builtin_pcre       \
    enable_builtin_zlib       \
    enable_builtin_lzma       \
+   enable_cxx11              \
    enable_castor             \
    enable_chirp              \
    enable_cintex             \
@@ -138,6 +139,7 @@ for c in $options $deprecated_options; do
 done
 for c in $options ; do eval ${c}_explicit="" ; done
 
+enable_cxx11=no
 enable_cling=no
 enable_cocoa=no
 enable_afs=no
@@ -873,6 +875,48 @@ EOF
 }
 
 #_____________________________________________________________________
+check_cxxopt() {
+    # This function will try to compile with a specific cxx compiler
+    # option [$1]. The result of the check is stored in cxxopt_result,
+    # 1 if true, 0 otherwise, which should be immediately copied,
+    # since the variable will be overwritten at next invocation
+    # of this function.
+
+    # Assert that we got enough arguments
+    if test $# -lt 1 ; then
+        echo "check_compopt: need at least one argument"
+        cxxopt_result=0
+        return 1
+    fi
+
+    # save arguments in logical names
+    cxxopt="$1"; shift
+
+    logmsg " trying to compile with option $cxxopt"
+    cat <<EOF > conftest.mk
+include ${ac_srcdir}/config/Makefile.${arch}
+conftest: conftest.cxx
+	\$(CXX) \$(CFLAGS) $cxxopt \$(LDFLAGS) \$< -o \$@
+
+conftest.cxx:
+	echo "int main() { return 0; }" > \$@
+EOF
+
+    $gnumake -f conftest.mk >> $logfile 2>&1
+    if test $? -eq 0 ; then
+        cxxopt_result=1
+        logmsg " Compilation OK"
+    else
+        cxxopt_result=0
+        logmsg " Failed code was"
+        cat conftest.mk >> $logfile
+    fi
+    rm -rf conftest.cxx conftest.mk conftest conftest.dSYM
+
+    unset cxxopt
+}
+
+#_____________________________________________________________________
 check_symbol() {
     # This function will try to locate a symbol [$1] in a specific
     # library [$2] and in a given directory [$3].
@@ -1407,7 +1451,7 @@ FIRST argument one of the architecures given at the end of this message.
    FLAG            DESCRIPTION               DEFAULT
    --aclocaldir    Autoconf macro install dir(<prefix>/share/aclocal)
    --bindir        Binary installation dir   (<prefix>/bin)
-   --build         Build configuration [debug, c++11, ...],
+   --build         Build configuration [debug, ...],
                    overrides the ROOTBUILD shell variable
    --cintincdir    CINT interpeted headers   (<libdir>/cint)
    --datadir       Data installation dir     (<prefix>/share/root)
@@ -1446,6 +1490,7 @@ enable/disable options, prefix with either --enable- or --disable-
   builtin-pcre       Built included libpcre, or use system libpcre
   builtin-zlib       Built included libz, or use system libz
   builtin-lzma       Built included liblzma, or use system liblzma
+  c++11              Build using C++11 compatible mode, requires gcc > 4.7.x or clang
   castor             CASTOR support, requires libshift from CASTOR >= 1.5.2
   chirp              Chirp filesystem support, requires cctools >= 3.2.2
   cintex             Build the libCintex Reflex interface library
@@ -1948,7 +1993,7 @@ if test $# -gt 0 ; then
       # features
       #
       --enable-*)
-        f=`echo $1 | sed -e 's/--//' -e 's/-/_/g'`
+        f=`echo $1 | sed -e 's/--//' -e 's/-/_/g' -e 's/++11/xx11/'`
         eval prev='$'`echo ${f}`
         eval prev_expl='$'`echo ${f}_explicit`
         if test "${prev}:${prev_expl}" = "yes:"; then
@@ -1977,7 +2022,7 @@ if test $# -gt 0 ; then
         fi
         ;;
       --disable-*)
-        f=`echo $1 | sed -e 's/--disable/enable/' -e 's/-/_/g'`
+        f=`echo $1 | sed -e 's/--disable/enable/' -e 's/-/_/g' -e 's/++11/xx11/'`
         eval prev='$'`echo ${f}`
         eval prev_expl='$'`echo ${f}_explicit`
         if test "${prev}:${prev_expl}" = "xno:"; then
@@ -2081,28 +2126,32 @@ fi
 #
 ### echo %%% Check for Fink or MacPorts on Mac OS X
 #
-message "Checking for Fink/MacPorts directory"
-if test "x$platform" = "xmacosx" -a "x$enable_fink" = "xyes"; then
-    if test -d "$finkdir"; then
-        # User specified a directory with --with-finkdir=...
-        logmsg "Using user-specified Fink directory"
-        logmsg "$finkdir"
-    else
-        # Fink has precedence over MacPorts
-        logmsg "Checking Fink directory"
-        finkdir=`$cwhich fink 2>&1 | sed -ne "s/\/bin\/fink//p"`
-        logmsg "$finkdir"
-
-        if test "x$finkdir" = "x"; then
-            logmsg "Checking MacPorts directory"
-            finkdir=`$cwhich port 2>&1 | sed -ne "s/\/bin\/port//p"`
+if test "x$platform" = "xmacosx"; then
+    message "Checking for Fink/MacPorts directory"
+    if test "x$enable_fink" = "xyes"; then
+        if test -d "$finkdir"; then
+            # User specified a directory with --with-finkdir=...
+            logmsg "Using user-specified Fink directory"
+            logmsg "$finkdir"
+        else
+            # Fink has precedence over MacPorts
+            logmsg "Checking Fink directory"
+            finkdir=`$cwhich fink 2>&1 | sed -ne "s/\/bin\/fink//p"`
             logmsg "$finkdir"
+
+            if test "x$finkdir" = "x"; then
+                logmsg "Checking MacPorts directory"
+                finkdir=`$cwhich port 2>&1 | sed -ne "s/\/bin\/port//p"`
+                logmsg "$finkdir"
+            fi
         fi
+        result "$finkdir"
+    else
+        logmsg "Fink/MacPorts disabled"
+        result "disabled"
     fi
-    result "$finkdir"
 else
-    logmsg "Fink/MacPorts disabled"
-    result "disabled"
+    enable_fink="no"
 fi
 
 ######################################################################
@@ -2253,6 +2302,24 @@ fi
 
 ######################################################################
 #
+### echo %%% C++11 - compile using c++11 compatible option
+#
+# needs gcc > 4.7.x or clang
+usecxx11="undef"
+if test "x$enable_cxx11" = "xyes"; then
+    message "Checking whether c++11 mode is supported"
+    check_cxxopt -std=c++11
+    if test $cxxopt_result -eq 0 ; then
+        enable_cxx11="no"
+	result "no"
+    else
+	usecxx11="define"
+	result "yes"
+    fi
+fi
+
+######################################################################
+#
 ### echo %%% Check if native MacOS X Cocoa/Quartz backend should be build
 #
 if test ! "x$platform" = "xmacosx"; then
@@ -6716,6 +6783,7 @@ sed -e "s|@srcdir@|$ac_srcdir|"                 \
     -e "s|@afdsmgrdapmon@|$afdsmgrdapmon|"      \
     -e "s|@buildglite@|$enable_glite|"          \
     -e "s|@buildcocoa@|$enable_cocoa|"          \
+    -e "s|@c++11@|$enable_cxx11|"               \
     < Makefile.tmp > $MAKEOUT
 rm -f Makefile.tmp
 
@@ -6768,6 +6836,7 @@ sed \
     -e "s|@hasxft@|$hasxft|"               \
     -e "s|@hascling@|$hascling|"           \
     -e "s|@hascocoa@|$hascocoa|"           \
+    -e "s|@usec++11@|$usecxx11|"           \
     < RConfigure.tmp > RConfigure-out.tmp
 rm -f RConfigure.tmp
 
diff --git a/core/base/inc/RVersion.h b/core/base/inc/RVersion.h
index 3d09cd3..f85da01 100644
--- a/core/base/inc/RVersion.h
+++ b/core/base/inc/RVersion.h
@@ -14,11 +14,11 @@
  *
 */
 
-#define ROOT_RELEASE "5.34/00-rc1"
-#define ROOT_RELEASE_DATE "May  7 2012"
-#define ROOT_RELEASE_TIME "15:01:57"
-#define ROOT_SVN_REVISION 44153
-#define ROOT_SVN_BRANCH "trunk"
+#define ROOT_RELEASE "5.34/00"
+#define ROOT_RELEASE_DATE "Jun  5 2012"
+#define ROOT_RELEASE_TIME "15:17:17"
+#define ROOT_SVN_REVISION 44555
+#define ROOT_SVN_BRANCH "branches/v5-34-00-patches"
 #define ROOT_VERSION_CODE 336384
 #define ROOT_VERSION(a,b,c) (((a) << 16) + ((b) << 8) + (c))
 
diff --git a/core/base/src/TBenchmark.cxx b/core/base/src/TBenchmark.cxx
index af1092b..e5d99f5 100644
--- a/core/base/src/TBenchmark.cxx
+++ b/core/base/src/TBenchmark.cxx
@@ -16,20 +16,18 @@ TBenchmark *gBenchmark = 0;
 
 ClassImp(TBenchmark)
 
-//______________________________________________________________________________
 //////////////////////////////////////////////////////////////////////////
-//
-// This class is a ROOT utility to help benchmarking applications
-//
-//  Examples of use of this class are given in the tutorials macros.
+//                                                                      //
+// TBenchmark                                                           //
+//                                                                      //
+// This class is a ROOT utility to help benchmarking applications       //
+//                                                                      //
 //////////////////////////////////////////////////////////////////////////
 
-
 //______________________________________________________________________________
 TBenchmark::TBenchmark(): TNamed()
 {
-//*-*-*-*-*-*-*-*-*-*-*Benchmark default constructor*-*-*-*-*-*-*-*-*-*-*-*-*-*
-//*-*                  =============================
+   // Benchmark default constructor
 
    fNbench   = 0;
    fNmax     = 20;
@@ -49,7 +47,8 @@ TBenchmark::TBenchmark(const TBenchmark& bm) :
   fCpuTime(0),
   fTimer(0)
 { 
-   //copy constructor
+   // Copy constructor.
+   
    fNames    = new TString[fNmax];
    fRealTime = new Float_t[fNmax];
    fCpuTime  = new Float_t[fNmax];
@@ -66,8 +65,9 @@ TBenchmark::TBenchmark(const TBenchmark& bm) :
 //______________________________________________________________________________
 TBenchmark& TBenchmark::operator=(const TBenchmark& bm)
 {
-   //assignment operator
-   if(this!=&bm) {
+   // Assignment operator.
+   
+   if (this!=&bm) {
       TNamed::operator=(bm);
       fNbench=bm.fNbench;
       fNmax=bm.fNmax;
@@ -95,8 +95,7 @@ TBenchmark& TBenchmark::operator=(const TBenchmark& bm)
 //______________________________________________________________________________
 TBenchmark::~TBenchmark()
 {
-//*-*-*-*-*-*-*-*-*-*-*Benchmark default destructor*-*-*-*-*-*-*-*-*-*-*-*-*-*
-//*-*                  ============================
+   // Benchmark destructor.
 
    fNbench   = 0;
    if (fNames)    { delete [] fNames;    fNames  = 0;}
@@ -108,8 +107,7 @@ TBenchmark::~TBenchmark()
 //______________________________________________________________________________
 Int_t TBenchmark::GetBench(const char *name) const
 {
-//*-*-*-*-*-*-*-*-*-*-*Returns index of Benchmark name*-*-*-*-*-*-*-*
-//*-*                  ===============================
+   // Returns index of Benchmark name.
 
    for (Int_t i=0;i<fNbench;i++) {
       if (!strcmp(name,(const char*)fNames[i])) return i;
@@ -120,8 +118,7 @@ Int_t TBenchmark::GetBench(const char *name) const
 //______________________________________________________________________________
 Float_t TBenchmark::GetCpuTime(const char *name)
 {
-//*-*-*-*-*-*-*-*-*-*-*Returns Cpu time used by Benchmark name*-*-*-*-*-*-*-*
-//*-*                  =======================================
+   // Returns Cpu time used by Benchmark name.
 
    Int_t bench = GetBench(name);
    if (bench >= 0) return fCpuTime[bench];
@@ -131,8 +128,7 @@ Float_t TBenchmark::GetCpuTime(const char *name)
 //______________________________________________________________________________
 Float_t TBenchmark::GetRealTime(const char *name)
 {
-//*-*-*-*-*-*-*-*-*-*-*Returns Realtime used by Benchmark name*-*-*-*-*-*-*-*
-//*-*                  =======================================
+   // Returns Realtime used by Benchmark name.
 
    Int_t bench = GetBench(name);
    if (bench >= 0) return fRealTime[bench];
@@ -142,8 +138,7 @@ Float_t TBenchmark::GetRealTime(const char *name)
 //______________________________________________________________________________
 void TBenchmark::Print(const char *name) const
 {
-//*-*-*-*-*-*-*-*-*-*-*Prints parameters of Benchmark name*-*-*-*-*-*-*-*-*-*
-//*-*                  ===================================
+   // Prints parameters of Benchmark name.
 
    Int_t bench = GetBench(name);
    if (bench < 0) return;
@@ -153,18 +148,15 @@ void TBenchmark::Print(const char *name) const
 //______________________________________________________________________________
 void TBenchmark::Reset()
 {
-//*-*-*-*-*-*-*-*-*-*-*-*-*-*Reset all Benchmarks*-*-*-*-*-*-*-*-*-*-*-*-*
-//*-*                        ====================
+   // Reset all Benchmarks
 
    fNbench = 0;
-
 }
 
 //______________________________________________________________________________
 void TBenchmark::Show(const char *name)
 {
-//*-*-*-*-*-*-*-*-*Stops Benchmark name and Prints results*-*-*-*-*-*-*-*-*-*
-//*-*              =======================================
+   // Stops Benchmark name and Prints results
 
    Stop(name);
    Print((char*)name);
@@ -173,18 +165,16 @@ void TBenchmark::Show(const char *name)
 //______________________________________________________________________________
 void TBenchmark::Start(const char *name)
 {
-//*-*-*-*-*-*-*-*-*-*-*-*-*-*-*Starts Benchmark name*-*-*-*-*-*-*-*-*-*
-//*-*                          =====================
-//*-*
-//*-*   An independent timer (see class TStopwatch) is started.
-//*-*   the name of the benchmark is entered into the list of benchmarks.
-//*-*   Benchmark can be stopped via TBenchmark::Stop
-//*-*   Results can be printed via TBenchmark::Print
-//*-*   TBenchmark::Show can be used to stop benchmark and print results.
-//*-*   If name is an already existing benchmark, existing parameters are reset.
-//*-*   A summary of all benchmarks can be seen via TBenchmark::Summary.
-//*-*
-//*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-**-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*
+   // Starts Benchmark with the specified name.
+   //
+   // An independent timer (see class TStopwatch) is started.
+   // The name of the benchmark is entered into the list of benchmarks.
+   // Benchmark can be stopped via TBenchmark::Stop().
+   // Results can be printed via TBenchmark::Print().
+   // TBenchmark::Show() can be used to stop benchmark and print results.
+   // If name is an already existing benchmark, timing will resume.
+   // A summary of all benchmarks can be seen via TBenchmark::Summary().
+
    if (!fNames) {
       fNames    = new TString[fNmax];
       fRealTime = new Float_t[fNmax];
@@ -193,7 +183,7 @@ void TBenchmark::Start(const char *name)
    }
    Int_t bench = GetBench(name);
    if (bench < 0 && fNbench < fNmax ) {
-   // define a new benchmark to Start
+      // define a new benchmark to Start
       fNames[fNbench] = name;
       bench = fNbench;
       fNbench++;
@@ -201,20 +191,18 @@ void TBenchmark::Start(const char *name)
       fTimer[bench].Start();
       fRealTime[bench] = 0;
       fCpuTime[bench]  = 0;
-   } else if (bench >=0) {
-   // Resume the existen benchmark
+   } else if (bench >= 0) {
+      // Resume the existing benchmark
       fTimer[bench].Continue();
    }
    else
-      Warning("Start","too many benches");
-
+      Warning("Start","too many benchemarks");
 }
 
 //______________________________________________________________________________
 void TBenchmark::Stop(const char *name)
 {
-//*-*-*-*-*-*-*-*-*-*-*Terminates Benchmark name*-*-*-*-*-*-*-*-*-*-*-*
-//*-*                  =========================
+   // Terminates Benchmark with specified name.
 
    Int_t bench = GetBench(name);
    if (bench < 0) return;
@@ -222,14 +210,12 @@ void TBenchmark::Stop(const char *name)
    fTimer[bench].Stop();
    fRealTime[bench] = fTimer[bench].RealTime();
    fCpuTime[bench]  = fTimer[bench].CpuTime();
-
 }
 
 //______________________________________________________________________________
 void TBenchmark::Summary(Float_t &rt, Float_t &cp)
 {
-//*-*-*-*-*-*-*-*-*-*-*-*-*-*Prints a summary of all benchmarks*-*-*-*-*-*-*-*
-//*-*                        ==================================
+   // Prints a summary of all benchmarks.
 
    rt = 0;
    cp = 0;
@@ -239,5 +225,4 @@ void TBenchmark::Summary(Float_t &rt, Float_t &cp)
       cp += fCpuTime[i];
    }
    Printf("%-10s: Real Time = %6.2f seconds Cpu Time = %6.2f seconds","TOTAL",rt,cp);
-
 }
diff --git a/core/macosx/src/TMacOSXSystem.mm b/core/macosx/src/TMacOSXSystem.mm
index 8a5608f..5b538ca 100644
--- a/core/macosx/src/TMacOSXSystem.mm
+++ b/core/macosx/src/TMacOSXSystem.mm
@@ -1,4 +1,4 @@
-// @(#)root/graf2d:$Id: TMacOSXSystem.mm 44061 2012-05-02 08:26:29Z tpochep $
+// @(#)root/graf2d:$Id: TMacOSXSystem.mm 44457 2012-06-01 13:36:30Z tpochep $
 // Author: Timur Pocheptsov 5/12/2011
 
 /*************************************************************************
@@ -85,8 +85,8 @@ namespace Detail {
 class MacOSXSystem {
 public:
    enum DescriptorType {
-      write,
-      read
+      kDTWrite,
+      kDTRead
    };
 
    MacOSXSystem();
@@ -170,7 +170,7 @@ void MacOSXSystem::AddFileHandler(TFileHandler *fh)
    assert(fh != 0 && "AddFileHandler, fh parameter is null");
    assert(fFileDescriptors.find(fh->GetFd()) == fFileDescriptors.end() && "AddFileHandler, file descriptor was registered already");
 
-   fFileDescriptors[fh->GetFd()] = fh->HasReadInterest() ? read : write;
+   fFileDescriptors[fh->GetFd()] = fh->HasReadInterest() ? kDTRead : kDTWrite;
 }
 
 //______________________________________________________________________________
@@ -194,7 +194,7 @@ bool MacOSXSystem::SetFileDescriptors()
 
    try {
       for (std::map<int, DescriptorType>::iterator fdIter = fFileDescriptors.begin(), end = fFileDescriptors.end(); fdIter != end; ++fdIter) {
-         const bool read = fdIter->second == read;
+         const bool read = fdIter->second == kDTRead;
          CFFileDescriptorRef fdref = CFFileDescriptorCreate(kCFAllocatorDefault, fdIter->first, false, read ? TMacOSXSystem_ReadCallback : TMacOSXSystem_WriteCallback, 0);
 
          if (!fdref)
@@ -279,7 +279,7 @@ void TMacOSXSystem::ProcessApplicationDefinedEvent(void *e)
    } else {
       std::map<int, Private::MacOSXSystem::DescriptorType>::iterator fdIter = fPimpl->fFileDescriptors.find(event.data1);
       assert(fdIter != fPimpl->fFileDescriptors.end() && "WaitForAllEvents, file descriptor from NSEvent not found");
-      if (fdIter->second == Private::MacOSXSystem::read)
+      if (fdIter->second == Private::MacOSXSystem::kDTRead)
          fReadready->Set(event.data1);
       else
          fWriteready->Set(event.data1);
diff --git a/core/textinput/src/textinput/Editor.cpp b/core/textinput/src/textinput/Editor.cpp
index 070f184..5f1165f 100644
--- a/core/textinput/src/textinput/Editor.cpp
+++ b/core/textinput/src/textinput/Editor.cpp
@@ -143,6 +143,8 @@ namespace textinput {
 
   void
   Editor::CancelSpecialInputMode(Range& DisplayR) {
+    // Stop incremental history search, leaving text at the
+    // history line currently selected.
     if (fMode == kInputMode) return;
     fContext->GetKeyBinding()->EnableEscCmd(false);
     SetEditorPrompt(Text());
@@ -150,6 +152,16 @@ namespace textinput {
     fMode = kInputMode;
   }
 
+  void
+  Editor::CancelAndRevertSpecialInputMode(EditorRange& R) {
+    // Stop incremental history search, reset text to what it was
+    // before search started.
+    if (fMode == kInputMode) return;
+    CancelSpecialInputMode(R.fDisplay);
+    // Original line should be top of undo buffer.
+    ProcessCommand(kCmdUndo, R);
+  }
+
   Editor::EProcessResult
   Editor::ProcessChar(char C, EditorRange& R) {
     if (C < 32) return kPRError;
@@ -186,6 +198,14 @@ namespace textinput {
 
   Editor::EProcessResult
   Editor::ProcessMove(EMoveID M, EditorRange &R) {
+    if (fMode == kHistSearchMode) {
+       if (M == kMoveRight) {
+          // ^G, i.e. cancel hist search and revert original line.
+          CancelAndRevertSpecialInputMode(R);
+          return kPRSuccess;
+       }
+    }
+
     ClearPasteBuf();
     CancelSpecialInputMode(R.fDisplay);
 
@@ -407,6 +427,7 @@ namespace textinput {
         ProcessMove(kMoveEnd, R);
         return kPRSuccess;
       case kCmdReverseSearch:
+        PushUndo();
         fMode = kHistSearchMode;
         fSearch.clear();
         SetReverseHistSearchPrompt(R.fDisplay);
diff --git a/core/textinput/src/textinput/Editor.h b/core/textinput/src/textinput/Editor.h
index a5d2ff2..a95b6ae 100644
--- a/core/textinput/src/textinput/Editor.h
+++ b/core/textinput/src/textinput/Editor.h
@@ -127,6 +127,7 @@ namespace textinput {
     const Text& GetEditorPrompt() const { return fEditorPrompt; }
     void SetEditorPrompt(const Text& EP) { fEditorPrompt = EP; }
     void CancelSpecialInputMode(Range& DisplayR);
+    void CancelAndRevertSpecialInputMode(EditorRange& R);
 
   private:
     EProcessResult ProcessChar(char C, EditorRange& R);
diff --git a/core/textinput/src/textinput/TerminalDisplay.cpp b/core/textinput/src/textinput/TerminalDisplay.cpp
index 94d61d2..a54529c 100644
--- a/core/textinput/src/textinput/TerminalDisplay.cpp
+++ b/core/textinput/src/textinput/TerminalDisplay.cpp
@@ -25,8 +25,6 @@
 #include "textinput/Text.h"
 #include "textinput/Editor.h"
 
-#include <cstring>
-
 namespace textinput {
   TerminalDisplay::~TerminalDisplay() {}
 
@@ -215,9 +213,8 @@ namespace textinput {
       // Any prompt update means we'll have to re-write the text
       Offset = 0;
       Requested = (size_t) -1;
-    } else {
-      Move(IndexToPos(PromptLen + EditorPromptLen + Offset));
     }
+    Move(IndexToPos(PromptLen + EditorPromptLen + Offset));
 
     size_t avail = 0;
     if (hidden) {
diff --git a/etc/svninfo.txt b/etc/svninfo.txt
index 417b5b1..42472fe 100644
--- a/etc/svninfo.txt
+++ b/etc/svninfo.txt
@@ -1,3 +1,3 @@
 branches/v5-34-00-patches
-44178
-May 08 2012, 17:30:42
+44569
+Jun 05 2012, 15:31:56
diff --git a/graf2d/cocoa/inc/CocoaPrivate.h b/graf2d/cocoa/inc/CocoaPrivate.h
index 9206749..7800b63 100644
--- a/graf2d/cocoa/inc/CocoaPrivate.h
+++ b/graf2d/cocoa/inc/CocoaPrivate.h
@@ -1,4 +1,4 @@
-// @(#)root/graf2d:$Id: CocoaPrivate.h 44026 2012-04-30 09:32:25Z tpochep $
+// @(#)root/graf2d:$Id: CocoaPrivate.h 44330 2012-05-29 11:30:29Z tpochep $
 // Author: Timur Pocheptsov   29/11/2011
 
 /*************************************************************************
@@ -74,6 +74,9 @@ private:
    NSObject<X11Window>   *GetWindow(unsigned windowID)const;
    void                   DeleteDrawable(unsigned drawableID);
    
+   ULong_t                RegisterGLContextForView(unsigned viewID);
+   NSObject<X11Window>   *GetWindowForGLContext(Handle_t glContextID);
+   
    //This function resets strong reference, if you still want NSObject for drawableID to live,
    //you have to retain the pointer (probably) and also drawableID will become id for nsObj (replacement).
    void               ReplaceDrawable(unsigned drawableID, NSObject *nsObj);
@@ -97,6 +100,9 @@ private:
    std::map<unsigned, Util::NSStrongReference<NSObject<X11Drawable> > > fDrawables;
    typedef std::map<unsigned, Util::NSStrongReference<NSObject<X11Drawable> > >::iterator drawable_iterator;
    typedef std::map<unsigned, Util::NSStrongReference<NSObject<X11Drawable> > >::const_iterator const_drawable_iterator;
+   
+   std::map<ULong_t, unsigned> fGLContextMap;
+   ULong_t fFreeGLContextID;
 };
 
 }//Details
diff --git a/graf2d/cocoa/inc/QuartzPixmap.h b/graf2d/cocoa/inc/QuartzPixmap.h
index bd54c90..25aa1e6 100644
--- a/graf2d/cocoa/inc/QuartzPixmap.h
+++ b/graf2d/cocoa/inc/QuartzPixmap.h
@@ -1,4 +1,4 @@
-// @(#)root/graf2d:$Id: QuartzPixmap.h 43898 2012-04-23 09:32:53Z tpochep $
+// @(#)root/graf2d:$Id: QuartzPixmap.h 44330 2012-05-29 11:30:29Z tpochep $
 // Author: Timur Pocheptsov   16/02/2012
 
 /*************************************************************************
@@ -60,14 +60,21 @@
 //                                                     //
 /////////////////////////////////////////////////////////
 
+//TODO: split image and mask image?
+
 @interface QuartzImage : NSObject<X11Drawable>
 
 - (id) initWithW : (unsigned) width H : (unsigned) height data : (unsigned char *) data;
 - (id) initMaskWithW : (unsigned) width H : (unsigned) height bitmapMask : (unsigned char *) mask;
+- (id) initMaskWithW : (unsigned) width H : (unsigned) height;
+
 - (void) dealloc;
 @property (nonatomic, readonly) BOOL fIsStippleMask;
 - (CGImageRef) fImage;
 
+- (void) clearMask;
+- (void) maskOutPixels : (NSRect) maskedArea;
+
 //X11Drawable protocol.
 @property (nonatomic, assign) unsigned fID;
 
diff --git a/graf2d/cocoa/inc/QuartzWindow.h b/graf2d/cocoa/inc/QuartzWindow.h
index c26404a..c2d0395 100644
--- a/graf2d/cocoa/inc/QuartzWindow.h
+++ b/graf2d/cocoa/inc/QuartzWindow.h
@@ -1,4 +1,4 @@
-// @(#)root/graf2d:$Id: QuartzWindow.h 44075 2012-05-02 15:14:08Z tpochep $
+// @(#)root/graf2d:$Id: QuartzWindow.h 44330 2012-05-29 11:30:29Z tpochep $
 // Author: Timur Pocheptsov   16/02/2012
 
 /*************************************************************************
@@ -126,11 +126,19 @@
 //                                    //
 ////////////////////////////////////////
 
+ at class QuartzImage;
+
 @interface QuartzView : NSView<X11Window>
 
 //Life-cycle.
 - (id) initWithFrame : (NSRect) frame windowAttributes : (const SetWindowAttributes_t *) attr;
 
+//Clip mask - to deal with overlaps.
+ at property (nonatomic, assign) BOOL fClipMaskIsValid;
+- (BOOL) initClipMask;
+- (QuartzImage *) fClipMask;
+- (void) addOverlap : (NSRect)overlapRect;
+
 //X11Drawable protocol.
 
 @property (nonatomic, assign) unsigned fID;
@@ -232,6 +240,7 @@ QuartzView *CreateChildView(QuartzView *parent, Int_t x, Int_t y, UInt_t w, UInt
                             UInt_t clss, void *visual, SetWindowAttributes_t *attr, UInt_t wtype);
 
 void GetRootWindowAttributes(WindowAttributes_t *attr);
+void GetWindowAttributes(NSObject<X11Window> *window, WindowAttributes_t *dst);
 
 //Coordinate conversion.
 int GlobalYCocoaToROOT(CGFloat yCocoa);
@@ -249,6 +258,10 @@ bool ViewIsTextViewFrame(NSView<X11Window> *view, bool checkParent);
 bool LockFocus(NSView<X11Window> *view);
 void UnlockFocus(NSView<X11Window> *view);//For symmetry only.
 
+//Find intersection of view and sibling, result is a rect in view's space.
+NSRect FindOverlapRect(const NSRect &viewRect, const NSRect &siblingViewRect);
+bool RectsOverlap(const NSRect &r1, const NSRect &r2);
+
 }//X11
 }//MacOSX
 }//ROOT
diff --git a/graf2d/cocoa/inc/ROOTOpenGLView.h b/graf2d/cocoa/inc/ROOTOpenGLView.h
index 6763dda..b2a7041 100644
--- a/graf2d/cocoa/inc/ROOTOpenGLView.h
+++ b/graf2d/cocoa/inc/ROOTOpenGLView.h
@@ -1,4 +1,4 @@
-// @(#)root/graf2d:$Id: ROOTOpenGLView.h 43971 2012-04-26 14:09:41Z tpochep $
+// @(#)root/graf2d:$Id: ROOTOpenGLView.h 44330 2012-05-29 11:30:29Z tpochep $
 // Author: Timur Pocheptsov   26/04/2012
 
 /*************************************************************************
@@ -22,19 +22,22 @@
 //                                       //
 ///////////////////////////////////////////
 
- at interface ROOTOpenGLView : NSOpenGLView <X11Window>
+ at interface ROOTOpenGLView : NSView <X11Window>
 
-//NSOpenGLView methods.
 - (id) initWithFrame : (NSRect) frameRect pixelFormat : (NSOpenGLPixelFormat *) format;
 - (void) clearGLContext;
 - (NSOpenGLContext *) openGLContext;
-- (NSOpenGLPixelFormat *) pixelFormat;
-- (void) prepareOpenGL;
-- (void) reshape;
 - (void) setOpenGLContext : (NSOpenGLContext *) context;
+
+- (NSOpenGLPixelFormat *) pixelFormat;
 - (void) setPixelFormat : (NSOpenGLPixelFormat *) pixelFormat;
+
 - (void) update;
 
+- (void) makeContextCurrent;
+- (BOOL) isGLContextCurrent;
+- (void) flushGLBuffer;
+
 //X11Drawable protocol
 
 @property (nonatomic, assign) unsigned fID;
@@ -49,12 +52,18 @@
 
 //X11Window protocol.
 
+- (void) getAttributes : (WindowAttributes_t *) attr;
+
 - (void) setDrawableSize : (NSSize) newSize;
 - (void) setX : (int) x Y : (int) y width : (unsigned) w height : (unsigned) h;
 - (void) setX : (int) x Y : (int) y;
 
 @property (nonatomic, assign) long  fEventMask;
+ at property (nonatomic, assign) int   fClass;
 @property (nonatomic, readonly) int fMapState;
+ at property (nonatomic, assign) int           fDepth;
+ at property (nonatomic, assign) int           fBitGravity;
+ at property (nonatomic, assign) int           fWinGravity;
 
 @property (nonatomic, assign) QuartzView          *fParentView;
 @property (nonatomic, assign) unsigned             fLevel;
@@ -65,22 +74,28 @@
 @property (nonatomic, assign) unsigned fGrabButtonEventMask;
 @property (nonatomic, assign) unsigned fGrabKeyModifiers;
 @property (nonatomic, assign) BOOL     fOwnerEvents;
+
+- (void) mapWindow;
+- (void) mapSubwindows;
+- (void) configureNotifyTree;
+- (BOOL) fIsOverlapped;
+- (void) setOverlapped : (BOOL) overlap;
+- (void) updateLevel : (unsigned) newLevel;
+
 /*
-- (void) getAttributes : (WindowAttributes_t *) attr;
+
 - (void) setAttributes : (const SetWindowAttributes_t *) attr;
 
 - (void) mapRaised;
-- (void) mapWindow;
+
 - (void) mapSubwindows;
 - (void) unmapWindow;
 - (void) raiseWindow;
 - (void) lowerWindow;
 
-- (BOOL) fIsOverlapped;
-- (void) setOverlapped : (BOOL) overlap;
-- (void) updateLevel : (unsigned) newLevel;
 - (void) configureNotifyTree;
 */
+
 - (void) addPassiveKeyGrab : (unichar) keyCode modifiers : (NSUInteger) modifiers;
 - (void) removePassiveKeyGrab : (unichar) keyCode modifiers : (NSUInteger) modifiers;
 - (PassiveKeyGrab *) findPassiveKeyGrab : (unichar) keyCode modifiers : (NSUInteger) modifiers;
diff --git a/graf2d/cocoa/inc/TGCocoa.h b/graf2d/cocoa/inc/TGCocoa.h
index 6779e6f..bd22011 100644
--- a/graf2d/cocoa/inc/TGCocoa.h
+++ b/graf2d/cocoa/inc/TGCocoa.h
@@ -1,4 +1,4 @@
-// @(#)root/graf2d:$Id: TGCocoa.h 44027 2012-04-30 10:30:04Z tpochep $
+// @(#)root/graf2d:$Id: TGCocoa.h 44330 2012-05-29 11:30:29Z tpochep $
 // Author: Timur Pocheptsov   22/11/2011
 
 /*************************************************************************
@@ -283,7 +283,13 @@ public:
    virtual void      SetWMState(Window_t wid, EInitialState state);
    virtual void      SetWMTransientHint(Window_t wid, Window_t main_id);
 
+   //
+   virtual Window_t  CreateOpenGLWindow(Window_t parentID, UInt_t width, UInt_t height, const std::vector<std::pair<UInt_t, Int_t> > &format);
+   virtual Handle_t  CreateOpenGLContext(Window_t windowID, Handle_t sharedContext);
    virtual void      CreateOpenGLContext(Int_t wid);
+   virtual Bool_t    MakeOpenGLContextCurrent(Handle_t ctx);
+   virtual void      FlushOpenGLBuffer(Handle_t ctx);
+
    virtual void      DeleteOpenGLContext(Int_t wid);
 
    virtual UInt_t    ExecCommand(TGWin32Command *code);
diff --git a/graf2d/cocoa/inc/X11Buffer.h b/graf2d/cocoa/inc/X11Buffer.h
index 2c86079..ad75c07 100644
--- a/graf2d/cocoa/inc/X11Buffer.h
+++ b/graf2d/cocoa/inc/X11Buffer.h
@@ -1,4 +1,4 @@
-// @(#)root/graf2d:$Id: X11Buffer.h 44026 2012-04-30 09:32:25Z tpochep $
+// @(#)root/graf2d:$Id: X11Buffer.h 44330 2012-05-29 11:30:29Z tpochep $
 // Author: Timur Pocheptsov   29/02/2012
 
 /*************************************************************************
@@ -210,7 +210,7 @@ private:
    CommandBuffer &operator = (const CommandBuffer &rhs);
    
    std::vector<Command *> fCommands;
-
+   std::vector<QuartzView *> fViewBranch;
 public:
    typedef std::vector<Command *>::size_type size_type;
 
@@ -238,6 +238,7 @@ public:
    }
 private:
    void ClearCommands();
+   void ClipOverlaps(QuartzView *view);
 };
 
 }//X11
diff --git a/graf2d/cocoa/inc/X11Events.h b/graf2d/cocoa/inc/X11Events.h
index 7c8463b..1cc327a 100644
--- a/graf2d/cocoa/inc/X11Events.h
+++ b/graf2d/cocoa/inc/X11Events.h
@@ -1,4 +1,13 @@
-//Author: Timur Pocheptsov 16/02/2012
+// @(#)root/graf2d:$Id: X11Events.h 44392 2012-05-31 11:35:09Z tpochep $
+// Author: Timur Pocheptsov   16/02/2012
+
+/*************************************************************************
+ * Copyright (C) 1995-2012, Rene Brun and Fons Rademakers.               *
+ * All rights reserved.                                                  *
+ *                                                                       *
+ * For the licensing terms see $ROOTSYS/LICENSE.                         *
+ * For the list of contributors see $ROOTSYS/README/CREDITS.             *
+ *************************************************************************/
 
 #ifndef ROOT_X11Events
 #define ROOT_X11Events
@@ -91,6 +100,7 @@ private:
 
    void GenerateButtonReleaseEventNoGrab(NSView<X11Window> *eventView, NSEvent *theEvent, EMouseButton btn);
    void GenerateButtonReleaseEventActiveGrab(NSView<X11Window> *eventView, NSEvent *theEvent, EMouseButton btn);
+   bool CancelImplicitOrPassiveGrab();
    
    void GenerateKeyPressEventNoGrab(NSEvent *theEvent);
    void GenerateKeyReleaseEventNoGrab(NSEvent *theEvent);
diff --git a/graf2d/cocoa/inc/XLFDParser.h b/graf2d/cocoa/inc/XLFDParser.h
index 48d446d..c7c99e9 100644
--- a/graf2d/cocoa/inc/XLFDParser.h
+++ b/graf2d/cocoa/inc/XLFDParser.h
@@ -1,4 +1,4 @@
-// @(#)root/graf2d:$Id: XLFDParser.h 44026 2012-04-30 09:32:25Z tpochep $
+// @(#)root/graf2d:$Id: XLFDParser.h 44201 2012-05-09 15:17:36Z tpochep $
 // Author: Timur Pocheptsov   2/03/2012
 
 /*************************************************************************
@@ -25,16 +25,19 @@ namespace MacOSX {
 namespace X11 {//X11 emulation.
 
 enum FontSlant {
+   kFSAny, //For '*' wildcard in xlfd string.
    kFSRegular,
    kFSItalic
 };
 
 enum FontWeight {
+   kFWAny, //For '*' wildcard in xlfd string.
    kFWMedium,
    kFWBold
 };
 
 struct XLFDName {
+   XLFDName();
    //foundry *
    std::string fFamilyName;
    FontWeight fWeight;
diff --git a/graf2d/cocoa/src/CocoaPrivate.mm b/graf2d/cocoa/src/CocoaPrivate.mm
index b404bd0..69d9318 100644
--- a/graf2d/cocoa/src/CocoaPrivate.mm
+++ b/graf2d/cocoa/src/CocoaPrivate.mm
@@ -1,4 +1,4 @@
-// @(#)root/graf2d:$Id: CocoaPrivate.mm 44026 2012-04-30 09:32:25Z tpochep $
+// @(#)root/graf2d:$Id: CocoaPrivate.mm 44330 2012-05-29 11:30:29Z tpochep $
 // Author: Timur Pocheptsov   29/11/2011
 
 /*************************************************************************
@@ -32,8 +32,9 @@ namespace Details {
 
 //______________________________________________________________________________
 CocoaPrivate::CocoaPrivate()
-               : fCurrentDrawableID(GetRootWindowID() + 1)//Any real window has id > rootID.
-                                                        //0 is also used by some X11 functions as None.
+               : fCurrentDrawableID(GetRootWindowID() + 1), //Any real window has id > rootID.
+                                                            //0 is also used by some X11 functions as None.
+                 fFreeGLContextID(1)
 {
    //Init NSApplication, if it was not done yet.
    Util::AutoreleasePool pool;
@@ -158,6 +159,21 @@ void CocoaPrivate::DeleteDrawable(unsigned drawableID)
 }
 
 //______________________________________________________________________________
+ULong_t CocoaPrivate::RegisterGLContextForView(unsigned viewID)
+{
+   //At the moment, let's assume we attach only 1 gl context to 1 view.
+   fGLContextMap[fFreeGLContextID] = viewID;
+   return fFreeGLContextID++;
+}
+
+//______________________________________________________________________________
+NSObject<X11Window> *CocoaPrivate::GetWindowForGLContext(Handle_t glContextID)
+{
+   assert(fGLContextMap.find(glContextID) != fGLContextMap.end() && "GetWindowForGLContext, bad context id");
+   return GetWindow(fGLContextMap[glContextID]);
+}
+
+//______________________________________________________________________________
 void CocoaPrivate::ReplaceDrawable(unsigned drawableID, NSObject *nsObj)
 {
    drawable_iterator drawableIter = fDrawables.find(drawableID);
diff --git a/graf2d/cocoa/src/FontCache.mm b/graf2d/cocoa/src/FontCache.mm
index a6d554f..02deda8 100644
--- a/graf2d/cocoa/src/FontCache.mm
+++ b/graf2d/cocoa/src/FontCache.mm
@@ -1,4 +1,4 @@
-// @(#)root/graf2d:$Id: FontCache.mm 44151 2012-05-07 10:05:38Z tpochep $
+// @(#)root/graf2d:$Id: FontCache.mm 44201 2012-05-09 15:17:36Z tpochep $
 // Author: Timur Pocheptsov   19/03/2012
 
 /*************************************************************************
@@ -55,9 +55,14 @@ const CFStringRef fixedFontNames[FontCache::nPadFonts] =
 
 
 //______________________________________________________________________________
-CTFontCollectionRef CreateFontCollection(const X11::XLFDName &xlfd)
+CTFontCollectionRef CreateFontCollection(const X11::XLFDName &/*xlfd*/)
 {
-   CTFontCollectionRef ctCollection = 0;
+   CTFontCollectionRef ctCollection = CTFontCollectionCreateFromAvailableFonts(0);
+   if (!ctCollection) 
+      ::Error("CreateFontCollection", "CTFontCollectionCreateFromAvailableFonts failed");
+   
+   return ctCollection;
+/*   CTFontCollectionRef ctCollection = 0;
    if (xlfd.fFamilyName == "*")
       ctCollection = CTFontCollectionCreateFromAvailableFonts(0);//Select all available fonts.
    else {
@@ -90,7 +95,7 @@ CTFontCollectionRef CreateFontCollection(const X11::XLFDName &xlfd)
    }
 
 
-   return ctCollection;
+   return ctCollection;*/
 }
 
 //______________________________________________________________________________
@@ -115,6 +120,23 @@ void GetWeightAndSlant(CTFontDescriptorRef fontDescriptor, X11::XLFDName &newXLF
    //Let's ask for a weight and pixel size.
    const Util::CFScopeGuard<CFDictionaryRef> traits((CFDictionaryRef)CTFontDescriptorCopyAttribute(fontDescriptor, kCTFontTraitsAttribute));
    if (traits.Get()) {
+      if (CFNumberRef symbolTraits = (CFNumberRef)CFDictionaryGetValue(traits.Get(), kCTFontSymbolicTrait)) {
+         uint32_t val = 0;
+         CFNumberGetValue(symbolTraits, kCFNumberIntType, &val);
+         if (val & kCTFontItalicTrait)
+            newXLFD.fSlant = X11::kFSItalic;
+         else
+            newXLFD.fSlant = X11::kFSRegular;
+            
+         if (val & kCTFontBoldTrait)
+            newXLFD.fWeight = X11::kFWBold;
+         else
+            newXLFD.fWeight = X11::kFWMedium;
+      }
+   
+      /*
+      //The code below is wrong - using it, I can not identify bold or italic and always have 
+      //only medium/regular.
       if(CFNumberRef weight = (CFNumberRef)CFDictionaryGetValue(traits.Get(), kCTFontWeightTrait)) {
          double val = 0.;
          if (CFNumberGetValue(weight, kCFNumberDoubleType, &val))
@@ -126,6 +148,7 @@ void GetWeightAndSlant(CTFontDescriptorRef fontDescriptor, X11::XLFDName &newXLF
          if (CFNumberGetValue(slant, kCFNumberDoubleType, &val))
             newXLFD.fSlant = val > 0. ? X11::kFSItalic : X11::kFSRegular;
       }
+      */
    }
 }
 
@@ -156,7 +179,7 @@ void CreateXLFDString(const X11::XLFDName &xlfd, std::string &xlfdString)
     if (xlfd.fWeight == X11::kFWBold)
         xlfdString += "-bold";
     else
-        xlfdString += "-*";
+        xlfdString += "-normal";
 
     if (xlfd.fSlant == X11::kFSItalic)
         xlfdString += "-i";
@@ -257,7 +280,7 @@ char **FontCache::ListFonts(const X11::XLFDName &xlfd, int maxNames, int &count)
    
    std::vector<char> xlfdData;
    std::vector<char> familyName;
-   X11::XLFDName newXLFD = {};
+   X11::XLFDName newXLFD;
    std::string xlfdString;
    
    const CFIndex nFonts = CFArrayGetCount(fonts.Get());
@@ -266,21 +289,29 @@ char **FontCache::ListFonts(const X11::XLFDName &xlfd, int maxNames, int &count)
 
       if (!GetFamilyName(font, familyName))
          continue;
-      //I do not check family name: if xlfd.fFamilyName is '*', all font names fit,
-      //if it's a special name - collection is created using this name.
+ 
+      if (xlfd.fFamilyName != "*" && xlfd.fFamilyName != &familyName[0])
+         continue;
+
       newXLFD.fFamilyName = &familyName[0];
+      
+      //If family name has '-', ROOT's GUI can not parse it correctly - 
+      //'-' is a separator in XLFD. Just skip this font (anyway, it wan not requested by GUI, only
+      //listed by FontCache.
+      if (newXLFD.fFamilyName.find('-') != std::string::npos)
+         continue;
 
       GetWeightAndSlant(font, newXLFD);
+
       //Check weight and slant.
-      if (newXLFD.fWeight != xlfd.fWeight)
+      if (xlfd.fWeight != X11::kFWAny && newXLFD.fWeight != xlfd.fWeight)
          continue;
-      if (newXLFD.fSlant != xlfd.fSlant)
+      if (xlfd.fSlant != X11::kFSAny && newXLFD.fSlant != xlfd.fSlant)
          continue;
 
       if (xlfd.fPixelSize) {//Size was requested.
          GetPixelSize(font, newXLFD);
-         //I do not think, that font has a pixel size.
-         //But Core Text supports different font sizes.
+         //Core Text supports different font sizes.
          if (!newXLFD.fPixelSize)
             newXLFD.fPixelSize = xlfd.fPixelSize;
       }
diff --git a/graf2d/cocoa/src/QuartzPixmap.mm b/graf2d/cocoa/src/QuartzPixmap.mm
index 22675d1..7878459 100644
--- a/graf2d/cocoa/src/QuartzPixmap.mm
+++ b/graf2d/cocoa/src/QuartzPixmap.mm
@@ -1,4 +1,4 @@
-// @(#)root/graf2d:$Id: QuartzPixmap.mm 44030 2012-04-30 13:40:41Z tpochep $
+// @(#)root/graf2d:$Id: QuartzPixmap.mm 44530 2012-06-04 16:25:19Z tpochep $
 // Author: Timur Pocheptsov   16/02/2012
 
 /*************************************************************************
@@ -414,6 +414,7 @@ std::size_t ROOT_QuartzImage_GetBytesAtPosition(void* info, void* buffer, off_t
       }
 
       fImage = CGImageMaskCreate(width, height, 8, 8, width, provider, 0, false);//null -> decode, false -> shouldInterpolate.
+      CGDataProviderRelease(provider);
 
       if (!fImage) {
          NSLog(@"QuartzPixmap: -initMaskWithW:H:bitmapMask:, CGImageMaskCreate failed");
@@ -432,6 +433,45 @@ std::size_t ROOT_QuartzImage_GetBytesAtPosition(void* info, void* buffer, off_t
 }
 
 //______________________________________________________________________________
+- (id) initMaskWithW : (unsigned) width H : (unsigned) height
+{
+   assert(width > 0 && "initMaskWithW:H:, width parameter is zero");
+   assert(height > 0 && "initMaskWithW:H:, height parameter is zero");
+   
+   if (self = [super init]) {
+      fImageData = new unsigned char[width * height];
+      fIsStippleMask = YES;
+      const CGDataProviderDirectCallbacks providerCallbacks = {0, ROOT_QuartzImage_GetBytePointer, 
+                                                               ROOT_QuartzImage_ReleaseBytePointer, 
+                                                               ROOT_QuartzImage_GetBytesAtPosition, 0};
+      CGDataProviderRef provider = CGDataProviderCreateDirect(fImageData, width * height, &providerCallbacks);
+      if (!provider) {
+         NSLog(@"QuartzPixmap: -initMaskWithW:H: CGDataProviderCreateDirect failed");
+         delete [] fImageData;
+         fImageData = 0;
+         return nil;
+      }
+
+      fImage = CGImageMaskCreate(width, height, 8, 8, width, provider, 0, false);//null -> decode, false -> shouldInterpolate.
+      CGDataProviderRelease(provider);
+
+      if (!fImage) {
+         NSLog(@"QuartzPixmap: -initMaskWithW:H:, CGImageMaskCreate failed");
+         delete [] fImageData;
+         fImageData = 0;
+         return nil;
+      }
+      
+      fWidth = width;
+      fHeight = height;
+      
+      return self;
+   }
+   
+   return nil;
+}
+
+//______________________________________________________________________________
 - (void) dealloc
 {
    if (fImage) {
@@ -443,6 +483,35 @@ std::size_t ROOT_QuartzImage_GetBytesAtPosition(void* info, void* buffer, off_t
 }
 
 //______________________________________________________________________________
+- (void) clearMask
+{
+   assert(fIsStippleMask == YES && "-clearMask, called for non-mask image");
+   
+   for (unsigned i = 0, e = fWidth * fHeight; i < e; ++i)
+      fImageData[i] = 0;//All pixels are ok.
+}
+
+//______________________________________________________________________________
+- (void) maskOutPixels : (NSRect) maskedArea
+{
+   assert(fIsStippleMask == YES && "-maskOutPixels, called for non-mask image");
+   assert(fImageData != 0 && "-maskOutPixels, image was not initialized");
+   
+   const int iStart = std::max(0, int(maskedArea.origin.x));
+   const int iEnd = std::min(int(fWidth), int(maskedArea.size.width) + iStart);
+   
+   //Note about j: as soon as QuartzView is flipped, orde of pixel lines is changed here.
+   const int jStart = int(fHeight) - std::min(int(fHeight), int(maskedArea.origin.y + maskedArea.size.height));
+   const int jEnd = std::min(int(fHeight), int(jStart + maskedArea.size.height));
+   
+   for (int j = jStart; j < jEnd; ++j) {
+      unsigned char *line = fImageData + j * fWidth;
+      for (int i = iStart; i < iEnd; ++i)
+         line[i] = 255;
+   }
+}
+
+//______________________________________________________________________________
 - (BOOL) isRectInside : (Rectangle_t) area
 {
    if (area.fX < 0 || (unsigned)area.fX >= fWidth)
@@ -567,13 +636,13 @@ bool AdjustCropArea(const Rectangle_t &srcRect, Rectangle_t &cropArea)
       cropArea.fWidth = std::min(int(srcRect.fWidth), int(cropArea.fWidth) - int(srcRect.fX - cropArea.fX));
       cropArea.fX = srcRect.fX;
    } else
-      cropArea.fWidth = std::min(srcRect.fWidth, cropArea.fWidth);
+      cropArea.fWidth = std::min(int(srcRect.fWidth) - int(cropArea.fX - srcRect.fX), int(cropArea.fWidth));
       
    if (cropArea.fY < srcRect.fY) {
       cropArea.fHeight = std::min(int(srcRect.fHeight), int(cropArea.fHeight) - int(srcRect.fY - cropArea.fY));
       cropArea.fY = srcRect.fY;
    } else
-      cropArea.fHeight = std::min(srcRect.fHeight, cropArea.fHeight);
+      cropArea.fHeight = std::min(int(srcRect.fHeight) - int(cropArea.fY - srcRect.fY), int(cropArea.fHeight));
    
    return true;
 }
diff --git a/graf2d/cocoa/src/QuartzWindow.mm b/graf2d/cocoa/src/QuartzWindow.mm
index ae62d42..371aa8a 100644
--- a/graf2d/cocoa/src/QuartzWindow.mm
+++ b/graf2d/cocoa/src/QuartzWindow.mm
@@ -1,4 +1,4 @@
-// @(#)root/graf2d:$Id: QuartzWindow.mm 44086 2012-05-03 12:42:17Z tpochep $
+// @(#)root/graf2d:$Id: QuartzWindow.mm 44505 2012-06-04 11:37:36Z tpochep $
 // Author: Timur Pocheptsov   16/02/2012
 
 /*************************************************************************
@@ -13,8 +13,6 @@
 
 //#define NDEBUG
 
-#include <stdexcept>
-
 #ifdef DEBUG_ROOT_COCOA
 #import <iostream>
 #import <fstream>
@@ -22,6 +20,7 @@
 #import "TClass.h"
 #endif
 
+#import <algorithm>
 #import <stdexcept>
 #import <cassert>
 
@@ -435,9 +434,55 @@ void UnlockFocus(NSView<X11Window> *view)
    ((QuartzView *)view).fContext = 0;
 }
 
+//________________________________________________________________________________________
+NSRect FindOverlapRect(const NSRect &viewRect, const NSRect &siblingViewRect)
+{
+   NSRect frame1 = viewRect;
+   NSRect frame2 = siblingViewRect;
+
+   //Adjust frames - move to frame1's space.
+   frame2.origin.x -= frame1.origin.x;
+   frame2.origin.y -= frame1.origin.y;
+   frame1.origin = CGPointZero;
+
+   NSRect overlap = {};
+   
+   if (frame2.origin.x < 0) {
+      overlap.size.width = std::min(frame1.size.width, frame2.size.width - (frame1.origin.x - frame2.origin.x));
+   } else {
+      overlap.origin.x = frame2.origin.x;
+      overlap.size.width = std::min(frame2.size.width, frame1.size.width - frame2.origin.x);
+   }
+   
+   if (frame2.origin.y < 0) {
+      overlap.size.height = std::min(frame1.size.height, frame2.size.height - (frame1.origin.y - frame2.origin.y));
+   } else {
+      overlap.origin.y = frame2.origin.y;
+      overlap.size.height = std::min(frame2.size.height, frame1.size.height - frame2.origin.y);
+   }
+   
+   return overlap;
+
 }
+
+//________________________________________________________________________________________
+bool RectsOverlap(const NSRect &r1, const NSRect &r2)
+{
+   if (r2.origin.x >= r1.origin.x + r1.size.width)
+      return false;
+   if (r2.origin.x + r2.size.width <= r1.origin.x)
+      return false;
+   if (r2.origin.y >= r1.origin.y + r1.size.height)
+      return false;
+   if (r2.origin.y + r2.size.height <= r1.origin.y)
+      return false;
+   
+   return true;
 }
-}
+
+}//X11
+}//MacOSX
+}//ROOT
 
 #ifdef DEBUG_ROOT_COCOA
 
@@ -512,13 +557,13 @@ void print_mask_info(ULong_t mask)
 @implementation QuartzWindow {
 @private
    QuartzView *fContentView;
+   BOOL fDelayedTransient;
 }
 
 
 @synthesize fMainWindow;
 @synthesize fBackBuffer;
 
-
 //QuartzWindow's life cycle.
 //______________________________________________________________________________
 - (id) initWithContentRect : (NSRect) contentRect styleMask : (NSUInteger) windowStyle backing : (NSBackingStoreType) bufferingType 
@@ -543,6 +588,7 @@ void print_mask_info(ULong_t mask)
       [self setContentView : fContentView];
 
       [fContentView release];
+      fDelayedTransient = NO;
       
       if (attr)
          ROOT::MacOSX::X11::SetWindowAttributes(attr, self);
@@ -556,8 +602,14 @@ void print_mask_info(ULong_t mask)
 {
    assert(window != nil && "addTransientWindow, window parameter is nil");
 
-   window.fMainWindow = self;   
-   [self addChildWindow : window ordered : NSWindowAbove];
+   window.fMainWindow = self;
+   
+   if (window.fMapState != kIsViewable) {
+      window.fDelayedTransient = YES;
+   } else {
+      [self addChildWindow : window ordered : NSWindowAbove];
+      window.fDelayedTransient = NO;
+   }
 }
 
 //______________________________________________________________________________
@@ -566,6 +618,12 @@ void print_mask_info(ULong_t mask)
    [super dealloc];
 }
 
+//______________________________________________________________________________
+- (void) setFDelayedTransient : (BOOL) d
+{
+   fDelayedTransient = d;
+}
+
 ///////////////////////////////////////////////////////////
 //X11Drawable's protocol.
 
@@ -899,10 +957,16 @@ void print_mask_info(ULong_t mask)
 //______________________________________________________________________________
 - (void) addChild : (NSView<X11Window> *) child
 {
-   assert(fContentView != nil && "addChild, content view is nil");
    assert(child != nil && "addChild, child view is nil");
-   
-   [fContentView addChild : child];
+ 
+   if (!fContentView) {
+      //This can happen only in case of re-parent operation.
+      assert([child isKindOfClass : [QuartzView class]] && "addChild: gl view in a top-level window as content view is not supported");
+      fContentView = (QuartzView *)child;
+      [self setContentView : child];
+      fContentView.fParentView = nil;
+   } else
+      [fContentView addChild : child];
 }
 
 //______________________________________________________________________________
@@ -935,6 +999,11 @@ void print_mask_info(ULong_t mask)
    [self makeKeyAndOrderFront : self];
    [fContentView setHidden : NO];
    [fContentView configureNotifyTree];
+
+   if (fDelayedTransient) {
+      fDelayedTransient = NO;
+      [fMainWindow addChildWindow : self ordered : NSWindowAbove];
+   }
 }
 
 //______________________________________________________________________________
@@ -946,6 +1015,11 @@ void print_mask_info(ULong_t mask)
    [self makeKeyAndOrderFront : self];
    [fContentView setHidden : NO];
    [fContentView configureNotifyTree];
+   
+   if (fDelayedTransient) {
+      fDelayedTransient = NO;
+      [fMainWindow addChildWindow : self ordered : NSWindowAbove];
+   }
 }
 
 //______________________________________________________________________________
@@ -1093,11 +1167,15 @@ void print_mask_info(ULong_t mask)
 
 @end
 
+
 @implementation QuartzView {
    NSMutableArray *fPassiveKeyGrabs;
    BOOL            fIsOverlapped;
+   QuartzImage    *fClipMask;
 }
 
+ at synthesize fClipMaskIsValid;
+
 @synthesize fID;
 @synthesize fContext;
 /////////////////////
@@ -1125,6 +1203,9 @@ void print_mask_info(ULong_t mask)
 {
    if (self = [super initWithFrame : frame]) {
       //Make this explicit (though memory is zero initialized).
+      fClipMaskIsValid = NO;
+      fClipMask = nil;
+
       fID = 0;
       fLevel = 0;
       
@@ -1154,6 +1235,51 @@ void print_mask_info(ULong_t mask)
    return self;
 }
 
+//Overlap management.
+//______________________________________________________________________________
+- (BOOL) initClipMask
+{
+   const NSSize size = self.frame.size;
+
+   if (fClipMask) {
+      if ((unsigned)size.width == fClipMask.fWidth && (unsigned)size.height == fClipMask.fHeight) {
+         //All pixels must be visible.
+         [fClipMask clearMask];
+      } else {
+         [fClipMask release];
+         fClipMask = nil;
+      }
+   }
+   
+   if (!fClipMask) {
+      fClipMask = [QuartzImage alloc];
+      if ([fClipMask initMaskWithW : (unsigned)size.width H : (unsigned)size.height]) {
+         return YES;
+      } else {
+         [fClipMask release];
+         fClipMask = nil;
+         return NO;
+      }
+   }
+
+   return YES;
+}
+
+//______________________________________________________________________________
+- (QuartzImage *) fClipMask
+{
+   return fClipMask;
+}
+
+//______________________________________________________________________________
+- (void) addOverlap : (NSRect)overlapRect
+{
+   assert(fClipMask != nil && "addOverlap, fClipMask is nil");
+   assert(fClipMaskIsValid == YES && "addOverlap, fClipMask is invalid");
+   
+   [fClipMask maskOutPixels : overlapRect];
+}
+
 //X11Drawable protocol.
 //______________________________________________________________________________
 - (BOOL) fIsPixmap
@@ -1210,8 +1336,6 @@ void print_mask_info(ULong_t mask)
 //______________________________________________________________________________
 - (void) setX : (int) x Y : (int) y width : (unsigned) w height : (unsigned) h
 {
-   assert(fParentView != nil && "setX:Y:width:height:, parent view is nil");
-
    NSRect newFrame = {};
    newFrame.origin.x = x;
    newFrame.origin.y = y;
@@ -1224,8 +1348,6 @@ void print_mask_info(ULong_t mask)
 //______________________________________________________________________________
 - (void) setX : (int) x Y : (int) y
 {
-   assert(fParentView != nil && "setX:Y:, parent view is nil");
-   
    NSRect newFrame = self.frame;
    newFrame.origin.x = x;
    newFrame.origin.y = y;
@@ -1571,7 +1693,7 @@ void print_mask_info(ULong_t mask)
 {
    for (QuartzView * v in [self subviews]) {
       [v setHidden : NO]; 
-      [v mapSubwindows];
+      //[v mapSubwindows];
    }
 }
 
@@ -1603,12 +1725,21 @@ void print_mask_info(ULong_t mask)
    for (QuartzView *sibling in [fParentView subviews]) {
       if (self == sibling)
          continue;
+      if ([sibling isHidden])
+         continue;
       //TODO: equal test is not good :) I have a baaad feeling about this ;)
-      if (CGRectEqualToRect(sibling.frame, self.frame))
+      if (CGRectEqualToRect(sibling.frame, self.frame)) {
          [sibling setOverlapped : YES];
+         //
+         [sibling setHidden : YES];
+         //
+      }
    }
 
    [self setOverlapped : NO];
+   //
+   [self setHidden : NO];
+   //
    [fParentView sortSubviewsUsingFunction : CompareViewsToRaise context : (void *)self];
    [self setNeedsDisplay : YES];//?
 }
@@ -1622,11 +1753,18 @@ void print_mask_info(ULong_t mask)
    for (QuartzView *sibling in reverseEnumerator) {
       if (sibling == self)
          continue;
+
       //TODO: equal test is not good :) I have a baaad feeling about this ;)
       if (CGRectEqualToRect(sibling.frame, self.frame)) {
          [sibling setOverlapped : NO];
+         //
+         [sibling setHidden : NO];
+         //
          [sibling setNeedsDisplay : YES];
          [self setOverlapped : YES];
+         //
+         [self setHidden : YES];
+         //
          break;
       }
    }
@@ -1654,7 +1792,7 @@ void print_mask_info(ULong_t mask)
 //______________________________________________________________________________
 - (void) configureNotifyTree
 {
-   if (self.fMapState == kIsViewable) {
+   if (self.fMapState == kIsViewable || fIsOverlapped == YES) {
       if (fEventMask & kStructureNotifyMask) {
          TGCocoa *vx = dynamic_cast<TGCocoa *>(gVirtualX);
          assert(vx && "configureNotifyTree, gVirtualX is either null or has type different from TGCocoa");
@@ -1809,7 +1947,7 @@ void print_mask_info(ULong_t mask)
    
    [super setFrameSize : newSize];
    
-   if ((fEventMask & kStructureNotifyMask) && self.fMapState == kIsViewable) {
+   if ((fEventMask & kStructureNotifyMask) && (self.fMapState == kIsViewable || fIsOverlapped == YES)) {
       TGCocoa *vx = dynamic_cast<TGCocoa *>(gVirtualX);
       assert(vx != 0 && "setFrameSize:, gVirtualX is either null or has a type, different from TGCocoa");
       vx->GetEventTranslator()->GenerateConfigureNotifyEvent(self, self.frame);
diff --git a/graf2d/cocoa/src/ROOTOpenGLView.mm b/graf2d/cocoa/src/ROOTOpenGLView.mm
index a2aeeb1..bc2a67d 100644
--- a/graf2d/cocoa/src/ROOTOpenGLView.mm
+++ b/graf2d/cocoa/src/ROOTOpenGLView.mm
@@ -1,3 +1,7 @@
+#import <cassert>
+
+#import <OpenGL/gl.h>
+
 #import "ROOTOpenGLView.h"
 #import "QuartzWindow.h"
 #import "X11Events.h"
@@ -6,6 +10,10 @@
 @implementation ROOTOpenGLView {
    NSMutableArray *fPassiveKeyGrabs;
    BOOL            fIsOverlapped;
+   
+   NSOpenGLPixelFormat *fPixelFormat;
+   NSOpenGLContext *fOpenGLContext;
+   BOOL fCtxIsCurrent;
 }
 
 @synthesize fID;
@@ -17,18 +25,24 @@
 @synthesize fGrabKeyModifiers;
 @synthesize fOwnerEvents;
 @synthesize fCurrentCursor;
+ at synthesize fDepth;
+ at synthesize fBitGravity;
+ at synthesize fWinGravity;
+ at synthesize fClass;
 
 //______________________________________________________________________________
 - (id) initWithFrame : (NSRect) frameRect pixelFormat : (NSOpenGLPixelFormat *) format
 {
-
-   if (self = [super initWithFrame : frameRect pixelFormat : format]) {
+   if (self = [super initWithFrame : frameRect]) {
       fPassiveKeyGrabs = [[NSMutableArray alloc] init];
       [self setHidden : YES];//Not sure.
       fCurrentCursor = kPointer;
+      fIsOverlapped = NO;
+      fPixelFormat = [format retain];
+      fCtxIsCurrent = kFALSE;
       //Tracking area?
    }
-   
+
    return self;
 }
 
@@ -36,57 +50,81 @@
 - (void) dealloc
 {
    [fPassiveKeyGrabs release];
+   [fPixelFormat release];
+   [fOpenGLContext release];
+
    [super dealloc];
 }
 
-//NSOpenGLView's overriders.
-
 //______________________________________________________________________________
 - (void) clearGLContext
 {
-   [super clearGLContext];
+   //[NSOpenGLContext clearCurrentContext];
 }
 
 //______________________________________________________________________________
 - (NSOpenGLContext *) openGLContext
 {
-   return [super openGLContext];
+   return fOpenGLContext;
 }
 
 //______________________________________________________________________________
-- (NSOpenGLPixelFormat *) pixelFormat
+- (void) setOpenGLContext : (NSOpenGLContext *) context
 {
-   return [super pixelFormat];
+   if (context != fOpenGLContext) {
+      [fOpenGLContext release];
+      //
+      fOpenGLContext = [context retain];
+      if (![self isHidden])
+         [fOpenGLContext setView : self];
+   }
 }
 
 //______________________________________________________________________________
-- (void) prepareOpenGL
+- (void) makeContextCurrent
 {
-   [super prepareOpenGL];
+   fCtxIsCurrent = NO;
+   if (!fOpenGLContext)
+      return;
+   
+   if ([fOpenGLContext view] != self)
+      [fOpenGLContext setView : self];
+   
+   [fOpenGLContext makeCurrentContext];
+   fCtxIsCurrent = YES; 
 }
 
 //______________________________________________________________________________
-- (void) reshape
+- (void) flushGLBuffer 
 {
-   [super reshape];
+   assert(fOpenGLContext == [NSOpenGLContext currentContext] && "flushGLBuffer, view's GL context is not current");
+   //
+   glFlush();//???
+   [fOpenGLContext flushBuffer];
 }
 
 //______________________________________________________________________________
-- (void) setOpenGLContext : (NSOpenGLContext *) context
+- (NSOpenGLPixelFormat *) pixelFormat
 {
-   [super setOpenGLContext : context];
+   return fPixelFormat;
 }
 
 //______________________________________________________________________________
 - (void) setPixelFormat : (NSOpenGLPixelFormat *) pixelFormat
 {
-   [super setPixelFormat : pixelFormat];
+   (void)pixelFormat;
+   //Do not modify fPixelFormat.
 }
 
 //______________________________________________________________________________
 - (void) update
 {
-   [super update];
+}
+
+//______________________________________________________________________________
+- (BOOL) isGLContextCurrent
+{
+   return fCtxIsCurrent;
 }
 
 //X11Drawable protocol.
@@ -103,6 +141,58 @@
    return YES;
 }
 
+//______________________________________________________________________________
+- (void) getAttributes : (WindowAttributes_t *) attr
+{
+   assert(attr && "getAttributes, attr parameter is nil");
+   ROOT::MacOSX::X11::GetWindowAttributes(self, attr);
+}
+
+//______________________________________________________________________________
+- (void) mapWindow
+{   
+   [self setHidden : NO];
+}
+
+//______________________________________________________________________________
+- (void) mapSubwindows
+{
+   //GL-view can not have any subwindows.
+   assert([[self subviews] count] == 0 && "mapSubwindows, GL-view has children");
+}
+
+//______________________________________________________________________________
+- (void) configureNotifyTree
+{
+   //The only node in the tree is 'self'.
+   if (self.fMapState == kIsViewable) {
+      if (fEventMask & kStructureNotifyMask) {
+         TGCocoa *vx = dynamic_cast<TGCocoa *>(gVirtualX);
+         assert(vx && "configureNotifyTree, gVirtualX is either null or has type different from TGCocoa");
+         vx->GetEventTranslator()->GenerateConfigureNotifyEvent(self, self.frame);
+      }
+   }
+}
+
+//______________________________________________________________________________
+- (BOOL) fIsOverlapped
+{
+   return fIsOverlapped;
+}
+
+//______________________________________________________________________________
+- (void) setOverlapped : (BOOL) overlap
+{
+   fIsOverlapped = overlap;
+   [self setHidden : fIsOverlapped];
+}
+
+//______________________________________________________________________________
+- (void) updateLevel : (unsigned) newLevel
+{
+   fLevel = newLevel;
+}
+
 ////////
 //Shared methods:
 
diff --git a/graf2d/cocoa/src/TGCocoa.mm b/graf2d/cocoa/src/TGCocoa.mm
index f2ba932..db8d5ba 100644
--- a/graf2d/cocoa/src/TGCocoa.mm
+++ b/graf2d/cocoa/src/TGCocoa.mm
@@ -1,4 +1,4 @@
-// @(#)root/graf2d:$Id: TGCocoa.mm 44155 2012-05-07 13:49:07Z tpochep $
+// @(#)root/graf2d:$Id: TGCocoa.mm 44330 2012-05-29 11:30:29Z tpochep $
 // Author: Timur Pocheptsov   22/11/2011
 
 /*************************************************************************
@@ -18,8 +18,10 @@
 #include <cstddef>
 #include <limits>
 
-#include  <Cocoa/Cocoa.h>
+#include <OpenGL/OpenGL.h>
+#include <Cocoa/Cocoa.h>
 
+#include "ROOTOpenGLView.h"
 #include "CocoaPrivate.h"
 #include "QuartzWindow.h"
 #include "QuartzPixmap.h"
@@ -28,6 +30,7 @@
 #include "CocoaUtils.h"
 #include "X11Events.h"
 #include "X11Buffer.h"
+#include "TGLFormat.h"
 #include "TGClient.h"
 #include "TGWindow.h"
 #include "TGFrame.h"
@@ -252,11 +255,7 @@ TGCocoa::TGCocoa()
               fForegroundProcess(false),
               fCurrentMessageID(1)
 {
-   try {
-      fPimpl.reset(new Details::CocoaPrivate);
-   } catch (const std::exception &) {
-      throw;
-   }
+   fPimpl.reset(new Details::CocoaPrivate);
 }
 
 //______________________________________________________________________________
@@ -269,11 +268,7 @@ TGCocoa::TGCocoa(const char *name, const char *title)
               fForegroundProcess(false),
               fCurrentMessageID(1)
 {
-   try {
-      fPimpl.reset(new Details::CocoaPrivate);
-   } catch (const std::exception &) {
-      throw;   
-   }
+   fPimpl.reset(new Details::CocoaPrivate);
 }
 
 //______________________________________________________________________________
@@ -569,31 +564,25 @@ Window_t TGCocoa::CreateWindow(Window_t parentID, Int_t x, Int_t y, UInt_t w, UI
    const Util::AutoreleasePool pool;
    
    if (fPimpl->IsRootWindow(parentID)) {//parent == root window.
-      try {
-         QuartzWindow *newWindow = X11::CreateTopLevelWindow(x, y, w, h, border, depth, clss, visual, attr, wtype);//Can throw.
-         const Util::NSScopeGuard<QuartzWindow> winGuard(newWindow);
-         const Window_t result = fPimpl->RegisterDrawable(newWindow);//Can throw.
-         newWindow.fID = result;
-
-         return result;
-      } catch (const std::exception &) {//Bad alloc.
-         throw;
-      }
+      QuartzWindow *newWindow = X11::CreateTopLevelWindow(x, y, w, h, border, depth, clss, visual, attr, wtype);//Can throw.
+      const Util::NSScopeGuard<QuartzWindow> winGuard(newWindow);
+      const Window_t result = fPimpl->RegisterDrawable(newWindow);//Can throw.
+      newWindow.fID = result;
+
+      [newWindow setAcceptsMouseMovedEvents : YES];
+
+      return result;
    } else {
       NSObject<X11Window> *parentWin = fPimpl->GetWindow(parentID);
       //OpenGL view can not have children.
       assert([parentWin.fContentView isKindOfClass : [QuartzView class]] && "CreateWindow, parent view must be QuartzView");
-      try {
-         QuartzView *childView = X11::CreateChildView((QuartzView *)parentWin.fContentView, x, y, w, h, border, depth, clss, visual, attr, wtype);//Can throw.
-         const Util::NSScopeGuard<QuartzView> viewGuard(childView);
-         const Window_t result = fPimpl->RegisterDrawable(childView);//Can throw.
-         childView.fID = result;
-         [parentWin addChild : childView];
-         
-         return result;
-      } catch (const std::exception &) {//Bad alloc.
-         throw;
-      }
+      QuartzView *childView = X11::CreateChildView((QuartzView *)parentWin.fContentView, x, y, w, h, border, depth, clss, visual, attr, wtype);//Can throw.
+      const Util::NSScopeGuard<QuartzView> viewGuard(childView);
+      const Window_t result = fPimpl->RegisterDrawable(childView);//Can throw.
+      childView.fID = result;
+      [parentWin addChild : childView];
+      
+      return result;
    }
 }
 
@@ -739,7 +728,7 @@ void TGCocoa::ReparentChild(Window_t wid, Window_t pid, Int_t x, Int_t y)
       QuartzWindow *newTopLevel = [[QuartzWindow alloc] initWithContentRect : frame styleMask : styleMask backing : NSBackingStoreBuffered defer : NO];
       
       [view setX : x Y : y];
-      [newTopLevel setContentView : view];
+      [newTopLevel addChild : view];
       fPimpl->ReplaceDrawable(wid, newTopLevel);
 
       [view updateLevel : 0];
@@ -771,6 +760,7 @@ void TGCocoa::ReparentTopLevel(Window_t wid, Window_t pid, Int_t x, Int_t y)
    
    NSView<X11Window> *contentView = fPimpl->GetWindow(wid).fContentView;
    [contentView retain];
+   [contentView removeFromSuperview];
    QuartzWindow *topLevel = (QuartzWindow *)[contentView window];
    [topLevel setContentView : nil];
    fPimpl->ReplaceDrawable(wid, contentView);
@@ -1736,18 +1726,14 @@ Int_t TGCocoa::OpenPixmap(UInt_t w, UInt_t h)
    newSize.width = w;
    newSize.height = h;
 
-   try {
-      Util::NSScopeGuard<QuartzPixmap> obj([QuartzPixmap alloc]);
-      if (QuartzPixmap *pixmap = [obj.Get() initWithW : w H : h]) {
-         obj.Reset(pixmap);
-         pixmap.fID = fPimpl->RegisterDrawable(pixmap);//Can throw.
-         return (Int_t)pixmap.fID;
-      } else {
-         Error("OpenPixmap", "Pixmap initialization failed");
-         return -1;
-      }
-   } catch (const std::exception &) {//std::bad_alloc.
-      throw;
+   Util::NSScopeGuard<QuartzPixmap> obj([QuartzPixmap alloc]);
+   if (QuartzPixmap *pixmap = [obj.Get() initWithW : w H : h]) {
+      obj.Reset(pixmap);
+      pixmap.fID = fPimpl->RegisterDrawable(pixmap);//Can throw.
+      return (Int_t)pixmap.fID;
+   } else {
+      Error("OpenPixmap", "Pixmap initialization failed");
+      return -1;
    }
 }
 
@@ -1832,46 +1818,40 @@ Pixmap_t TGCocoa::CreatePixmap(Drawable_t /*wid*/, const char *bitmap, UInt_t wi
    assert(width > 0 && "CreatePixmap, width parameter is 0");
    assert(height > 0 && "CreatePixmap, height parameter is 0");
    
-   try {
-      unsigned char *imageData = 0;      
-      if (depth > 1)
-         imageData = new unsigned char[width * height * 4]();
-      else
-         imageData = new unsigned char[width * height];
+   unsigned char *imageData = 0;      
+   if (depth > 1)
+      imageData = new unsigned char[width * height * 4]();
+   else
+      imageData = new unsigned char[width * height];
 
-      X11::FillPixmapBuffer((unsigned char*)bitmap, width, height, foregroundPixel, backgroundPixel, depth, imageData);
+   X11::FillPixmapBuffer((unsigned char*)bitmap, width, height, foregroundPixel, backgroundPixel, depth, imageData);
 
-      //Now we can create CGImageRef.
-      Util::NSScopeGuard<QuartzImage> mem([QuartzImage alloc]);
-      if (!mem.Get()) {
-         Error("CreatePixmap", "[QuartzImage alloc] failed");
-         delete [] imageData;
-         return Pixmap_t();
-      }
-   
-      QuartzImage *image = nil;
-      
-      if (depth > 1)
-         image = [mem.Get() initWithW : width H : height data: imageData];
-      else
-         image = [mem.Get() initMaskWithW : width H : height bitmapMask : imageData];
+   //Now we can create CGImageRef.
+   Util::NSScopeGuard<QuartzImage> mem([QuartzImage alloc]);
+   if (!mem.Get()) {
+      Error("CreatePixmap", "[QuartzImage alloc] failed");
+      delete [] imageData;
+      return Pixmap_t();
+   }
 
-      if (!image) {
-         delete [] imageData;
-         Error("CreatePixmap", "[QuartzImage initWithW:H:data:] failed");
-         return Pixmap_t();
-      }
+   QuartzImage *image = nil;
+   
+   if (depth > 1)
+      image = [mem.Get() initWithW : width H : height data: imageData];
+   else
+      image = [mem.Get() initMaskWithW : width H : height bitmapMask : imageData];
 
-      mem.Reset(image);
-      //Now imageData is owned by image.
-      image.fID = fPimpl->RegisterDrawable(image);//This can throw.
-      return image.fID;      
-   } catch (const std::exception &) {
-      //Memory is owned by QuartzImage.
-      throw;
+   if (!image) {
+      delete [] imageData;
+      Error("CreatePixmap", "[QuartzImage initWithW:H:data:] failed");
+      return Pixmap_t();
    }
 
-   return Pixmap_t();
+   mem.Reset(image);
+   //Now imageData is owned by image.
+   image.fID = fPimpl->RegisterDrawable(image);//This can throw.
+
+   return image.fID;      
 }
 
 //______________________________________________________________________________
@@ -1882,42 +1862,36 @@ Pixmap_t TGCocoa::CreatePixmapFromData(unsigned char *bits, UInt_t width, UInt_t
    assert(width != 0 && "CreatePixmapFromData, width parameter is 0");
    assert(height != 0 && "CreatePixmapFromData, height parameter is 0");
 
-   try {
-      //I'm not using vector here, since I have to pass this pointer to Obj-C code
-      //(and Obj-C object will own this memory later).
-      unsigned char *imageData = new unsigned char[width * height * 4];
-      std::copy(bits, bits + width * height * 4, imageData);
-
-      //Convert bgra to rgba.
-      unsigned char *p = imageData;
-      for (unsigned i = 0, e = width * height; i < e; ++i, p += 4)
-         std::swap(p[0], p[2]);
-   
-      //Now we can create CGImageRef.
-      Util::NSScopeGuard<QuartzImage> mem([QuartzImage alloc]);
-      if (!mem.Get()) {
-         Error("CreatePixmapFromData", "[QuartzImage alloc] failed");
-         delete [] imageData;
-         return Pixmap_t();
-      }
-   
-      QuartzImage *image = [mem.Get() initWithW : width H : height data : imageData];
-      if (!image) {
-         delete [] imageData;
-         Error("CreatePixmapFromData", "[QuartzImage initWithW:H:data:] failed");
-         return Pixmap_t();
-      }
-      
-      mem.Reset(image);
-      //Now imageData is owned by image.
-      image.fID = fPimpl->RegisterDrawable(image);//This can throw.
-      
-      return image.fID;      
-   } catch (const std::exception &) {//Bad alloc.
-      throw;
+   //I'm not using vector here, since I have to pass this pointer to Obj-C code
+   //(and Obj-C object will own this memory later).
+   unsigned char *imageData = new unsigned char[width * height * 4];
+   std::copy(bits, bits + width * height * 4, imageData);
+
+   //Convert bgra to rgba.
+   unsigned char *p = imageData;
+   for (unsigned i = 0, e = width * height; i < e; ++i, p += 4)
+      std::swap(p[0], p[2]);
+
+   //Now we can create CGImageRef.
+   Util::NSScopeGuard<QuartzImage> mem([QuartzImage alloc]);
+   if (!mem.Get()) {
+      Error("CreatePixmapFromData", "[QuartzImage alloc] failed");
+      delete [] imageData;
+      return Pixmap_t();
    }
 
-   return Pixmap_t();
+   QuartzImage *image = [mem.Get() initWithW : width H : height data : imageData];
+   if (!image) {
+      delete [] imageData;
+      Error("CreatePixmapFromData", "[QuartzImage initWithW:H:data:] failed");
+      return Pixmap_t();
+   }
+   
+   mem.Reset(image);
+   //Now imageData is owned by image.
+   image.fID = fPimpl->RegisterDrawable(image);//This can throw.
+   
+   return image.fID;      
 }
 
 //______________________________________________________________________________
@@ -1926,47 +1900,41 @@ Pixmap_t TGCocoa::CreateBitmap(Drawable_t /*wid*/, const char *bitmap, UInt_t wi
    //Create QuartzImage with image mask.
    assert(std::numeric_limits<unsigned char>::digits == 8 && "CreateBitmap, ASImage requires octets");
 
-   try {
-      //I'm not using vector here, since I have to pass this pointer to Obj-C code
-      //(and Obj-C object will own this memory later).
-      
-      //TASImage has a bug, it calculates size in pixels (making a with to multiple-of eight and 
-      //allocates memory as each bit occupies one byte, and later packs bits into bytes.
-      //Posylaiu luchi ponosa avtoru.
-
-      unsigned char *imageData = new unsigned char[width * height]();
-      for (unsigned i = 0, j = 0, e = width / 8 * height; i < e; ++i) {//TASImage supposes 8-bit bytes and packs mask bits.
-         for(unsigned bit = 0; bit < 8; ++bit, ++j) {
-            if (bitmap[i] & (1 << bit))
-               imageData[j] = 0;//Opaque.
-            else
-               imageData[j] = 255;//Masked out bit.
-         }
-      }
-
-      //Now we can create CGImageRef.
-      Util::NSScopeGuard<QuartzImage> mem([QuartzImage alloc]);
-      if (!mem.Get()) {
-         Error("CreateBitmap", "[QuartzImage alloc] failed");
-         delete [] imageData;
-         return Pixmap_t();
-      }
+   //I'm not using vector here, since I have to pass this pointer to Obj-C code
+   //(and Obj-C object will own this memory later).
    
-      QuartzImage *image = [mem.Get() initMaskWithW : width H : height bitmapMask: imageData];
-      if (!image) {
-         delete [] imageData;
-         return Pixmap_t();
+   //TASImage has a bug, it calculates size in pixels (making a with to multiple-of eight and 
+   //allocates memory as each bit occupies one byte, and later packs bits into bytes.
+   //Posylaiu luchi ponosa avtoru.
+
+   unsigned char *imageData = new unsigned char[width * height]();
+   for (unsigned i = 0, j = 0, e = width / 8 * height; i < e; ++i) {//TASImage supposes 8-bit bytes and packs mask bits.
+      for(unsigned bit = 0; bit < 8; ++bit, ++j) {
+         if (bitmap[i] & (1 << bit))
+            imageData[j] = 0;//Opaque.
+         else
+            imageData[j] = 255;//Masked out bit.
       }
-      
-      mem.Reset(image);
-      //Now, imageData is owned by image.
-      image.fID = fPimpl->RegisterDrawable(image);//This can throw.      
-      return image.fID;      
-   } catch (const std::exception &e) {//Bad alloc.
-      throw;
    }
 
-   return Pixmap_t();
+   //Now we can create CGImageRef.
+   Util::NSScopeGuard<QuartzImage> mem([QuartzImage alloc]);
+   if (!mem.Get()) {
+      Error("CreateBitmap", "[QuartzImage alloc] failed");
+      delete [] imageData;
+      return Pixmap_t();
+   }
+
+   QuartzImage *image = [mem.Get() initMaskWithW : width H : height bitmapMask: imageData];
+   if (!image) {//Error is already reported by QuartzImage.
+      delete [] imageData;
+      return Pixmap_t();
+   }
+   
+   mem.Reset(image);
+   //Now, imageData is owned by image.
+   image.fID = fPimpl->RegisterDrawable(image);//This can throw.      
+   return image.fID;      
 }
 
 //______________________________________________________________________________
@@ -2074,7 +2042,7 @@ FontStruct_t TGCocoa::LoadQueryFont(const char *fontName)
    //-foundry-family- ..... etc., some components can be omitted and replaced by *.
    assert(fontName != 0 && "LoadQueryFont, fontName is null");
 
-   ROOT::MacOSX::X11::XLFDName xlfd = {};
+   X11::XLFDName xlfd;
    if (ParseXLFDName(fontName, xlfd)) {
       //Make names more flexible: fFamilyName can be empty or '*'.
       if (!xlfd.fFamilyName.length() || xlfd.fFamilyName == "*")
@@ -2147,7 +2115,7 @@ char **TGCocoa::ListFonts(const char *fontName, Int_t maxNames, Int_t &count)
    count = 0;
 
    if (fontName && fontName[0]) {
-      X11::XLFDName xlfd = {};
+      X11::XLFDName xlfd;
       if (X11::ParseXLFDName(fontName, xlfd))
          return fPimpl->fFontManager.ListFonts(xlfd, maxNames, count);
    }
@@ -2412,6 +2380,8 @@ void TGCocoa::SetCursor(Window_t wid, Cursor_t cursorID)
    // window "wid".
    if (cursorID > 0)
       SetCursor(Int_t(wid), ECursor(cursorID - 1));
+   else
+      SetCursor(Int_t(wid), kPointer);
 }
 
 //______________________________________________________________________________
@@ -2428,12 +2398,118 @@ void TGCocoa::GetPasteBuffer(Window_t /*id*/, Atom_t /*atom*/, TString &/*text*/
 }
 
 //______________________________________________________________________________
+Window_t TGCocoa::CreateOpenGLWindow(Window_t parentID, UInt_t width, UInt_t height, const std::vector<std::pair<UInt_t, Int_t> > &formatComponents)
+{
+   //ROOT never creates GL widgets with 'root' as a parent (so not top-level gl-windows).
+   //If this change, assert must be deleted.
+   typedef std::pair<UInt_t, Int_t> component_type;
+   typedef std::vector<component_type>::size_type size_type;
+
+   assert(!fPimpl->IsRootWindow(parentID) && "CreateOpenGLWindow, could not create top-level gl window");
+   //Convert pairs into Cocoa's GL attributes.
+   
+
+   std::vector<NSOpenGLPixelFormatAttribute> attribs;
+   for (size_type i = 0, e = formatComponents.size(); i < e; ++i) {
+      const component_type &comp = formatComponents[i];
+      
+      if (comp.first == TGLFormat::kDoubleBuffer) {
+         attribs.push_back(NSOpenGLPFADoubleBuffer);
+      } else if (comp.first == TGLFormat::kDepth) {
+         attribs.push_back(NSOpenGLPFADepthSize);
+         attribs.push_back(comp.second > 0 ? comp.second : 32);
+      } else if (comp.first == TGLFormat::kAccum) {
+         attribs.push_back(NSOpenGLPFAAccumSize);
+         attribs.push_back(comp.second > 0 ? comp.second : 1);
+      } else if (comp.first == TGLFormat::kStencil) {
+         attribs.push_back(NSOpenGLPFAStencilSize);
+         attribs.push_back(comp.second > 0 ? comp.second : 8);
+      } else if (comp.first == TGLFormat::kMultiSample) {
+         attribs.push_back(NSOpenGLPFASampleBuffers);
+         attribs.push_back(1);
+         attribs.push_back(NSOpenGLPFASamples);
+         attribs.push_back(comp.second ? comp.second : 4);
+      }
+   }
+   
+   attribs.push_back(NSOpenGLPFAAccelerated);//??? I think, TGLWidget always wants this.
+   attribs.push_back(0);
+
+   NSOpenGLPixelFormat *pixelFormat = [[NSOpenGLPixelFormat alloc] initWithAttributes : &attribs[0]];
+   const Util::NSScopeGuard<NSOpenGLPixelFormat> formatGuard(pixelFormat);
+   
+   NSView<X11Window> *parentView = fPimpl->GetWindow(parentID).fContentView;
+   assert([parentView isKindOfClass : [QuartzView class]] && "CreateOpenGLWindow, parent view must be QuartzView");
+   
+   NSRect viewFrame = {};
+   viewFrame.size.width = width;
+   viewFrame.size.height = height;
+
+   ROOTOpenGLView *glView = [[ROOTOpenGLView alloc] initWithFrame : viewFrame pixelFormat : pixelFormat];
+   const Util::NSScopeGuard<ROOTOpenGLView> viewGuard(glView);
+   
+   [parentView addChild : glView];
+   const Window_t glID = fPimpl->RegisterDrawable(glView);
+   glView.fID = glID;
+
+   return glID;
+}
+
+//______________________________________________________________________________
+Handle_t TGCocoa::CreateOpenGLContext(Window_t windowID, Handle_t sharedID)
+{
+   assert(!fPimpl->IsRootWindow(windowID) && "CreateOpenGLContext, windowID is a 'root' window");
+
+   assert([fPimpl->GetWindow(windowID).fContentView isKindOfClass : [ROOTOpenGLView class]] && 
+          "CreateOpenGLContext, view is not an OpenGL view");
+   
+   ROOTOpenGLView *glView = (ROOTOpenGLView *)fPimpl->GetWindow(windowID).fContentView;
+   //At the moment I can not have several gl contenxts, created for the same view.
+   assert([glView openGLContext] == nil && "CreateOpenGLContext, view's context is not nil");
+   NSOpenGLPixelFormat *pixelFormat = glView.pixelFormat;
+
+   NSOpenGLContext *sharedContext = nil;
+
+   if (sharedID) {
+      NSObject<X11Window> *v = fPimpl->GetWindowForGLContext(sharedID);
+      assert([v isKindOfClass : [ROOTOpenGLView class]] && "CreateOpenGLContext, shared context's view is not an OpenGL view");
+      sharedContext = ((ROOTOpenGLView *)v).openGLContext;
+   }
+
+   Util::NSScopeGuard<NSOpenGLContext> newContext([[NSOpenGLContext alloc] initWithFormat : pixelFormat shareContext : sharedContext]);
+   glView.openGLContext = newContext.Get();   
+   const ULong_t ctxID = fPimpl->RegisterGLContextForView(windowID);
+   newContext.Release();
+
+   return ctxID;
+}
+
+//______________________________________________________________________________
 void TGCocoa::CreateOpenGLContext(Int_t /*wid*/)
 {
    // Creates OpenGL context for window "wid"
 }
 
 //______________________________________________________________________________
+Bool_t TGCocoa::MakeOpenGLContextCurrent(Handle_t ctx)
+{
+   assert(ctx > 0 && "MakeOpenGLContextCurrent, invalid context id");
+   
+   ROOTOpenGLView *glView = (ROOTOpenGLView *)fPimpl->GetWindowForGLContext(ctx);
+   [glView makeContextCurrent];
+   return [glView isGLContextCurrent];
+}
+
+//______________________________________________________________________________
+void TGCocoa::FlushOpenGLBuffer(Handle_t ctx)
+{
+   assert(ctx > 0 && "FlushOpenGLBuffer, invalid context id");
+
+   ROOTOpenGLView *glView = (ROOTOpenGLView *)fPimpl->GetWindowForGLContext(ctx);
+   [glView flushGLBuffer];
+}
+
+//______________________________________________________________________________
 void TGCocoa::DeleteOpenGLContext(Int_t /*wid*/)
 {
    // Deletes OpenGL context for window "wid"
@@ -2588,23 +2664,19 @@ void TGCocoa::SetDoubleBufferON()
          return;
    }
 
-   try {
-      Util::NSScopeGuard<QuartzPixmap> mem([QuartzPixmap alloc]);      
-      if (QuartzPixmap *pixmap = [mem.Get() initWithW : currW H : currH]) {
-         mem.Reset(pixmap);
-         pixmap.fID = fPimpl->RegisterDrawable(pixmap);//Can throw.
-         if (window.fBackBuffer) {//Now we can delete the old one, since the new was created.
-            if (fPimpl->fX11CommandBuffer.BufferSize())
-               fPimpl->fX11CommandBuffer.RemoveOperationsForDrawable(window.fBackBuffer.fID);
-            fPimpl->DeleteDrawable(window.fBackBuffer.fID);
-         }
-
-         window.fBackBuffer = pixmap;
-      } else {
-         Error("SetDoubleBufferON", "Can't create a pixmap");
+   Util::NSScopeGuard<QuartzPixmap> mem([QuartzPixmap alloc]);      
+   if (QuartzPixmap *pixmap = [mem.Get() initWithW : currW H : currH]) {
+      mem.Reset(pixmap);
+      pixmap.fID = fPimpl->RegisterDrawable(pixmap);//Can throw.
+      if (window.fBackBuffer) {//Now we can delete the old one, since the new was created.
+         if (fPimpl->fX11CommandBuffer.BufferSize())
+            fPimpl->fX11CommandBuffer.RemoveOperationsForDrawable(window.fBackBuffer.fID);
+         fPimpl->DeleteDrawable(window.fBackBuffer.fID);
       }
-   } catch (const std::exception &) {//std::bad_alloc.
-      throw;
+
+      window.fBackBuffer = pixmap;
+   } else {
+      Error("SetDoubleBufferON", "Can't create a pixmap");
    }
 }
 
@@ -2876,13 +2948,15 @@ void TGCocoa::DispatchClientMessage(UInt_t messageID)
    assert(widget.fID != 0 && "DispatchClientMessage, widget.fID is 0");
    
    TGWindow *window = gClient->GetWindowById(widget.fID);
-   assert(window != 0 && "DispatchClientMessage, no window was found");
    Event_t clientMessage = messageIter->second.second;
 
    fClientMessages.erase(messageIter);   
    fFreeMessageIDs.push_back(messageID);
 
-   window->HandleEvent(&clientMessage);
+   //Many thanks to ROOT's GUI, TGWindow can be deleted, but QuartzViews is still alive
+   //(DestroyWindow is never called for this window).
+   if (window)
+      window->HandleEvent(&clientMessage);
 }
 
 //______________________________________________________________________________
@@ -3054,6 +3128,10 @@ void TGCocoa::SetWMTransientHint(Window_t wid, Window_t mainWid)
       return;
    
    QuartzWindow *mainWindow = fPimpl->GetWindow(mainWid).fQuartzWindow;
+   
+   if (![mainWindow isVisible])
+      return;
+   
    QuartzWindow *transientWindow = fPimpl->GetWindow(wid).fQuartzWindow;
 
    if (mainWindow != transientWindow) {
diff --git a/graf2d/cocoa/src/X11Buffer.mm b/graf2d/cocoa/src/X11Buffer.mm
index f3c6fb0..70053b0 100644
--- a/graf2d/cocoa/src/X11Buffer.mm
+++ b/graf2d/cocoa/src/X11Buffer.mm
@@ -1,4 +1,4 @@
-// @(#)root/graf2d:$Id: X11Buffer.mm 44028 2012-04-30 12:27:45Z tpochep $
+// @(#)root/graf2d:$Id: X11Buffer.mm 44330 2012-05-29 11:30:29Z tpochep $
 // Author: Timur Pocheptsov   29/02/2012
 
 /*************************************************************************
@@ -474,6 +474,9 @@ void CommandBuffer::Flush(Details::CocoaPrivate *impl)
       
       QuartzView *view = (QuartzView *)impl->GetWindow(cmd->fID).fContentView;
       
+      if (prevView != view)
+         ClipOverlaps(view);
+      
       if (prevView && prevView != view && [[prevView subviews] count])
          RepaintTree(prevView);
       
@@ -490,6 +493,11 @@ void CommandBuffer::Flush(Details::CocoaPrivate *impl)
             CGContextFlush(prevContext);
          prevContext = currContext;
          
+         //Context can be modified by a clip mask.
+         const Quartz::CGStateGuard ctxGuard(currContext);
+         if (view.fClipMaskIsValid)
+            CGContextClipToMask(currContext, CGRectMake(0, 0, view.fClipMask.fWidth, view.fClipMask.fHeight), view.fClipMask.fImage);
+         
          cmd->Execute();
          if (view.fBackBuffer) {
             //Very "special" window.
@@ -502,6 +510,7 @@ void CommandBuffer::Flush(Details::CocoaPrivate *impl)
          }
          
          [view unlockFocus];
+         
          view.fContext = 0;
       }
    }
@@ -516,6 +525,57 @@ void CommandBuffer::Flush(Details::CocoaPrivate *impl)
 }
 
 //______________________________________________________________________________
+void CommandBuffer::ClipOverlaps(QuartzView *view)
+{
+   typedef std::vector<QuartzView *>::reverse_iterator reverse_iterator;
+
+   assert(view != nil && "ClipOverlaps, view parameter is nil");
+
+   fViewBranch.clear();
+   fViewBranch.reserve(view.fLevel + 1);
+   
+   for (QuartzView *v = view; v; v = v.fParentView)
+      fViewBranch.push_back(v);
+   
+   if (fViewBranch.size())
+      fViewBranch.pop_back();//we do not need content view, it does not have any sibling.
+
+   NSRect frame1 = {};
+   NSRect frame2 = view.frame;
+   
+   //[view clearClipMask];
+   view.fClipMaskIsValid = NO;
+   
+   for (reverse_iterator it = fViewBranch.rbegin(), eIt = fViewBranch.rend(); it != eIt; ++it) {
+      QuartzView *ancestorView = *it;//Actually, it's either one of ancestors, or a view itself.
+      bool doCheck = false;
+      for (QuartzView *sibling in [ancestorView.fParentView subviews]) {
+         if (ancestorView == sibling) {
+            doCheck = true;//all views after this must be checked.
+            continue;
+         } else if (!doCheck || sibling.fMapState != kIsViewable) {
+            continue;
+         }
+         
+         //Real check is here.
+         frame1 = sibling.frame;
+         frame2.origin = [view.fParentView convertPoint : view.frame.origin toView : ancestorView.fParentView];
+         
+         //Check if two rects intersect.
+         if (RectsOverlap(frame2, frame1)) {
+            if (!view.fClipMaskIsValid) {
+               if (![view initClipMask])//initClipMask will issue an error message.
+                  return;//Forget about clipping at all.
+               view.fClipMaskIsValid = YES;
+            }
+            //Update view's clip mask - mask out hidden pixels.
+            [view addOverlap : FindOverlapRect(frame2, frame1)];
+         }
+      }
+   }
+}
+
+//______________________________________________________________________________
 void CommandBuffer::RemoveOperationsForDrawable(Drawable_t drawable)
 {
    for (size_type i = 0; i < fCommands.size(); ++i) {
diff --git a/graf2d/cocoa/src/X11Events.mm b/graf2d/cocoa/src/X11Events.mm
index 0542416..2159cca 100644
--- a/graf2d/cocoa/src/X11Events.mm
+++ b/graf2d/cocoa/src/X11Events.mm
@@ -1,4 +1,4 @@
-// @(#)root/graf2d:$Id: X11Events.mm 44026 2012-04-30 09:32:25Z tpochep $
+// @(#)root/graf2d:$Id: X11Events.mm 44497 2012-06-04 08:54:58Z tpochep $
 // Author: Timur Pocheptsov   16/02/2012
 
 /*************************************************************************
@@ -16,6 +16,7 @@
 
 #include <Cocoa/Cocoa.h>
 
+#include "ROOTOpenGLView.h"
 #include "QuartzWindow.h"
 #include "CocoaUtils.h"
 #include "KeySymbols.h"
@@ -988,7 +989,8 @@ void EventTranslator::GenerateCrossingEvent(NSView<X11Window> *view, NSEvent *th
 
    if (fPointerGrab == kPGNoGrab) {
       NSView *candidateView = [[[view window] contentView] hitTest : [theEvent locationInWindow]];
-      if (candidateView && ![candidateView isKindOfClass : [QuartzView class]]) {//TODO: add a test for OpenGL view.
+      const bool isROOTView = [candidateView isKindOfClass : [QuartzView class]] || [candidateView isKindOfClass : [ROOTOpenGLView class]];
+      if (candidateView && !isROOTView) {
          NSLog(@"EventTranslator::GenerateCrossingEvent: error, hit test returned not a QuartzView!");
          candidateView = nil;
       }
@@ -1207,8 +1209,8 @@ void EventTranslator::SetPointerGrab(NSView<X11Window> *grabView, unsigned event
    assert(grabView != nil && "SetPointerGrab, view parameter is nil");
    
    //Now some magic to receive mouse move events even outside any window.
-   if (eventMask & kPointerMotionMask)
-      [[grabView window] setAcceptsMouseMovedEvents : YES];
+   //if (eventMask & kPointerMotionMask)
+   //   [[grabView window] setAcceptsMouseMovedEvents : YES];
    
    fButtonGrabView = grabView;
    fPointerGrab = kPGActiveGrab;
@@ -1222,7 +1224,7 @@ void EventTranslator::CancelPointerGrab()
    if (!fButtonGrabView)
       return;
       
-   [[fButtonGrabView window] setAcceptsMouseMovedEvents : NO];//Do not track mouse move events outside window anymore.
+   //[[fButtonGrabView window] setAcceptsMouseMovedEvents : NO];//Do not track mouse move events outside window anymore.
    
    fButtonGrabView = nil;
    fPointerGrab = kPGNoGrab;
@@ -1276,6 +1278,12 @@ void ClearPointerIfViewIsRelated(NSView<X11Window> *&view, Window_t winID)
 //______________________________________________________________________________
 void EventTranslator::CheckUnmappedView(Window_t winID)
 {
+   //Window was unmapped, check, if it's the same window as the current grab,
+   //or focus window, or key grabbing window and if so - do cleanup.
+   
+   //TODO: This is quite rough implementation - not sure, if this also has to 
+   //generate some additional events.
+
    if (fButtonGrabView) {
       for (NSView<X11Window> *view = fButtonGrabView; view; view = view.fParentView) {
          if (view.fID == winID) {
@@ -1352,6 +1360,10 @@ void EventTranslator::GeneratePointerMotionEventActiveGrab(NSView<X11Window> * /
 //______________________________________________________________________________
 void EventTranslator::GenerateButtonPressEventNoGrab(NSView<X11Window> *view, NSEvent *theEvent, EMouseButton btn)
 {
+   //Generate button press event when no pointer grab is active:
+   //either find a window with a passive grab, or create an implicit
+   //grab (to emulate X11's behavior).
+
    assert(view != nil && "GenerateButtonPressEventNoGrab, view parameter is nil");
    assert(theEvent != nil && "GenerateButtonPressEventNoGrab, event parameter is nil");
 
@@ -1372,6 +1384,8 @@ void EventTranslator::GenerateButtonPressEventNoGrab(NSView<X11Window> *view, NS
 //______________________________________________________________________________
 void EventTranslator::GenerateButtonPressEventActiveGrab(NSView<X11Window> * /*view*/, NSEvent *theEvent, EMouseButton btn)
 {
+   //Generate button press event in the presence of activated pointer grab.
+
    //TODO: change interface? remove view parameter from declaration.
 
    //assert(view != nil && "GenerateButtonPressEventActiveGrab, view parameter is nil");
@@ -1408,6 +1422,8 @@ void EventTranslator::GenerateButtonPressEventActiveGrab(NSView<X11Window> * /*v
 //______________________________________________________________________________
 void EventTranslator::GenerateButtonReleaseEventNoGrab(NSView<X11Window> *eventView, NSEvent *theEvent, EMouseButton btn)
 {
+   //Generate button release event when there is no active pointer grab.
+
    assert(eventView != nil && "GenerateButtonReleaseEventNoGrab, view parameter is nil");
    assert(theEvent != nil && "GenerateButtonReleaseEventNoGrabm event parameter is nil");
    
@@ -1418,6 +1434,8 @@ void EventTranslator::GenerateButtonReleaseEventNoGrab(NSView<X11Window> *eventV
 //______________________________________________________________________________
 void EventTranslator::GenerateButtonReleaseEventActiveGrab(NSView<X11Window> *eventView, NSEvent *theEvent, EMouseButton btn)
 {
+   //Generate button release event in the presence of active grab (explicit pointer grab, activated passive grab or implicit grab).
+
    assert(eventView != nil && "GenerateButtonReleaseEventActiveGrab, view parameter is nil");
    assert(theEvent != nil && "GenerateButtonReleaseEventActiveGrab, event parameter is nil");
    
@@ -1434,40 +1452,55 @@ void EventTranslator::GenerateButtonReleaseEventActiveGrab(NSView<X11Window> *ev
       return;
    }
    
+   bool needCrossingEvent = false;
+   
    if (fOwnerEvents) {//X11: Either XGrabPointer with owner_events == True or passive grab (owner_events is always true)
       SortTopLevelWindows();
       if (QuartzWindow *topLevel = FindTopLevelWindowForMouseEvent()) {
          const NSPoint mousePosition = [topLevel mouseLocationOutsideOfEventStream];
          NSView<X11Window> *candidateView = (NSView<X11Window> *)[[topLevel contentView] hitTest : mousePosition];
          if (candidateView) {
-            /*
-            bool continueSearch = true;
-            if (fPointerGrab == PointerGrab::passiveGrab && candidateView == fButtonGrabView) {
-               if (fGrabEventMask & kButtonReleaseMask)
-                  continueSearch = false;
-            }
-            //Do propagation.
-            if (continueSearch)*/
             candidateView = Detail::FindViewToPropagateEvent(candidateView, kButtonReleaseMask, fButtonGrabView, fGrabEventMask);
-            if (candidateView)//We have such a view, send event to a corresponding ROOT's window.
+            if (candidateView) {//We have such a view, send event to a corresponding ROOT's window.
+               needCrossingEvent = CancelImplicitOrPassiveGrab();
                Detail::SendButtonReleaseEvent(candidateView, theEvent, btn);
-         } else if (fGrabEventMask & kButtonReleaseMask)
-            Detail::SendButtonReleaseEvent(fButtonGrabView, theEvent, btn);
+            }
+         } else if (fGrabEventMask & kButtonReleaseMask) {
+            NSView<X11Window> *grabView = fButtonGrabView;
+            needCrossingEvent = CancelImplicitOrPassiveGrab();
+            Detail::SendButtonReleaseEvent(grabView, theEvent, btn);
+         }
       } else {//Report to the grab view, if it has a corresponding bit set.
-         if (fGrabEventMask & kButtonReleaseMask)
-            Detail::SendButtonReleaseEvent(fButtonGrabView, theEvent, btn);
+         if (fGrabEventMask & kButtonReleaseMask) {
+            NSView<X11Window> *grabView = fButtonGrabView;
+            needCrossingEvent = CancelImplicitOrPassiveGrab();
+            Detail::SendButtonReleaseEvent(grabView, theEvent, btn);
+         }
       }
    } else {//Either implicit grab or XGrabPointer with owner_events == False.
-      if (fGrabEventMask & kButtonReleaseMask)
-         Detail::SendButtonReleaseEvent(fButtonGrabView, theEvent, btn);   
+      if (fGrabEventMask & kButtonReleaseMask) {
+         NSView<X11Window> *grabView = fButtonGrabView;
+         needCrossingEvent = CancelImplicitOrPassiveGrab();
+         Detail::SendButtonReleaseEvent(grabView, theEvent, btn);   
+      }
    }
    
+   if (needCrossingEvent || CancelImplicitOrPassiveGrab())
+      GenerateCrossingEvent(eventView, theEvent, kNotifyUngrab);
+}
+
+//______________________________________________________________________________
+bool EventTranslator::CancelImplicitOrPassiveGrab()
+{
+   //Cancel the current grab, if it's implicit or passive button grab.
+
    if (fPointerGrab == kPGPassiveGrab || fPointerGrab == kPGImplicitGrab) {
       fButtonGrabView = nil;
       fPointerGrab = kPGNoGrab;
-
-      GenerateCrossingEvent(eventView, theEvent, kNotifyUngrab);
+      return true;
    }
+   
+   return false;
 }
 
 //______________________________________________________________________________
diff --git a/graf2d/cocoa/src/XLFDParser.mm b/graf2d/cocoa/src/XLFDParser.mm
index bb3cd61..84cc603 100644
--- a/graf2d/cocoa/src/XLFDParser.mm
+++ b/graf2d/cocoa/src/XLFDParser.mm
@@ -1,4 +1,4 @@
-// @(#)root/graf2d:$Id: XLFDParser.mm 44123 2012-05-04 15:39:17Z tpochep $
+// @(#)root/graf2d:$Id: XLFDParser.mm 44201 2012-05-09 15:17:36Z tpochep $
 // Author: Timur Pocheptsov   2/03/2012
 
 /*************************************************************************
@@ -122,7 +122,13 @@ size_type ParseWeight(const std::string &name, size_type pos, XLFDName &dst)
    //and integer.
    std::string weight;
    pos = GetXLFDNameComponentAsString(name, "weight", pos, weight);
-   weight == "bold" ? dst.fWeight = kFWBold : dst.fWeight = kFWMedium;
+
+   if (weight == "*")
+      dst.fWeight = kFWAny;
+   else if (weight == "bold")
+      dst.fWeight = kFWBold;
+   else
+      dst.fWeight = kFWMedium;
 
    return pos;
 }
@@ -135,11 +141,13 @@ size_type ParseSlant(const std::string &name, size_type pos, XLFDName &dst)
    std::string slant;
    pos = GetXLFDNameComponentAsString(name, "slant", pos, slant);
 
-   //Can be 'r', 'R', 'i', 'I', 'o', 'O', and now I add also '*' - let it be regular.
-   dst.fSlant = kFSRegular;
-
-   if (slant == "i" || slant == "I" || slant == "o" || slant == "O")
+   //Can be 'r', 'R', 'i', 'I', 'o', 'O', '*'.
+   if (slant == "*")
+      dst.fSlant = kFSAny;
+   else if (slant == "i" || slant == "I" || slant == "o" || slant == "O")
       dst.fSlant = kFSItalic;
+   else
+      dst.fSlant = kFSRegular;   
 
    return pos;
 }
@@ -239,6 +247,14 @@ size_type ParseEncoding(const std::string &name, size_type pos, XLFDName &dst)
 }//Anonymous namespace.
 
 //______________________________________________________________________________
+XLFDName::XLFDName()
+            : fWeight(kFWAny),
+              fSlant(kFSAny),
+              fPixelSize(0)
+{
+}
+
+//______________________________________________________________________________
 bool ParseXLFDName(const std::string &xlfdName, XLFDName &dst)
 {
    const size_type nameLength = xlfdName.length();
diff --git a/gui/gui/src/TGCanvas.cxx b/gui/gui/src/TGCanvas.cxx
index 607a83c..ab60981 100644
--- a/gui/gui/src/TGCanvas.cxx
+++ b/gui/gui/src/TGCanvas.cxx
@@ -1,4 +1,4 @@
-// @(#)root/gui:$Id: TGCanvas.cxx 43910 2012-04-23 18:03:12Z tpochep $
+// @(#)root/gui:$Id: TGCanvas.cxx 44201 2012-05-09 15:17:36Z tpochep $
 // Author: Fons Rademakers   11/01/98
 
 /*************************************************************************
@@ -792,13 +792,16 @@ void TGContainer::SetPageDimension(UInt_t w, UInt_t h)
 void TGContainer::DoRedraw()
 {
    // Redraw content of container in the viewport region.
-
+#ifdef R__HAS_COCOA
+   DrawRegion(0, 0, GetWidth(), GetHeight());
+#else
    if (!fExposedRegion.IsEmpty()) {
       DrawRegion(fExposedRegion.fX, fExposedRegion.fY, 
                  fExposedRegion.fW, fExposedRegion.fH);
       
       fExposedRegion.Empty();
    }
+#endif
 }
 
 //______________________________________________________________________________
diff --git a/gui/gui/src/TGFontDialog.cxx b/gui/gui/src/TGFontDialog.cxx
index 49f7e04..fe7148e 100644
--- a/gui/gui/src/TGFontDialog.cxx
+++ b/gui/gui/src/TGFontDialog.cxx
@@ -1,4 +1,4 @@
-// @(#)root/gui:$Id: TGFontDialog.cxx 39352 2011-05-24 10:34:40Z bellenot $
+// @(#)root/gui:$Id: TGFontDialog.cxx 44201 2012-05-09 15:17:36Z tpochep $
 // Author: Bertrand Bellenot + Fons Rademakers + Valeriy Onuchin  23/04/03
 
 /*************************************************************************
@@ -180,9 +180,10 @@ TGFontDialog::TGFontDialog(const TGWindow *p, const TGWindow *t,
    fFontNames = new TGListBox(vf, kFDLG_FONTNAMES);
    fFontNames->Resize(120, fFontNames->GetDefaultHeight());
 
-   if (gVirtualX->InheritsFrom("TGX11")) {
+   if (gVirtualX->InheritsFrom("TGX11") || gVirtualX->InheritsFrom("TGCocoa")) {
       fFontNames->Connect("Selected(char*)", "TGFontDialog", this, "UpdateStyleSize(char*)");
    }
+
    fFontNames->Associate(this);
    vf->AddFrame(fFontNames,  new TGLayoutHints(kLHintsExpandX | kLHintsExpandY));
 
@@ -580,6 +581,13 @@ void TGFontDialog::UpdateStyleSize(const char *family)
    Bool_t x11 = gVirtualX->InheritsFrom("TGX11");
    Bool_t all_sizes = !x11;
    Bool_t all_styles = !x11;
+   
+   //
+   if (gVirtualX->InheritsFrom("TGCocoa")) {
+      all_sizes = kTRUE;
+      all_styles = kFALSE;
+   }
+   
    int szn = 0;
 
    fFontSizes->AddEntry("12", szn++);
diff --git a/hist/hist/inc/TH2.h b/hist/hist/inc/TH2.h
index fa0096a..d81c1ed 100644
--- a/hist/hist/inc/TH2.h
+++ b/hist/hist/inc/TH2.h
@@ -1,4 +1,4 @@
-// @(#)root/hist:$Id: TH2.h 42958 2012-02-10 14:47:09Z moneta $
+// @(#)root/hist:$Id: TH2.h 44515 2012-06-04 14:16:56Z moneta $
 // Author: Rene Brun   26/12/94
 
 /*************************************************************************
@@ -53,19 +53,20 @@ protected:
    TH2(const char *name,const char *title,Int_t nbinsx,const Float_t  *xbins
                                          ,Int_t nbinsy,const Float_t  *ybins);
 
-   virtual Int_t     BufferFill(Double_t, Double_t) {return -2;} //may not use
    virtual Int_t     BufferFill(Double_t x, Double_t y, Double_t w);
    virtual TH1D     *DoProjection(bool onX, const char *name, Int_t firstbin, Int_t lastbin, Option_t *option) const;
    virtual TProfile *DoProfile(bool onX, const char *name, Int_t firstbin, Int_t lastbin, Option_t *option) const;
    virtual void      DoFitSlices(bool onX, TF1 *f1, Int_t firstbin, Int_t lastbin, Int_t cut, Option_t *option, TObjArray* arr);
 
+   Int_t    BufferFill(Double_t, Double_t) {return -2;} //may not use
+   Int_t    Fill(Double_t); //MayNotUse
+   Int_t    Fill(const char*, Double_t) { return Fill(0);}  //MayNotUse
+
 public:
    TH2(const TH2&);
    virtual ~TH2();
    virtual Int_t    BufferEmpty(Int_t action=0);
    virtual void     Copy(TObject &hnew) const;
-           Int_t    Fill(Double_t) {return -1;} //MayNotUse
-           Int_t    Fill(const char*, Double_t) {return -1;} //MayNotUse
    virtual Int_t    Fill(Double_t x, Double_t y);
    virtual Int_t    Fill(Double_t x, Double_t y, Double_t w);
    virtual Int_t    Fill(Double_t x, const char *namey, Double_t w);
diff --git a/hist/hist/inc/TH3.h b/hist/hist/inc/TH3.h
index 29486db..67172ca 100644
--- a/hist/hist/inc/TH3.h
+++ b/hist/hist/inc/TH3.h
@@ -1,4 +1,4 @@
-// @(#)root/hist:$Id: TH3.h 43732 2012-04-13 13:40:14Z moneta $
+// @(#)root/hist:$Id: TH3.h 44515 2012-06-04 14:16:56Z moneta $
 // Author: Rene Brun   27/10/95
 
 /*************************************************************************
@@ -53,23 +53,24 @@ protected:
    TH3(const char *name,const char *title,Int_t nbinsx,const Double_t *xbins
                                          ,Int_t nbinsy,const Double_t *ybins
                                          ,Int_t nbinsz,const Double_t *zbins);
-   virtual Int_t    BufferFill(Double_t, Double_t) {return -2;} //may not use
-   virtual Int_t    BufferFill(Double_t, Double_t, Double_t) {return -2;} //may not use
    virtual Int_t    BufferFill(Double_t x, Double_t y, Double_t z, Double_t w);
 
    void DoFillProfileProjection(TProfile2D * p2, const TAxis & a1, const TAxis & a2, const TAxis & a3, Int_t bin1, Int_t bin2, Int_t bin3, Int_t inBin, Bool_t useWeights) const;
 
+   virtual Int_t    BufferFill(Double_t, Double_t) {return -2;} //may not use
+   virtual Int_t    BufferFill(Double_t, Double_t, Double_t) {return -2;} //may not use
+   Int_t    Fill(Double_t);        //MayNotUse
+   Int_t    Fill(Double_t,Double_t) {return Fill(0.);} //MayNotUse
+   Int_t    Fill(const char*, Double_t) {return Fill(0);} //MayNotUse
+   Int_t    Fill(Double_t,const char*,Double_t) {return Fill(0);} //MayNotUse
+   Int_t    Fill(const char*,Double_t,Double_t) {return Fill(0);} //MayNotUse
+   Int_t    Fill(const char*,const char*,Double_t) {return Fill(0);} //MayNotUse
+
 public:
    TH3(const TH3&);
    virtual ~TH3();
    virtual Int_t    BufferEmpty(Int_t action=0);
    virtual void     Copy(TObject &hnew) const;
-           Int_t    Fill(Double_t) {return -1;}        //MayNotUse
-           Int_t    Fill(Double_t,Double_t) {return -1;} //MayNotUse
-           Int_t    Fill(const char*, Double_t) {return -1;} //MayNotUse
-           Int_t    Fill(Double_t,const char*,Double_t) {return -1;} //MayNotUse
-           Int_t    Fill(const char*,Double_t,Double_t) {return -1;} //MayNotUse
-           Int_t    Fill(const char*,const char*,Double_t) {return -1;} //MayNotUse
    virtual Int_t    Fill(Double_t x, Double_t y, Double_t z);
    virtual Int_t    Fill(Double_t x, Double_t y, Double_t z, Double_t w);
 
diff --git a/hist/hist/inc/TProfile2D.h b/hist/hist/inc/TProfile2D.h
index 7ee4025..5bebabd 100644
--- a/hist/hist/inc/TProfile2D.h
+++ b/hist/hist/inc/TProfile2D.h
@@ -1,4 +1,4 @@
-// @(#)root/hist:$Id: TProfile2D.h 43802 2012-04-17 15:20:48Z moneta $
+// @(#)root/hist:$Id: TProfile2D.h 44515 2012-06-04 14:16:56Z moneta $
 // Author: Rene Brun   16/04/2000
 
 /*************************************************************************
@@ -53,6 +53,10 @@ protected:
                                                                      nbins[1], range[2], range[3]); };
    Int_t Fill(const Double_t* v) { return Fill(v[0], v[1], v[2], v[3]); };
 
+   using TH2::Fill;
+   Int_t             Fill(Double_t, Double_t) {return TH2::Fill(0); } //MayNotUse
+
+
 private:
    Double_t *GetB()  {return &fBinEntries.fArray[0];}
    Double_t *GetB2() {return (fBinSumw2.fN ? &fBinSumw2.fArray[0] : 0 ); }
@@ -93,9 +97,6 @@ public:
    virtual Bool_t    Divide(const TH1 *h1);
    virtual Bool_t    Divide(const TH1 *h1, const TH1 *h2, Double_t c1=1, Double_t c2=1, Option_t *option=""); // *MENU*
    virtual TH1      *DrawCopy(Option_t *option="") const;
-   Int_t             Fill(Double_t) {return -1;} //MayNotUse
-   Int_t             Fill(const char*, Double_t) {return -1;} //MayNotUse
-   Int_t             Fill(Double_t, Double_t) {return -1; } //MayNotUse
    Int_t             Fill(Double_t x, Double_t y, Double_t z);
    virtual Int_t     Fill(Double_t x, const char *namey, Double_t z);
    virtual Int_t     Fill(const char *namex, Double_t y, Double_t z);
diff --git a/hist/hist/inc/TProfile3D.h b/hist/hist/inc/TProfile3D.h
index d80b37f..858569b 100644
--- a/hist/hist/inc/TProfile3D.h
+++ b/hist/hist/inc/TProfile3D.h
@@ -1,4 +1,4 @@
-// @(#)root/hist:$Id: TProfile3D.h 43802 2012-04-17 15:20:48Z moneta $
+// @(#)root/hist:$Id: TProfile3D.h 44515 2012-06-04 14:16:56Z moneta $
 // Author: Rene Brun   17/05/2006
 
 /*************************************************************************
@@ -54,6 +54,17 @@ protected:
                                                                     nbins[1], range[2], range[3], 
                                                                     nbins[2], range[4], range[5]); };
    Int_t Fill(const Double_t* v) { return Fill(v[0], v[1], v[2], v[3], v[4]); };
+
+
+   using TH3::Fill;
+   Int_t             Fill(Double_t, Double_t,Double_t) {return TH3::Fill(0); } //MayNotUse
+   Int_t             Fill(const char *, const char *, const char *, Double_t) {return TH3::Fill(0); } //MayNotUse
+   Int_t             Fill(const char *, Double_t , const char *, Double_t) {return TH3::Fill(0); } //MayNotUse
+   Int_t             Fill(const char *, const char *, Double_t, Double_t) {return TH3::Fill(0); } //MayNotUse
+   Int_t             Fill(Double_t, const char *, const char *, Double_t) {return TH3::Fill(0); } //MayNotUse
+   Int_t             Fill(Double_t, const char *, Double_t, Double_t) {return TH3::Fill(0); } //MayNotUse
+   Int_t             Fill(Double_t, Double_t, const char *, Double_t) {return TH3::Fill(0); } //MayNotUse
+
    
 private:
    Double_t *GetB()  {return &fBinEntries.fArray[0];}
@@ -90,16 +101,6 @@ public:
    virtual Bool_t    Divide(const TH1 *h1);
    virtual Bool_t    Divide(const TH1 *h1, const TH1 *h2, Double_t c1=1, Double_t c2=1, Option_t *option=""); // *MENU*
    virtual TH1      *DrawCopy(Option_t *option="") const;
-   Int_t             Fill(Double_t) {return -1;} //MayNotUse
-   Int_t             Fill(const char*, Double_t) {return -1;} //MayNotUse
-   Int_t             Fill(Double_t, Double_t) {return -1; } //MayNotUse
-   Int_t             Fill(Double_t, Double_t,Double_t) {return -1; } //MayNotUse
-   Int_t             Fill(const char *, const char *, const char *, Double_t) {return -1; } //MayNotUse
-   Int_t             Fill(const char *, Double_t , const char *, Double_t) {return -1; } //MayNotUse
-   Int_t             Fill(const char *, const char *, Double_t, Double_t) {return -1; } //MayNotUse
-   Int_t             Fill(Double_t, const char *, const char *, Double_t) {return -1; } //MayNotUse
-   Int_t             Fill(Double_t, const char *, Double_t, Double_t) {return -1; } //MayNotUse
-   Int_t             Fill(Double_t, Double_t, const char *, Double_t) {return -1; } //MayNotUse
    virtual Int_t     Fill(Double_t x, Double_t y, Double_t z, Double_t t);
    virtual Int_t     Fill(Double_t x, Double_t y, Double_t z, Double_t t, Double_t w);
    virtual Double_t  GetBinContent(Int_t bin) const;
diff --git a/hist/hist/src/HFitImpl.cxx b/hist/hist/src/HFitImpl.cxx
index e20273a..afcd3af 100644
--- a/hist/hist/src/HFitImpl.cxx
+++ b/hist/hist/src/HFitImpl.cxx
@@ -560,6 +560,7 @@ void HFit::StoreAndDrawFitFunction(FitObject * h1, const TF1 * f1, const ROOT::F
    // copy TF1 using TClass to avoid slicing in case of derived classes
    if (ndim < 2) {
       fnew1 = (TF1*)f1->IsA()->New();
+      R__ASSERT(fnew1);
       f1->Copy(*fnew1);
       funcList->Add(fnew1);
       fnew1->SetParent( h1 );
@@ -569,6 +570,7 @@ void HFit::StoreAndDrawFitFunction(FitObject * h1, const TF1 * f1, const ROOT::F
       fnew1->SetBit(TFormula::kNotGlobal);
    } else if (ndim < 3) {
       fnew2 = (TF2*)f1->IsA()->New();
+      R__ASSERT(fnew2);
       f1->Copy(*fnew2);
       funcList->Add(fnew2);
       fnew2->SetRange(xmin,ymin,xmax,ymax);
@@ -579,6 +581,7 @@ void HFit::StoreAndDrawFitFunction(FitObject * h1, const TF1 * f1, const ROOT::F
    } else {
       // 3D- why f3d is not saved ???
       fnew3 = (TF3*)f1->IsA()->New();
+      R__ASSERT(fnew3);
       f1->Copy(*fnew3);
       funcList->Add(fnew3);
       fnew3->SetRange(xmin,ymin,zmin,xmax,ymax,zmax);
diff --git a/hist/hist/src/HFitInterface.cxx b/hist/hist/src/HFitInterface.cxx
index e048d1a..322ee81 100644
--- a/hist/hist/src/HFitInterface.cxx
+++ b/hist/hist/src/HFitInterface.cxx
@@ -1,4 +1,4 @@
-// @(#)root/hist:$Id: HFitInterface.cxx 42694 2012-01-18 13:09:09Z axel $
+// @(#)root/hist:$Id: HFitInterface.cxx 44270 2012-05-16 12:58:34Z moneta $
 // Author: L. Moneta Thu Aug 31 10:40:20 2006
 
 /**********************************************************************
@@ -632,9 +632,10 @@ void DoFillData ( BinData  & dv,  const TGraph * gr,  BinData::ErrorType type, T
 
          // adjust error in y according to option 
          double errorY = std::max(gr->GetErrorY(i), 0.); 
+         // we do not check the return value since we check later if error in X and Y is zero for skipping the point
          HFitInterface::AdjustError(fitOpt, errorY); 
 
-         // skip points with totla error = 0
+         // skip points with total error = 0
          if ( errorX <=0 && errorY <= 0 ) continue; 
          
          if (type == BinData::kAsymError)   { 
diff --git a/hist/hist/src/TF1.cxx b/hist/hist/src/TF1.cxx
index f0f5427..eb209a4 100644
--- a/hist/hist/src/TF1.cxx
+++ b/hist/hist/src/TF1.cxx
@@ -1,4 +1,4 @@
-// @(#)root/hist:$Id: TF1.cxx 38123 2011-02-17 17:15:26Z moneta $
+// @(#)root/hist:$Id: TF1.cxx 44216 2012-05-10 12:51:36Z moneta $
 // Author: Rene Brun   18/08/95
 
 /*************************************************************************
@@ -1082,6 +1082,8 @@ void TF1::Browse(TBrowser *b)
 void TF1::Copy(TObject &obj) const
 {
    // Copy this F1 to a new F1.
+   // Note that the cached integral with its related arrays are not copied
+   // (they are also set as transient data members) 
 
    if (((TF1&)obj).fParMin)    delete [] ((TF1&)obj).fParMin;
    if (((TF1&)obj).fParMax)    delete [] ((TF1&)obj).fParMax;
@@ -3058,8 +3060,8 @@ void TF1::SavePrimitive(ostream &out, Option_t *option /*= ""*/)
       out<<"   "<<GetName()<<"->SetNDF("<<GetNDF()<<");"<<endl;
    }
 
-   GetXaxis()->SaveAttributes(out,GetName(),"->GetXaxis()");
-   GetYaxis()->SaveAttributes(out,GetName(),"->GetYaxis()");
+   if (GetXaxis()) GetXaxis()->SaveAttributes(out,GetName(),"->GetXaxis()");
+   if (GetYaxis()) GetYaxis()->SaveAttributes(out,GetName(),"->GetYaxis()");
 
    Double_t parmin, parmax;
    for (i=0;i<fNpar;i++) {
diff --git a/hist/hist/src/TF2.cxx b/hist/hist/src/TF2.cxx
index eadcdb5..4f902d0 100644
--- a/hist/hist/src/TF2.cxx
+++ b/hist/hist/src/TF2.cxx
@@ -1,4 +1,4 @@
-// @(#)root/hist:$Id: TF2.cxx 37914 2011-01-31 15:47:54Z moneta $
+// @(#)root/hist:$Id: TF2.cxx 44216 2012-05-10 12:51:36Z moneta $
 // Author: Rene Brun   23/08/95
 
 /*************************************************************************
@@ -440,6 +440,10 @@ void TF2::GetMinimumXY(Double_t &x, Double_t &y)
    }
 
    TVirtualFitter *minuit = TVirtualFitter::Fitter(this, 2);
+   if (!minuit) { 
+      Error("GetMinimumXY", "Cannot create fitter");
+      return;
+   }
    minuit->Clear();
    minuit->SetFitMethod("F2Minimizer");
    Double_t arglist[10];
diff --git a/hist/hist/src/TF3.cxx b/hist/hist/src/TF3.cxx
index f489254..1b64e34 100644
--- a/hist/hist/src/TF3.cxx
+++ b/hist/hist/src/TF3.cxx
@@ -1,4 +1,4 @@
-// @(#)root/hist:$Id: TF3.cxx 37914 2011-01-31 15:47:54Z moneta $
+// @(#)root/hist:$Id: TF3.cxx 44216 2012-05-10 12:51:36Z moneta $
 // Author: Rene Brun   27/10/95
 
 /*************************************************************************
@@ -329,6 +329,10 @@ void TF3::GetMinimumXYZ(Double_t &x, Double_t &y, Double_t &z)
    }
 
    TVirtualFitter *minuit = TVirtualFitter::Fitter(this, 3);
+   if (!minuit) { 
+      Error("GetMinimumXYZ", "Cannot create fitter");
+      return;
+   }
    minuit->Clear();
    minuit->SetFitMethod("F3Minimizer");
    Double_t arglist[10];
diff --git a/hist/hist/src/TFormula.cxx b/hist/hist/src/TFormula.cxx
index a9c60ee..e7b2832 100644
--- a/hist/hist/src/TFormula.cxx
+++ b/hist/hist/src/TFormula.cxx
@@ -1,4 +1,4 @@
-// @(#)root/hist:$Id: TFormula.cxx 43508 2012-03-27 15:48:54Z pcanal $
+// @(#)root/hist:$Id: TFormula.cxx 44270 2012-05-16 12:58:34Z moneta $
 // Author: Nicolas Brun   19/08/95
 
 /*************************************************************************
@@ -3426,7 +3426,10 @@ void TFormula::Streamer(TBuffer &b)
             Int_t npar = fNpar;
             fParams = 0;
             fNames = 0;
-            Compile();
+            if (Compile()) {
+               Error("Streamer","error compiling formula");
+               return;
+            }
             for (Int_t i = 0; i<npar && i<fNpar; ++i) fParams[i] = param[i];
             delete [] param;
             delete [] fNames;
diff --git a/hist/hist/src/TGraph.cxx b/hist/hist/src/TGraph.cxx
index a02a960..70a8946 100644
--- a/hist/hist/src/TGraph.cxx
+++ b/hist/hist/src/TGraph.cxx
@@ -1,4 +1,4 @@
-// @(#)root/hist:$Id: TGraph.cxx 44012 2012-04-30 06:21:51Z moneta $
+// @(#)root/hist:$Id: TGraph.cxx 44216 2012-05-10 12:51:36Z moneta $
 // Author: Rene Brun, Olivier Couet   12/12/94
 
 /*************************************************************************
@@ -203,6 +203,8 @@ TGraph& TGraph::operator=(const TGraph &gr)
       else fHistogram = 0;
       fMinimum = gr.fMinimum;
       fMaximum = gr.fMaximum;
+      if (fX) delete [] fX;
+      if (fY) delete [] fY;
       if (!fMaxSize) {
          fX = fY = 0;
          return *this;
@@ -730,6 +732,8 @@ Bool_t TGraph::CtorAllocate()
 {
    // In constructors set fNpoints than call this method.
    // Return kFALSE if the graph will contain no points.
+   //Note: This function should be called only from the constructor
+   // since it does not delete previously existing arrays
 
    fHistogram = 0;
    fMaximum = -1111;
diff --git a/hist/hist/src/TGraph2D.cxx b/hist/hist/src/TGraph2D.cxx
index ae24227..a4f124f 100644
--- a/hist/hist/src/TGraph2D.cxx
+++ b/hist/hist/src/TGraph2D.cxx
@@ -1494,7 +1494,8 @@ void TGraph2D::SetMaximum(Double_t maximum)
    // Set maximum.
 
    fMaximum = maximum;
-   GetHistogram()->SetMaximum(maximum);
+   TH1 * h = GetHistogram();
+   if (h) h->SetMaximum(maximum);
 }
 
 
@@ -1504,7 +1505,8 @@ void TGraph2D::SetMinimum(Double_t minimum)
    // Set minimum.
 
    fMinimum = minimum;
-   GetHistogram()->SetMinimum(minimum);
+   TH1 * h = GetHistogram();
+   if (h) h->SetMinimum(minimum);
 }
 
 
diff --git a/hist/hist/src/TGraphAsymmErrors.cxx b/hist/hist/src/TGraphAsymmErrors.cxx
index 649cfcb..3128cf7 100644
--- a/hist/hist/src/TGraphAsymmErrors.cxx
+++ b/hist/hist/src/TGraphAsymmErrors.cxx
@@ -1,4 +1,4 @@
-// @(#)root/hist:$Id: TGraphAsymmErrors.cxx 43691 2012-04-10 18:34:14Z moneta $
+// @(#)root/hist:$Id: TGraphAsymmErrors.cxx 44216 2012-05-10 12:51:36Z moneta $
 // Author: Rene Brun   03/03/99
 
 /*************************************************************************
@@ -99,6 +99,12 @@ TGraphAsymmErrors& TGraphAsymmErrors::operator=(const TGraphAsymmErrors &gr)
 
    if(this!=&gr) {
       TGraph::operator=(gr);
+      // delete arrays 
+      if (fEXlow) delete [] fEXlow; 
+      if (fEYlow) delete [] fEYlow; 
+      if (fEXhigh) delete [] fEXhigh; 
+      if (fEYhigh) delete [] fEYhigh; 
+
       if (!CtorAllocate()) return *this;
       Int_t n = fNpoints*sizeof(Double_t);
       memcpy(fEXlow, gr.fEXlow, n);
@@ -802,6 +808,8 @@ Bool_t TGraphAsymmErrors::CopyPoints(Double_t **arrays,
 Bool_t TGraphAsymmErrors::CtorAllocate(void)
 {
    // Should be called from ctors after fNpoints has been set
+   // Note: This function should be called only from the constructor
+   // since it does not delete previously existing arrays
 
    if (!fNpoints) {
       fEXlow = fEYlow = fEXhigh = fEYhigh = 0;
diff --git a/hist/hist/src/TGraphErrors.cxx b/hist/hist/src/TGraphErrors.cxx
index 1ae60b4..9130297 100644
--- a/hist/hist/src/TGraphErrors.cxx
+++ b/hist/hist/src/TGraphErrors.cxx
@@ -1,4 +1,4 @@
-// @(#)root/hist:$Id: TGraphErrors.cxx 44012 2012-04-30 06:21:51Z moneta $
+// @(#)root/hist:$Id: TGraphErrors.cxx 44216 2012-05-10 12:51:36Z moneta $
 // Author: Rene Brun   15/09/96
 
 /*************************************************************************
@@ -197,6 +197,9 @@ TGraphErrors& TGraphErrors::operator=(const TGraphErrors &gr)
 
    if (this != &gr) {
       TGraph::operator=(gr);
+      // N.B CtorAllocate does not delete arrays
+      if (fEX) delete [] fEX; 
+      if (fEY) delete [] fEY; 
       if (!CtorAllocate()) return *this;
 
       Int_t n = sizeof(Double_t) * fNpoints;
@@ -518,6 +521,9 @@ Bool_t TGraphErrors::CopyPoints(Double_t **arrays, Int_t ibegin, Int_t iend,
 Bool_t TGraphErrors::CtorAllocate()
 {
    // Constructor allocate.
+   //Note: This function should be called only from the constructor
+   // since it does not delete previously existing arrays
+
 
    if (!fNpoints) {
       fEX = fEY = 0;
diff --git a/hist/hist/src/TH1.cxx b/hist/hist/src/TH1.cxx
index 2ff3a30..559eebe 100644
--- a/hist/hist/src/TH1.cxx
+++ b/hist/hist/src/TH1.cxx
@@ -1,4 +1,4 @@
-// @(#)root/hist:$Id: TH1.cxx 44122 2012-05-04 15:15:01Z moneta $
+// @(#)root/hist:$Id: TH1.cxx 44270 2012-05-16 12:58:34Z moneta $
 // Author: Rene Brun   26/12/94
 
 /*************************************************************************
@@ -2393,25 +2393,39 @@ void TH1::Copy(TObject &obj) const
    ((TH1&)obj).fBarOffset = fBarOffset;
    ((TH1&)obj).fBarWidth  = fBarWidth;
    ((TH1&)obj).fOption    = fOption;
-   ((TH1&)obj).fBuffer    = 0;
    ((TH1&)obj).fBufferSize= fBufferSize;
+   // copy the Buffer 
+   // delete first a previously existing buffer
+   if (((TH1&)obj).fBuffer != 0)  { 
+      delete []  ((TH1&)obj).fBuffer;
+      ((TH1&)obj).fBuffer = 0;
+   }
+   if (fBuffer) {
+      Double_t *buf = new Double_t[fBufferSize];
+      for (Int_t i=0;i<fBufferSize;i++) buf[i] = fBuffer[i];
+      // obj.fBuffer has been deleted before
+      ((TH1&)obj).fBuffer    = buf;
+   }
+
 
    TArray* a = dynamic_cast<TArray*>(&obj);
    if (a) a->Set(fNcells);
    Int_t canRebin = ((TH1&)obj).TestBit(kCanRebin);
    ((TH1&)obj).ResetBit(kCanRebin);  //we want to avoid the call to LabelsInflate
+   // we need to set fBuffer to zero to avoid calling BufferEmpty in GetBinContent
+   Double_t * buffer = 0; 
+   if (fBuffer) { 
+      buffer = fBuffer; 
+      ((TH1*)this)->fBuffer = 0; 
+   }
    for (Int_t i=0;i<fNcells;i++) ((TH1&)obj).SetBinContent(i,this->GetBinContent(i));
+   // restore rebin bit and buffer pointer
    if (canRebin) ((TH1&)obj).SetBit(kCanRebin);
+   if (buffer) ((TH1*)this)->fBuffer  = buffer;
    ((TH1&)obj).fEntries   = fEntries;
 
-   // copy the Buffer (needs to do after calling Get/SetBinContent 
-   // which will call BufferEmpty. Maybe one should call 
+   // which will call BufferEmpty(0) and set fBuffer[0] to a  Maybe one should call 
    // assignment operator on the TArrayD
-   if (fBuffer) {
-      Double_t *buf = new Double_t[fBufferSize];
-      for (Int_t i=0;i<fBufferSize;i++) buf[i] = fBuffer[i];
-      ((TH1&)obj).fBuffer    = buf;
-   }
 
    ((TH1&)obj).fTsumw     = fTsumw;
    ((TH1&)obj).fTsumw2    = fTsumw2;
@@ -4681,7 +4695,8 @@ void TH1::LabelsDeflate(Option_t *ax)
       if (ibin > nbins) nbins = ibin; 
    }
    if (nbins < 1) nbins = 1;
-   TH1 *hold = (TH1*)IsA()->New();;
+   TH1 *hold = (TH1*)IsA()->New();
+   R__ASSERT(hold);
    hold->SetDirectory(0);
    Copy(*hold);
 
@@ -7574,7 +7589,7 @@ void TH1::SetBuffer(Int_t buffersize, Option_t * /*option*/)
    if (buffersize < 100) buffersize = 100;
    fBufferSize = 1 + buffersize*(fDimension+1);
    fBuffer = new Double_t[fBufferSize];
-   memset(fBuffer,0,8*fBufferSize);
+   memset(fBuffer,0,sizeof(Double_t)*fBufferSize);
 }
 
 //______________________________________________________________________________
@@ -8386,8 +8401,13 @@ TH1* TH1::TransformHisto(TVirtualFFT *fft, TH1* h_output,  Option_t *option)
 //   "MAG" - magnitude of the output
 //   "PH"  - phase of the output
 
+   if (!fft ||  !fft->GetN() ) {
+      ::Error("TransformHisto","Invalid FFT transform class");
+      return 0; 
+   }
+
    if (fft->GetNdim()>2){
-      printf("Only 1d and 2d\n");
+      ::Error("TransformHisto","Only 1d and 2D transform are supported");
       return 0;
    }
    Int_t binx,biny;
@@ -8438,7 +8458,7 @@ TH1* TH1::TransformHisto(TVirtualFFT *fft, TH1* h_output,  Option_t *option)
             }
          }
       } else {
-         printf("No complex numbers in the output");
+         ::Error("TransformHisto","No complex numbers in the output");
          return 0;
       }
    }
diff --git a/hist/hist/src/TH2.cxx b/hist/hist/src/TH2.cxx
index adc1066..83ccd04 100644
--- a/hist/hist/src/TH2.cxx
+++ b/hist/hist/src/TH2.cxx
@@ -1,4 +1,4 @@
-// @(#)root/hist:$Id: TH2.cxx 43740 2012-04-13 15:50:21Z moneta $
+// @(#)root/hist:$Id: TH2.cxx 44515 2012-06-04 14:16:56Z moneta $
 // Author: Rene Brun   26/12/94
 
 /*************************************************************************
@@ -254,6 +254,13 @@ void TH2::Copy(TObject &obj) const
 }
 
 //______________________________________________________________________________
+Int_t TH2::Fill(Double_t )
+{
+   // Invalid Fill method
+   Error("Fill", "Invalid signature - do nothing"); 
+   return -1;
+}
+//______________________________________________________________________________
 Int_t TH2::Fill(Double_t x,Double_t y)
 {
    //*-*-*-*-*-*-*-*-*-*-*Increment cell defined by x,y by 1*-*-*-*-*-*-*-*-*-*
diff --git a/hist/hist/src/TH3.cxx b/hist/hist/src/TH3.cxx
index 60fc5fb..6b3336d 100644
--- a/hist/hist/src/TH3.cxx
+++ b/hist/hist/src/TH3.cxx
@@ -1,4 +1,4 @@
-// @(#)root/hist:$Id: TH3.cxx 43738 2012-04-13 15:41:27Z moneta $
+// @(#)root/hist:$Id: TH3.cxx 44515 2012-06-04 14:16:56Z moneta $
 // Author: Rene Brun   27/10/95
 
 /*************************************************************************
@@ -252,6 +252,13 @@ Int_t TH3::BufferFill(Double_t x, Double_t y, Double_t z, Double_t w)
 }
 
 //______________________________________________________________________________
+Int_t TH3::Fill(Double_t )
+{
+   // Invalid Fill method
+   Error("Fill", "Invalid signature - do nothing"); 
+   return -1;
+}
+//______________________________________________________________________________
 Int_t TH3::Fill(Double_t x, Double_t y, Double_t z)
 {
    //*-*-*-*-*-*-*-*-*-*-*Increment cell defined by x,y,z by 1 *-*-*-*-*
diff --git a/hist/hist/src/THStack.cxx b/hist/hist/src/THStack.cxx
index 4752854..c0afc71 100644
--- a/hist/hist/src/THStack.cxx
+++ b/hist/hist/src/THStack.cxx
@@ -1,4 +1,4 @@
-// @(#)root/hist:$Id: THStack.cxx 41395 2011-10-14 12:25:08Z pcanal $
+// @(#)root/hist:$Id: THStack.cxx 44270 2012-05-16 12:58:34Z moneta $
 // Author: Rene Brun   10/12/2001
 
 /*************************************************************************
@@ -801,8 +801,10 @@ void THStack::Paint(Option_t *option)
             h1->Paint(loption);
             static TClassRef clTFrame = TClass::GetClass("TFrame",kFALSE);
             TAttFill *frameFill = (TAttFill*)clTFrame->DynamicCast(TAttFill::Class(),gPad->GetFrame());
-            h1->SetFillColor(frameFill->GetFillColor());
-            h1->SetFillStyle(frameFill->GetFillStyle());
+            if (frameFill) { 
+               h1->SetFillColor(frameFill->GetFillColor());
+               h1->SetFillStyle(frameFill->GetFillStyle());
+            }
             h1->Paint(loption);
             h1->SetFillColor(h1col);
             h1->SetFillStyle(h1fill);
diff --git a/hist/hist/src/TMultiDimFit.cxx b/hist/hist/src/TMultiDimFit.cxx
index 2e7b539..3cff8ef 100644
--- a/hist/hist/src/TMultiDimFit.cxx
+++ b/hist/hist/src/TMultiDimFit.cxx
@@ -1,4 +1,4 @@
-// @(#)root/hist:$Id: TMultiDimFit.cxx 35406 2010-09-19 17:07:22Z brun $
+// @(#)root/hist:$Id: TMultiDimFit.cxx 44216 2012-05-10 12:51:36Z moneta $
 // Author: Christian Holm Christensen 07/11/2000
 
 //____________________________________________________________________
@@ -2380,11 +2380,17 @@ void TMultiDimFit::Fit(Option_t *option)
       Warning("Fit", "test sample is very small");
 
    if (!opt.Contains("m")) {
+      Error("Fit", "invalid option");
       delete [] x;
       return;
    }
 
    fFitter = TVirtualFitter::Fitter(0,fNCoefficients);
+   if (!fFitter) { 
+      Error("Fit", "Vannot create Fitter");
+      delete [] x; 
+      return;
+   }
    fFitter->SetFCN(mdfHelper);
 
    const Int_t  maxArgs = 16;
diff --git a/hist/hist/src/TPolyMarker.cxx b/hist/hist/src/TPolyMarker.cxx
index e67efb4..3fbe7ff 100644
--- a/hist/hist/src/TPolyMarker.cxx
+++ b/hist/hist/src/TPolyMarker.cxx
@@ -1,4 +1,4 @@
-// @(#)root/hist:$Id: TPolyMarker.cxx 37757 2011-01-10 14:01:53Z couet $
+// @(#)root/hist:$Id: TPolyMarker.cxx 44270 2012-05-16 12:58:34Z moneta $
 // Author: Rene Brun   12/12/94
 
 /*************************************************************************
@@ -116,6 +116,9 @@ TPolyMarker& TPolyMarker::operator=(const TPolyMarker& pm)
       TAttMarker::operator=(pm);
       fN=pm.fN;
       fLastPoint=pm.fLastPoint;
+   // delete first previous existing fX and fY
+      if (fX) delete [] fX;
+      if (fY) delete [] fY;
       fX=pm.fX;
       fY=pm.fY;
       fOption=pm.fOption;
@@ -155,6 +158,9 @@ void TPolyMarker::Copy(TObject &obj) const
    TObject::Copy(obj);
    TAttMarker::Copy(((TPolyMarker&)obj));
    ((TPolyMarker&)obj).fN = fN;
+   // delete first previous existing fX and fY
+   if (((TPolyMarker&)obj).fX) delete [] (((TPolyMarker&)obj).fX);
+   if (((TPolyMarker&)obj).fY) delete [] (((TPolyMarker&)obj).fY);
    if (fN > 0) {
       ((TPolyMarker&)obj).fX = new Double_t [fN];
       ((TPolyMarker&)obj).fY = new Double_t [fN];
diff --git a/hist/hist/src/TPrincipal.cxx b/hist/hist/src/TPrincipal.cxx
index 0ce34e9..4066cb2 100644
--- a/hist/hist/src/TPrincipal.cxx
+++ b/hist/hist/src/TPrincipal.cxx
@@ -1,4 +1,4 @@
-// @(#)root/hist:$Id: TPrincipal.cxx 35247 2010-09-13 14:10:41Z brun $
+// @(#)root/hist:$Id: TPrincipal.cxx 44270 2012-05-16 12:58:34Z moneta $
 // Author: Christian Holm Christensen    1/8/2000
 
 /*************************************************************************
@@ -663,7 +663,7 @@ in the transformed space.
 <!--*/
 // -->End_Html
 
-// $Id: TPrincipal.cxx 35247 2010-09-13 14:10:41Z brun $
+// $Id: TPrincipal.cxx 44270 2012-05-16 12:58:34Z moneta $
 // $Date: 2006/05/24 14:55:26 $
 // $Author: brun $
 
@@ -1260,6 +1260,7 @@ void TPrincipal::MakeHistograms(const char *name, Option_t *opt)
 
       // update the original data histogram
       x  = (Double_t*)(GetRow(i));
+      R__ASSERT(x);
 
       if (makeP||makeD||makeS)
          // calculate the corresponding principal component
diff --git a/hist/hist/src/TProfile.cxx b/hist/hist/src/TProfile.cxx
index 5dfbee3..fa95895 100644
--- a/hist/hist/src/TProfile.cxx
+++ b/hist/hist/src/TProfile.cxx
@@ -1,4 +1,4 @@
-// @(#)root/hist:$Id: TProfile.cxx 43802 2012-04-17 15:20:48Z moneta $
+// @(#)root/hist:$Id: TProfile.cxx 44273 2012-05-16 13:04:57Z moneta $
 // Author: Rene Brun   29/09/95
 
 /*************************************************************************
@@ -1704,7 +1704,7 @@ void TProfile::SetBuffer(Int_t buffersize, Option_t *)
    if (buffersize < 100) buffersize = 100;
    fBufferSize = 1 + 3*buffersize;
    fBuffer = new Double_t[fBufferSize];
-   memset(fBuffer,0,8*fBufferSize);
+   memset(fBuffer,0,sizeof(Double_t)*fBufferSize);
 }
 
 //______________________________________________________________________________
diff --git a/hist/hist/src/TProfile2D.cxx b/hist/hist/src/TProfile2D.cxx
index b95be0a..afcbd01 100644
--- a/hist/hist/src/TProfile2D.cxx
+++ b/hist/hist/src/TProfile2D.cxx
@@ -1,4 +1,4 @@
-// @(#)root/hist:$Id: TProfile2D.cxx 43802 2012-04-17 15:20:48Z moneta $
+// @(#)root/hist:$Id: TProfile2D.cxx 44273 2012-05-16 13:04:57Z moneta $
 // Author: Rene Brun   16/04/2000
 
 /*************************************************************************
@@ -1766,7 +1766,7 @@ void TProfile2D::SetBuffer(Int_t buffersize, Option_t *)
    if (buffersize < 100) buffersize = 100;
    fBufferSize = 1 + 4*buffersize;
    fBuffer = new Double_t[fBufferSize];
-   memset(fBuffer,0,8*fBufferSize);
+   memset(fBuffer,0,sizeof(Double_t)*fBufferSize);
 }
 
 //______________________________________________________________________________
diff --git a/hist/hist/src/TProfile3D.cxx b/hist/hist/src/TProfile3D.cxx
index b6aceec..96df93f 100644
--- a/hist/hist/src/TProfile3D.cxx
+++ b/hist/hist/src/TProfile3D.cxx
@@ -1,4 +1,4 @@
-// @(#)root/hist:$Id: TProfile3D.cxx 43802 2012-04-17 15:20:48Z moneta $
+// @(#)root/hist:$Id: TProfile3D.cxx 44273 2012-05-16 13:04:57Z moneta $
 // Author: Rene Brun   17/05/2006
 
 /*************************************************************************
@@ -1279,7 +1279,7 @@ void TProfile3D::SetBuffer(Int_t buffersize, Option_t *)
    if (buffersize < 100) buffersize = 100;
    fBufferSize = 1 + 5*buffersize; 
    fBuffer = new Double_t[fBufferSize];
-   memset(fBuffer,0,8*fBufferSize);
+   memset(fBuffer,0,sizeof(Double_t)*fBufferSize);
 }
 
 //______________________________________________________________________________
diff --git a/hist/hist/src/TUnfoldSys.cxx b/hist/hist/src/TUnfoldSys.cxx
index 5730bd9..673940f 100644
--- a/hist/hist/src/TUnfoldSys.cxx
+++ b/hist/hist/src/TUnfoldSys.cxx
@@ -1,4 +1,4 @@
-// @(#)root/hist:$Id: TUnfoldSys.cxx 37440 2010-12-09 15:13:46Z moneta $
+// @(#)root/hist:$Id: TUnfoldSys.cxx 44270 2012-05-16 12:58:34Z moneta $
 // Author: Stefan Schmitt
 // DESY, 23/01/09
 
@@ -404,14 +404,15 @@ void TUnfoldSys::DoBackgroundSubtraction(void) {
          {
             TMapIter bgrErrCorrPtr(fBgrErrCorrIn);
             for(key=bgrErrCorrPtr.Next();key;key=bgrErrCorrPtr.Next()) {
-               const TMatrixD *bgrerrcorr=(const TMatrixD *)
 #if ROOT_VERSION_CODE >= ROOT_VERSION(5,20,00)
-                  ((const TPair *)*bgrErrCorrPtr)->Value()
+                  if (!*bgrErrCorrPtr) continue;
+               const TMatrixD *bgrerrcorr=(const TMatrixD *)
+                  ((const TPair *)*bgrErrCorrPtr)->Value();
 #else
+               const TMatrixD *bgrerrcorr=(const TMatrixD *)
                   fBgrErrCorrIn->GetValue(((const TObjString *)key)
-                                          ->GetString())
+                                          ->GetString());
 #endif
-                  ;
                for(Int_t yi=0;yi<ny;yi++) {
                   if(!usedBin[yi]) continue;
                   for(Int_t yj=0;yj<ny;yj++) {
@@ -676,6 +677,7 @@ void TUnfoldSys::PrepareSysError(void) {
    for(key=(const TObjString *)sysErrIn.Next();key;
        key=(const TObjString *)sysErrIn.Next()) {
 #if ROOT_VERSION_CODE >= ROOT_VERSION(5,20,00)
+      if (!*sysErrIn) continue;
       const TMatrixDSparse *dsys=
          (const TMatrixDSparse *)((const TPair *)*sysErrIn)->Value();
 #else
@@ -1111,14 +1113,16 @@ Double_t TUnfoldSys::GetChi2Sys(void) {
    const TObject *key;
    // correlated su=ystematic errors
    for(key=sysErrPtr.Next();key;key=sysErrPtr.Next()) {
-      const TMatrixDSparse *delta=(TMatrixDSparse *)
 #if ROOT_VERSION_CODE >= ROOT_VERSION(5,20,00)
-                 ((const TPair *)*sysErrPtr)->Value()
+      if (!*sysErrPtr) continue;
+      const TMatrixDSparse *delta=(TMatrixDSparse *)
+         ((const TPair *)*sysErrPtr)->Value();
 #else
+      const TMatrixDSparse *delta=(TMatrixDSparse *)
          fDeltaCorrAx->GetValue(((const TObjString *)key)
-                                ->GetString())
+                                ->GetString());
 #endif
-         ;
+
       TMatrixDSparse *emat=MultiplyMSparseMSparseTranspVector(delta,delta,0);
       AddMSparse(&emat_sum,1.0,emat);
       DeleteMatrix(&emat);
diff --git a/hist/histpainter/src/THistPainter.cxx b/hist/histpainter/src/THistPainter.cxx
index 5ba2ee1..ddf57e1 100644
--- a/hist/histpainter/src/THistPainter.cxx
+++ b/hist/histpainter/src/THistPainter.cxx
@@ -1,4 +1,4 @@
-// @(#)root/histpainter:$Id: THistPainter.cxx 43774 2012-04-17 11:40:18Z couet $
+// @(#)root/histpainter:$Id: THistPainter.cxx 44519 2012-06-04 14:56:30Z moneta $
 // Author: Rene Brun   26/08/99
 
 /*************************************************************************
@@ -9097,7 +9097,8 @@ void THistPainter::ShowProjectionX(Int_t /*px*/, Int_t py)
    c->SetLogx(padsav->GetLogx());
 
    // Draw slice corresponding to mouse position
-   TH1D *hp = ((TH2*)fH)->ProjectionX("slice_px", biny1, biny2);
+   TString prjName = TString::Format("slice_px_of_%s",fH->GetName());
+   TH1D *hp = ((TH2*)fH)->ProjectionX(prjName, biny1, biny2);
    if (hp) {
       hp->SetFillColor(38);
       if (biny1 == biny2) hp->SetTitle(Form("ProjectionX of biny=%d", biny1));
@@ -9158,7 +9159,8 @@ void THistPainter::ShowProjectionY(Int_t px, Int_t /*py*/)
    c->SetLogx(padsav->GetLogy());
 
    // Draw slice corresponding to mouse position
-   TH1D *hp = ((TH2*)fH)->ProjectionY("slice_py", binx1, binx2);
+   TString prjName = TString::Format("slice_py_of_%s",fH->GetName());
+   TH1D *hp = ((TH2*)fH)->ProjectionY(prjName, binx1, binx2);
    if (hp) {
       hp->SetFillColor(38);
       if (binx1 == binx2) hp->SetTitle(Form("ProjectionY of binx=%d", binx1));
diff --git a/html/src/TDocOutput.cxx b/html/src/TDocOutput.cxx
index eff65a2..b4b37a5 100644
--- a/html/src/TDocOutput.cxx
+++ b/html/src/TDocOutput.cxx
@@ -1,4 +1,4 @@
-// @(#)root/html:$Id: TDocOutput.cxx 44070 2012-05-02 14:46:38Z axel $
+// @(#)root/html:$Id: TDocOutput.cxx 44323 2012-05-29 08:08:32Z axel $
 // Author: Axel Naumann 2007-01-09
 
 /*************************************************************************
@@ -1516,21 +1516,33 @@ Bool_t TDocOutput::IsModified(TClass * classPtr, EFileType type)
 
    switch (type) {
    case kSource:
-      if (classPtr->GetImplFileLine()) {
-         fHtml->GetImplFileName(classPtr, kTRUE, sourceFile);
-      } else {
-         fHtml->GetDeclFileName(classPtr, kTRUE, sourceFile);
+      {
+         TString declFile;
+         if (classPtr->GetImplFileLine()) {
+            fHtml->GetImplFileName(classPtr, kTRUE, sourceFile);
+         }
+         fHtml->GetDeclFileName(classPtr, kTRUE, declFile);
+         Long64_t size;
+         Long_t id, flags, iModtime, dModtime;
+         if (!(gSystem->GetPathInfo(sourceFile, &id, &size, &flags, &iModtime))) {
+            if (!(gSystem->GetPathInfo(declFile, &id, &size, &flags, &dModtime))) {
+               if (iModtime < dModtime) {
+                  // decl is newer than impl
+                  sourceFile = declFile;
+               }
+            }
+         }
+         dir = "src";
+         gSystem->PrependPathName(fHtml->GetOutputDir(), dir);
+         filename = classname;
+         NameSpace2FileName(filename);
+         gSystem->PrependPathName(dir, filename);
+         if (classPtr->GetImplFileLine())
+            filename += ".cxx.html";
+         else
+            filename += ".h.html";
+         break;
       }
-      dir = "src";
-      gSystem->PrependPathName(fHtml->GetOutputDir(), dir);
-      filename = classname;
-      NameSpace2FileName(filename);
-      gSystem->PrependPathName(dir, filename);
-      if (classPtr->GetImplFileLine())
-         filename += ".cxx.html";
-      else
-         filename += ".h.html";
-      break;
 
    case kInclude:
       fHtml->GetDeclFileName(classPtr, kFALSE, filename);
@@ -1548,16 +1560,28 @@ Bool_t TDocOutput::IsModified(TClass * classPtr, EFileType type)
       break;
 
    case kDoc:
-      if (classPtr->GetImplFileLine()) {
-         fHtml->GetImplFileName(classPtr, kTRUE, sourceFile);
-      } else {
-         fHtml->GetDeclFileName(classPtr, kTRUE, sourceFile);
+      {
+         TString declFile;
+         if (classPtr->GetImplFileLine()) {
+            fHtml->GetImplFileName(classPtr, kTRUE, sourceFile);
+         }
+         fHtml->GetDeclFileName(classPtr, kTRUE, declFile);
+         Long64_t size;
+         Long_t id, flags, iModtime, dModtime;
+         if (!(gSystem->GetPathInfo(sourceFile, &id, &size, &flags, &iModtime))) {
+            if (!(gSystem->GetPathInfo(declFile, &id, &size, &flags, &dModtime))) {
+               if (iModtime < dModtime) {
+                  // decl is newer than impl
+                  sourceFile = declFile;
+               }
+            }
+         }
+         filename = classname;
+         NameSpace2FileName(filename);
+         gSystem->PrependPathName(fHtml->GetOutputDir(), filename);
+         filename += ".html";
+         break;
       }
-      filename = classname;
-      NameSpace2FileName(filename);
-      gSystem->PrependPathName(fHtml->GetOutputDir(), filename);
-      filename += ".html";
-      break;
 
    default:
       Error("IsModified", "Unknown file type !");
@@ -1569,9 +1593,11 @@ Bool_t TDocOutput::IsModified(TClass * classPtr, EFileType type)
    Long64_t size;
    Long_t id, flags, sModtime, dModtime;
 
-   if (!(gSystem->GetPathInfo(sourceFile, &id, &size, &flags, &sModtime)))
-      if (!(gSystem->GetPathInfo(filename, &id, &size, &flags, &dModtime)))
+   if (!(gSystem->GetPathInfo(sourceFile, &id, &size, &flags, &sModtime))) {
+      if (!(gSystem->GetPathInfo(filename, &id, &size, &flags, &dModtime))) {
          return (sModtime > dModtime);
+      }
+   }
 
    return kTRUE;
 }
diff --git a/io/doc/v534/index.html b/io/doc/v534/index.html
index 7156812..052ecc7 100644
--- a/io/doc/v534/index.html
+++ b/io/doc/v534/index.html
@@ -8,7 +8,18 @@
 <li>Support for multiple <tt>TFileCacheRead</tt> per <tt>TFile</tt>.<p/>
 Multiple <tt>TFileCacheRead</tt> per <tt>TFile</tt> are supported by augmenting the existing <tt>TFile::SetCacheRead()</tt> function with an optional <tt>TObject*</tt> argument specifying the owner (i.e. tree) of the cache. This function will assign a <tt>TFileCacheRead</tt> to a <tt>TFile</tt> for the given <tt>TTree</tt>. A cache can be removed by setting the pointer <tt>TFileCacheRead</tt> to 0.<p/>
 Similarly, in <tt>TFile::GetCacheRead()</tt> an optional <tt>TObject*</tt> argument was added to obtain the <tt>TFileCacheRead</tt> from a <tt>TFile</tt>.<p/>
-In addition to the unassigned <tt>TFileCacheRead</tt> pointer, <tt>TFile</tt> will maintain a map of tree specific cache pointer.<p/>
-Backward compatibility in both functions is handled by making the <tt>TObject*</tt> argument optional. If it is not specified in the <tt>TFile::SetCacheRead()</tt> call, only the unassigned <tt>TFileCacheRead</tt> pointer is updated, otherwise the map and the unassigned cache are updated. In  <tt>TFile::GetCacheRead()</tt>, if an owner is not specified or doesn't exist in the files' cache map, the unassigned cache is returned, unless it is 0 and there is exactly one entry in the cache map.<p/>
+In addition to the unassigned <tt>TFileCacheRead</tt> pointer, <tt>TFile</tt> will maintain a map of tree specific cache pointers.<p/>
+Backward compatibility in both functions is handled by making the <tt>TObject*</tt> argument optional. If it is not specified in the <tt>TFile::SetCacheRead()</tt> call, only the unassigned <tt>TFileCacheRead</tt> pointer is updated, otherwise the map and the unassigned cache are updated. In <tt>TFile::GetCacheRead()</tt>, if an owner is not specified or doesn't exist in the file's cache map, the unassigned cache is returned, unless it is 0 and there is exactly one entry in the cache map.<p/>
+Distinguish counter for bytes read and read calls for learning phase.
 </li>
-</ul>
\ No newline at end of file
+</ul>
+
+<h4>TFileMerger</h4>
+
+<ul>
+<li>Improve efficiency of <tt>TFileMerger</tt> when merging a single file by doing a <tt>TFile::Cp</tt> rather than a load/write of the objects.</li>
+<li>In <tt>TFileMerger</tt> and hadd when objects can not be merged do <em>not</em> overwrite the last object in the set with the first!</li>
+<li>Renable warning about not being able to merge objects in <tt>TFileMerger</tt> and hadd.</li>
+<li>Fix <tt>hadd</tt> problem where the incremental merging fails if the <tt>TTree</tt> are stored in sub-directories.</li>
+<li>Improve the code used for forward compatibility (record the type as <tt>TDirectory</tt> even-though the class is now <tt>TDirectoryFile</tt>) by delaying the switching of the class name until it is written (to the buffer).  This avoids problem where a <tt>TKey</tt> is created (by <tt>TFile::mkdir</tt>) and then immediately used for reading (this happens in the incremental file merger).</li>
+</ul>
diff --git a/io/io/src/TFileMerger.cxx b/io/io/src/TFileMerger.cxx
index 53b6fea..7ce39a6 100644
--- a/io/io/src/TFileMerger.cxx
+++ b/io/io/src/TFileMerger.cxx
@@ -1,4 +1,4 @@
-// @(#)root/io:$Id: TFileMerger.cxx 44177 2012-05-08 15:18:42Z rdm $
+// @(#)root/io:$Id: TFileMerger.cxx 44534 2012-06-04 16:52:20Z pcanal $
 // Author: Andreas Peters + Fons Rademakers + Rene Brun  26/5/2005
 
 /*************************************************************************
@@ -148,21 +148,19 @@ Bool_t TFileMerger::AddFile(const char *url, Bool_t cpProgress)
    }
    
    // We want gDirectory untouched by anything going on here
-   TDirectory *dirsave = gDirectory;
+   TDirectory::TContext ctx(0);
    
    if (fLocal) {
       TUUID uuid;
       localcopy.Form("file:%s/ROOTMERGE-%s.root", gSystem->TempDirectory(), uuid.AsString());
       if (!TFile::Cp(url, localcopy, cpProgress)) {
          Error("AddFile", "cannot get a local copy of file %s", url);
-         gDirectory = dirsave;
          return kFALSE;
       }
       newfile = TFile::Open(localcopy, "READ");
    } else {
       newfile = TFile::Open(url, "READ");
    }
-   gDirectory = dirsave;
    
    if (!newfile) {
       if (fLocal)
@@ -226,20 +224,18 @@ Bool_t TFileMerger::AddFile(TFile *source, Bool_t own, Bool_t cpProgress)
    TString localcopy;
    
    // We want gDirectory untouched by anything going on here
-   TDirectory *dirsave = gDirectory;
+   TDirectory::TContext ctx(0);
    if (fLocal && !source->InheritsFrom(TMemFile::Class())) {
       TUUID uuid;
       localcopy.Form("file:%s/ROOTMERGE-%s.root", gSystem->TempDirectory(), uuid.AsString());
       if (!source->Cp(localcopy, cpProgress)) {
          Error("AddFile", "cannot get a local copy of file %s", source->GetName());
-         gDirectory = dirsave;
          return kFALSE;
       }
       newfile = TFile::Open(localcopy, "READ");
    } else {
       newfile = source;
    }
-   gDirectory = dirsave;
    
    if (!newfile) {
       if (fLocal)
@@ -305,13 +301,11 @@ Bool_t TFileMerger::OutputFile(const char *outputfile, const char *mode, Int_t c
    fOutputFilename = outputfile;
    
    // We want gDirectory untouched by anything going on here
-   TDirectory *dirsave = gDirectory;
+   TDirectory::TContext ctx(0);
    if (!(fOutputFile = TFile::Open(outputfile, mode, "", compressionLevel)) || fOutputFile->IsZombie()) {
       Error("OutputFile", "cannot open the MERGER output file %s", fOutputFilename.Data());
-      gDirectory = dirsave;
       return kFALSE;
    }
-   gDirectory = dirsave;
    return kTRUE;
 }
 
@@ -766,7 +760,7 @@ Bool_t TFileMerger::PartialMerge(Int_t in_type)
       TString outf(fOutputFilename);
       if (outf.IsNull()) {
          outf.Form("file:%s/FileMerger.root", gSystem->TempDirectory());
-         Info("Merge", "will merge the results to the file %s\n"
+         Info("PartialMerge", "will merge the results to the file %s\n"
               "since you didn't specify a merge filename",
               TUrl(outf).GetFile());
       }
@@ -774,7 +768,36 @@ Bool_t TFileMerger::PartialMerge(Int_t in_type)
          return kFALSE;
       }
    }
-   
+
+   // Special treament for the single file case ...
+   if ((fFileList->GetEntries() == 1) && !fExcessFiles->GetEntries() &&
+      !(in_type & kIncremental) && !fCompressionChange && !fExplicitCompLevel) {
+      fOutputFile->Close();
+      SafeDelete(fOutputFile);
+
+      TFile *file = (TFile *) fFileList->First();
+      if (!file || (file && file->IsZombie())) {
+         Error("PartialMerge", "one-file case: problem attaching to file");
+         return kFALSE;
+      }
+      Bool_t result = kTRUE;
+      if (!(result = file->Cp(fOutputFilename))) {
+         Error("PartialMerge", "one-file case: could not copy '%s' to '%s'",
+                               file->GetPath(), fOutputFilename.Data());
+         return kFALSE;
+      }
+      if (file->TestBit(kCanDelete)) file->Close();
+
+      // Remove the temporary file
+      if (fLocal) {
+         TUrl u(file->GetPath(), kTRUE); 
+         if (gSystem->Unlink(u.GetFile()) != 0)
+            Warning("PartialMerge", "problems removing temporary local file '%s'", u.GetFile());
+      }
+      fFileList->Clear();
+      return result;
+   }
+
    fOutputFile->SetBit(kMustCleanup);
 
    TDirectory::TContext ctxt(0);
@@ -842,7 +865,7 @@ Bool_t TFileMerger::OpenExcessFiles()
    TObjString *url = 0;
    TString localcopy;
    // We want gDirectory untouched by anything going on here
-   TDirectory *dirsave = gDirectory;
+   TDirectory::TContext ctx(0);
    while( nfiles < (fMaxOpenedFiles-1) && ( url = (TObjString*)next() ) ) {
       TFile *newfile = 0;
       if (fLocal) {
@@ -850,7 +873,6 @@ Bool_t TFileMerger::OpenExcessFiles()
          localcopy.Form("file:%s/ROOTMERGE-%s.root", gSystem->TempDirectory(), uuid.AsString());
          if (!TFile::Cp(url->GetName(), localcopy, url->TestBit(kCpProgress))) {
             Error("OpenExcessFiles", "cannot get a local copy of file %s", url->GetName());
-            gDirectory = dirsave;
             return kFALSE;
          }
          newfile = TFile::Open(localcopy, "READ");
@@ -864,7 +886,6 @@ Bool_t TFileMerger::OpenExcessFiles()
                   localcopy.Data(), url->GetName());
          else
             Error("OpenExcessFiles", "cannot open file %s", url->GetName());
-            gDirectory = dirsave;
          return kFALSE;
       } else {
          if (fOutputFile && fOutputFile->GetCompressionLevel() != newfile->GetCompressionLevel()) fCompressionChange = kTRUE;
@@ -875,7 +896,6 @@ Bool_t TFileMerger::OpenExcessFiles()
          fExcessFiles->Remove(url);
       }
    }
-   gDirectory = dirsave;
    return kTRUE;
 }
 
diff --git a/main/src/hadd.cxx b/main/src/hadd.cxx
index a6b8862..46dfc86 100644
--- a/main/src/hadd.cxx
+++ b/main/src/hadd.cxx
@@ -203,8 +203,7 @@ int main( int argc, char **argv )
          }
          while( indirect_file ){
             std::string line;
-            std::getline(indirect_file, line);
-            if( !merger.AddFile(line.c_str()) ) {
+            if( std::getline(indirect_file, line) && line.length() &&  !merger.AddFile(line.c_str()) ) {
                return 1;
             }
          }         
diff --git a/math/mathcore/CMakeLists.txt b/math/mathcore/CMakeLists.txt
index 61e9e08..815f6b3 100644
--- a/math/mathcore/CMakeLists.txt
+++ b/math/mathcore/CMakeLists.txt
@@ -6,7 +6,7 @@ ROOT_USE_PACKAGE(core)
 include_directories(${CMAKE_SOURCE_DIR}/hist/hist/inc)  # Explicit to avoid circular dependencies mathcore <--> hist :-(
 
 set(MATHCORE_HEADERS TRandom.h 
-  TRandom1.h TRandom2.h TRandom3.h TVirtualFitter.h TKDTree.h TKDTreeBinning.h 
+  TRandom1.h TRandom2.h TRandom3.h TVirtualFitter.h TKDTree.h TKDTreeBinning.h TStatistic.h 
   Math/IParamFunction.h Math/IFunction.h Math/ParamFunctor.h Math/Functor.h 
   Math/Minimizer.h Math/MinimizerOptions.h Math/IntegratorOptions.h Math/IOptions.h 
   Math/Integrator.h Math/VirtualIntegrator.h Math/AllIntegrationTypes.h Math/AdaptiveIntegratorMultiDim.h 
@@ -18,7 +18,7 @@ set(MATHCORE_HEADERS TRandom.h
 )
 
 
-ROOT_GENERATE_DICTIONARY(G__Math     TComplex.h TMath.h LINKDEF LinkDef1.h)
+ROOT_GENERATE_DICTIONARY(G__Math     TComplex.h TMath.h  LINKDEF LinkDef1.h)
 ROOT_GENERATE_DICTIONARY(G__MathCore ${MATHCORE_HEADERS} LINKDEF LinkDef2.h)
 ROOT_GENERATE_DICTIONARY(G__MathFit  Fit/*.h LINKDEF LinkDef3.h)
 
diff --git a/math/mathcore/Module.mk b/math/mathcore/Module.mk
index 740fb78..95738d7 100644
--- a/math/mathcore/Module.mk
+++ b/math/mathcore/Module.mk
@@ -30,12 +30,12 @@ MATHCOREDO   := $(MATHCOREDO1) $(MATHCOREDO2) $(MATHCOREDO3)
 MATHCOREDH   := $(MATHCOREDS:.cxx=.h)
 
 MATHCOREDH1  := $(MODDIRI)/TComplex.h \
-                $(MODDIRI)/TStatistic.h \
                 $(MODDIRI)/TMath.h 
 MATHCOREDH2  := $(MODDIRI)/TRandom.h \
                 $(MODDIRI)/TRandom1.h \
                 $(MODDIRI)/TRandom2.h \
 		$(MODDIRI)/TRandom3.h \
+                $(MODDIRI)/TStatistic.h \
                 $(MODDIRI)/TVirtualFitter.h \
                 $(MODDIRI)/TKDTree.h \
                 $(MODDIRI)/TKDTreeBinning.h \
diff --git a/math/mathcore/inc/LinkDef1.h b/math/mathcore/inc/LinkDef1.h
index 9c2e5b0..11da89e 100644
--- a/math/mathcore/inc/LinkDef1.h
+++ b/math/mathcore/inc/LinkDef1.h
@@ -1,4 +1,4 @@
-/* @(#)root/mathcore:$Id: LinkDef1.h 44158 2012-05-07 16:54:16Z moneta $ */
+/* @(#)root/mathcore:$Id: LinkDef1.h 44187 2012-05-09 09:48:09Z moneta $ */
 
 /*************************************************************************
  * Copyright (C) 1995-2007, Rene Brun and Fons Rademakers.               *
@@ -22,7 +22,6 @@
 #pragma link C++ global ROOT_TMath;
 
 #pragma link C++ class TComplex+;
-#pragma link C++ class TStatistic+;
 
 #pragma link C++ function operator*(Double_t, const TComplex&);
 #pragma link C++ function operator+(Double_t, const TComplex&);
diff --git a/math/mathcore/inc/LinkDef2.h b/math/mathcore/inc/LinkDef2.h
index c670372..11ec8bc 100644
--- a/math/mathcore/inc/LinkDef2.h
+++ b/math/mathcore/inc/LinkDef2.h
@@ -1,4 +1,4 @@
-// @(#)root/mathcore:$Id: LinkDef2.h 41529 2011-10-21 10:10:33Z moneta $
+// @(#)root/mathcore:$Id: LinkDef2.h 44187 2012-05-09 09:48:09Z moneta $
 
 /*************************************************************************
  * Copyright (C) 1995-2007, Rene Brun and Fons Rademakers.               *
@@ -44,6 +44,8 @@
 #pragma link C++ class TRandom2+;
 #pragma link C++ class TRandom3-;
 
+#pragma link C++ class TStatistic+;
+
 #pragma link C++ class TVirtualFitter+;
 
 #pragma link C++ class TKDTree<Int_t, Double_t>+;
diff --git a/math/mathcore/inc/TStatistic.h b/math/mathcore/inc/TStatistic.h
index 4625363..e9dc673 100644
--- a/math/mathcore/inc/TStatistic.h
+++ b/math/mathcore/inc/TStatistic.h
@@ -1,4 +1,4 @@
-// @(#)root/base:$Id: TStatistic.h 44158 2012-05-07 16:54:16Z moneta $
+// @(#)root/mathcore:$Id: TStatistic.h 44344 2012-05-29 15:33:12Z axel $
 // Author: G. Ganis 2012
 
 /*************************************************************************
@@ -22,14 +22,6 @@
 //                                                                      //
 //////////////////////////////////////////////////////////////////////////
 
-#ifndef ROOT_Riostream
-#include "Riostream.h"
-#endif
-
-#ifndef ROOT_TClass
-#include "TClass.h"
-#endif
-
 #ifndef ROOT_TObject
 #include "TObject.h"
 #endif
diff --git a/math/mathcore/src/RichardsonDerivator.cxx b/math/mathcore/src/RichardsonDerivator.cxx
index aa50701..668ed20 100644
--- a/math/mathcore/src/RichardsonDerivator.cxx
+++ b/math/mathcore/src/RichardsonDerivator.cxx
@@ -1,4 +1,4 @@
-// @(#)root/mathcore:$Id: RichardsonDerivator.cxx 44142 2012-05-06 20:44:03Z moneta $
+// @(#)root/mathcore:$Id: RichardsonDerivator.cxx 44464 2012-06-01 15:01:51Z moneta $
 // Authors: David Gonzalez Maline    01/2008 
 
 /**********************************************************************
@@ -49,7 +49,11 @@ RichardsonDerivator::~RichardsonDerivator()
 RichardsonDerivator::RichardsonDerivator(const RichardsonDerivator & rhs) 
 {
     // copy constructor
-    *this = rhs;
+    // copy constructor (deep copy or not depending on fFunctionCopied)
+   fStepSize = rhs.fStepSize;
+   fLastError = rhs.fLastError;
+   fFunctionCopied = rhs.fFunctionCopied; 
+   SetFunction(*rhs.fFunction);   
  }
 
 RichardsonDerivator &  RichardsonDerivator::operator= ( const RichardsonDerivator & rhs) 
diff --git a/math/mathcore/src/TMath.cxx b/math/mathcore/src/TMath.cxx
index 86c30d5..8ecb413 100644
--- a/math/mathcore/src/TMath.cxx
+++ b/math/mathcore/src/TMath.cxx
@@ -1,4 +1,4 @@
-// @(#)root/mathcore:$Id: TMath.cxx 41830 2011-11-09 10:07:39Z moneta $
+// @(#)root/mathcore:$Id: TMath.cxx 44435 2012-06-01 08:18:35Z moneta $
 // Authors: Rene Brun, Anna Kreshuk, Eddy Offermann, Fons Rademakers   29/07/95
 
 /*************************************************************************
@@ -2092,8 +2092,8 @@ Double_t TMath::Binomial(Int_t n,Int_t k)
 {
    // Calculate the binomial coefficient n over k.
 
+   if (n<0 || k<0 || n<k) return TMath::SignalingNaN();
    if (k==0 || n==k) return 1;
-   if (n<=0 || k<0 || n<k) return 0;
 
    Int_t k1=TMath::Min(k,n-k);
    Int_t k2=n-k1;
diff --git a/math/mathmore/src/cblas.cxx b/math/mathmore/src/cblas.cxx
new file mode 100644
index 0000000..caf40e4
--- /dev/null
+++ b/math/mathmore/src/cblas.cxx
@@ -0,0 +1,21 @@
+// import just a cblas symbol in mathmore
+#include "gsl/gsl_cblas.h"
+
+namespace ROOT { 
+
+   namespace Math { 
+
+      namespace Blas { 
+
+         // multiplication C = A * B where (n,m) is the size of C, A is size (n,k) and B is size (k,m)
+         void  AMultB(int n, int m, int k, const double * A, const double * B, double *C) { 
+            cblas_dgemm(CblasRowMajor, CblasNoTrans, CblasNoTrans, n, m, k, 1.0, A, k, B, m, 0.0, C, m);
+         }
+         // multiplication C = AT * B where (n,m) is the size of C, A is size (k,n) and B is size (k,m)
+         void  ATMultB(int n, int m, int k, const double * A, const double * B, double *C) { 
+            cblas_dgemm(CblasRowMajor, CblasTrans, CblasNoTrans, n, m, k, 1.0, A, n, B, m, 0.0, C, m);
+         }
+
+      }
+   }
+}
diff --git a/math/matrix/inc/TMatrixTUtils.h b/math/matrix/inc/TMatrixTUtils.h
index f29acca..9c7d6f3 100644
--- a/math/matrix/inc/TMatrixTUtils.h
+++ b/math/matrix/inc/TMatrixTUtils.h
@@ -1,4 +1,4 @@
-// @(#)root/matrix:$Id: TMatrixTUtils.h 36047 2010-10-04 06:43:15Z brun $
+// @(#)root/matrix:$Id: TMatrixTUtils.h 44467 2012-06-01 15:04:37Z moneta $
 // Authors: Fons Rademakers, Eddy Offermann   Nov 2003
 
 /*************************************************************************
@@ -574,7 +574,7 @@ public:
 template<class Element> class TMatrixTSparseRow_const {
 
 protected:
-   const TMatrixTBase<Element> *fMatrix;  // the matrix I am a row of
+   const TMatrixTSparse<Element> *fMatrix;  // the matrix I am a row of
          Int_t                  fRowInd;  // effective row index
          Int_t                  fNindex;  // index range
    const Int_t                 *fColPtr;  // column index pointer
@@ -640,7 +640,7 @@ public:
 template<class Element> class TMatrixTSparseDiag_const {
 
 protected:
-   const TMatrixTBase<Element> *fMatrix;  //  the matrix I am the diagonal of
+   const TMatrixTSparse<Element> *fMatrix;  //  the matrix I am the diagonal of
          Int_t                  fNdiag;   //  number of diag elems, min(nrows,ncols)
    const Element               *fDataPtr; //  data pointer
 
diff --git a/math/matrix/src/TMatrixTUtils.cxx b/math/matrix/src/TMatrixTUtils.cxx
index 6f2ed0c..c1baf27 100644
--- a/math/matrix/src/TMatrixTUtils.cxx
+++ b/math/matrix/src/TMatrixTUtils.cxx
@@ -1,4 +1,4 @@
-// @(#)root/matrix:$Id: TMatrixTUtils.cxx 34913 2010-08-20 19:18:35Z pcanal $
+// @(#)root/matrix:$Id: TMatrixTUtils.cxx 44467 2012-06-01 15:04:37Z moneta $
 // Authors: Fons Rademakers, Eddy Offermann  Nov 2003
 
 /*************************************************************************
@@ -1417,7 +1417,7 @@ Element &TMatrixTSparseRow<Element>::operator()(Int_t i)
    if (index >= 0 && this->fColPtr[index] == acoln)
       return (const_cast<Element*>(this->fDataPtr))[index];
    else {
-      TMatrixTBase<Element> *mt = const_cast<TMatrixTBase<Element> *>(this->fMatrix);
+      TMatrixTSparse<Element> *mt = const_cast<TMatrixTSparse<Element> *>(this->fMatrix);
       const Int_t row = this->fRowInd+mt->GetRowLwb();
       Element val = 0.;
       mt->InsertRow(row,i,&val,1);
@@ -1495,7 +1495,7 @@ void TMatrixTSparseRow<Element>::operator=(const TMatrixTSparseRow_const<Element
 
    TVectorT<Element> v(ncols);
    mt->ExtractRow(row2,col,v.GetMatrixArray());
-   const_cast<TMatrixTBase<Element> *>(this->fMatrix)->InsertRow(row1,col,v.GetMatrixArray());
+   const_cast<TMatrixTSparse<Element> *>(this->fMatrix)->InsertRow(row1,col,v.GetMatrixArray());
 
    const Int_t sIndex = this->fMatrix->GetRowIndexArray()[this->fRowInd];
    const Int_t eIndex = this->fMatrix->GetRowIndexArray()[this->fRowInd+1];
@@ -1522,7 +1522,7 @@ void TMatrixTSparseRow<Element>::operator=(const TVectorT<Element> &vec)
    const Element *vp = vec.GetMatrixArray();
    const Int_t row = this->fRowInd+this->fMatrix->GetRowLwb();
    const Int_t col = this->fMatrix->GetColLwb();
-   const_cast<TMatrixTBase<Element> *>(this->fMatrix)->InsertRow(row,col,vp,vec.GetNrows());
+   const_cast<TMatrixTSparse<Element> *>(this->fMatrix)->InsertRow(row,col,vp,vec.GetNrows());
 
    const Int_t sIndex = this->fMatrix->GetRowIndexArray()[this->fRowInd];
    const Int_t eIndex = this->fMatrix->GetRowIndexArray()[this->fRowInd+1];
@@ -1556,7 +1556,7 @@ void TMatrixTSparseRow<Element>::operator+=(const TMatrixTSparseRow_const<Elemen
    this->fMatrix->ExtractRow(row1,col,v1.GetMatrixArray());
    mt           ->ExtractRow(row2,col,v2.GetMatrixArray());
    v1 += v2;
-   const_cast<TMatrixTBase<Element> *>(this->fMatrix)->InsertRow(row1,col,v1.GetMatrixArray());
+   const_cast<TMatrixTSparse<Element> *>(this->fMatrix)->InsertRow(row1,col,v1.GetMatrixArray());
 
    const Int_t sIndex = this->fMatrix->GetRowIndexArray()[this->fRowInd];
    const Int_t eIndex = this->fMatrix->GetRowIndexArray()[this->fRowInd+1];
@@ -1592,7 +1592,7 @@ void TMatrixTSparseRow<Element>::operator*=(const TMatrixTSparseRow_const<Elemen
    mt           ->ExtractRow(row2,col,v2.GetMatrixArray());
 
    ElementMult(v1,v2);
-   const_cast<TMatrixTBase<Element> *>(this->fMatrix)->InsertRow(row1,col,v1.GetMatrixArray());
+   const_cast<TMatrixTSparse<Element> *>(this->fMatrix)->InsertRow(row1,col,v1.GetMatrixArray());
 
    const Int_t sIndex = this->fMatrix->GetRowIndexArray()[this->fRowInd];
    const Int_t eIndex = this->fMatrix->GetRowIndexArray()[this->fRowInd+1];
@@ -1687,7 +1687,7 @@ Element &TMatrixTSparseDiag<Element>::operator()(Int_t i)
       return (const_cast<Element*>(this->fDataPtr))[0];
    }
 
-   TMatrixTBase<Element> *mt = const_cast<TMatrixTBase<Element> *>(this->fMatrix);
+   TMatrixTSparse<Element> *mt = const_cast<TMatrixTSparse<Element> *>(this->fMatrix);
    const Int_t *pR = mt->GetRowIndexArray();
    const Int_t *pC = mt->GetColIndexArray();
    Int_t sIndex = pR[i];
diff --git a/math/minuit2/inc/Minuit2/StackAllocator.h b/math/minuit2/inc/Minuit2/StackAllocator.h
index 9c625a7..57de0bf 100644
--- a/math/minuit2/inc/Minuit2/StackAllocator.h
+++ b/math/minuit2/inc/Minuit2/StackAllocator.h
@@ -1,4 +1,4 @@
-// @(#)root/minuit2:$Id: StackAllocator.h 34992 2010-08-25 10:36:11Z moneta $
+// @(#)root/minuit2:$Id: StackAllocator.h 44476 2012-06-01 16:36:12Z moneta $
 // Authors: M. Winkler, F. James, L. Moneta, A. Zsenei   2003-2005  
 
 /**********************************************************************
@@ -26,6 +26,7 @@
 
 
 #include <cstdlib>
+#include <new>
 
 namespace ROOT {
 
@@ -94,6 +95,7 @@ public:
       
 #else
       void* result = malloc(nBytes);
+      if (!result) throw std::bad_alloc();
 #endif
 
       return result;
diff --git a/math/minuit2/src/Minuit2Minimizer.cxx b/math/minuit2/src/Minuit2Minimizer.cxx
index d4aedf3..11e767e 100644
--- a/math/minuit2/src/Minuit2Minimizer.cxx
+++ b/math/minuit2/src/Minuit2Minimizer.cxx
@@ -13,6 +13,7 @@
 #include "Minuit2/Minuit2Minimizer.h"
 
 #include "Math/IFunction.h"
+#include "Math/IOptions.h"
 
 #include "Minuit2/FCNAdapter.h"
 #include "Minuit2/FumiliFCNAdapter.h"
@@ -316,7 +317,7 @@ bool Minuit2Minimizer::Minimize() {
 
    int maxfcn = MaxFunctionCalls(); 
    double tol = Tolerance();
-   int strategy = Strategy(); 
+   int strategyLevel = Strategy(); 
    fMinuitFCN->SetErrorDef(ErrorDef() );
 
    if (PrintLevel() >=1) { 
@@ -328,7 +329,7 @@ bool Minuit2Minimizer::Minimize() {
       }      
       std::cout << "Minuit2Minimizer: Minimize with max-calls " << maxfcn_used 
                 << " convergence for edm < " << tol << " strategy " 
-                << strategy << std::endl; 
+                << strategyLevel << std::endl; 
    }
 
    // internal minuit messages
@@ -339,16 +340,55 @@ bool Minuit2Minimizer::Minimize() {
 
    // set the precision if needed
    if (Precision() > 0) fState.SetPrecision(Precision());
+
+   // set strategy and add extra options if needed
+   ROOT::Minuit2::MnStrategy strategy(strategyLevel);
+   ROOT::Math::IOptions * minuit2Opt = ROOT::Math::MinimizerOptions::FindDefault("Minuit2");
+   if (minuit2Opt) { 
+      // set extra strategy options
+      int nGradCycles = strategy.GradientNCycles();
+      int nHessCycles = strategy.HessianNCycles();
+      int nHessGradCycles = strategy.HessianGradientNCycles();
+
+      double gradTol =  strategy.GradientTolerance();
+      double gradStepTol = strategy.GradientStepTolerance();
+      double hessStepTol = strategy.HessianStepTolerance();
+      double hessG2Tol = strategy.HessianG2Tolerance();
+
+      minuit2Opt->GetValue("GradientNCycles",nGradCycles);
+      minuit2Opt->GetValue("HessianNCycles",nHessCycles);
+      minuit2Opt->GetValue("HessianGradientNCycles",nHessGradCycles);
+
+      minuit2Opt->GetValue("GradientTolerance",gradTol);
+      minuit2Opt->GetValue("GradientStepTolerance",gradStepTol);
+      minuit2Opt->GetValue("HessianStepTolerance",hessStepTol);
+      minuit2Opt->GetValue("HessianG2Tolerance",hessG2Tol);
+
+      strategy.SetGradientNCycles(nGradCycles);      
+      strategy.SetHessianNCycles(nHessCycles);
+      strategy.SetHessianGradientNCycles(nHessGradCycles);
+
+      strategy.SetGradientTolerance(gradTol);
+      strategy.SetGradientStepTolerance(gradStepTol);
+      strategy.SetHessianStepTolerance(hessStepTol);
+      strategy.SetHessianG2Tolerance(hessStepTol);
+
+      if (PrintLevel() > 0) { 
+         std::cout << "Minuit2Minimizer::Minuit  - Changing default stratgey options" << std::endl;
+         minuit2Opt->Print();
+      }
+      
+   }
       
    const ROOT::Minuit2::FCNGradientBase * gradFCN = dynamic_cast<const ROOT::Minuit2::FCNGradientBase *>( fMinuitFCN ); 
    if ( gradFCN != 0) {
       // use gradient
       //SetPrintLevel(3);
-      ROOT::Minuit2::FunctionMinimum min =  GetMinimizer()->Minimize(*gradFCN, fState, ROOT::Minuit2::MnStrategy(strategy), maxfcn, tol);
+      ROOT::Minuit2::FunctionMinimum min =  GetMinimizer()->Minimize(*gradFCN, fState, strategy, maxfcn, tol);
       fMinimum = new ROOT::Minuit2::FunctionMinimum (min);    
    }
    else {
-      ROOT::Minuit2::FunctionMinimum min = GetMinimizer()->Minimize(*GetFCN(), fState, ROOT::Minuit2::MnStrategy(strategy), maxfcn, tol);
+      ROOT::Minuit2::FunctionMinimum min = GetMinimizer()->Minimize(*GetFCN(), fState, strategy, maxfcn, tol);
       fMinimum = new ROOT::Minuit2::FunctionMinimum (min);    
    }
 
diff --git a/misc/table/src/TTable.cxx b/misc/table/src/TTable.cxx
index ef93f29..d4adc89 100644
--- a/misc/table/src/TTable.cxx
+++ b/misc/table/src/TTable.cxx
@@ -1,4 +1,4 @@
-// @(#)root/table:$Id: TTable.cxx 43515 2012-03-27 21:15:53Z pcanal $
+// @(#)root/table:$Id: TTable.cxx 44532 2012-06-04 16:37:53Z pcanal $
 // Author: Valery Fine(fine at bnl.gov)   03/07/98
 
 /*************************************************************************
@@ -2158,31 +2158,41 @@ Int_t TTable::SetfN(Long_t len)
 #undef StreamElelement
 #endif
 
-#define StreamElementIn(type)  case TTableDescriptor::_NAME2_(k,type):        \
- if (evolutionOn) {                                  \
-     if (nextCol->fDimensions)  {                    \
-       if (nextCol->fOffset != UInt_t(-1)) {         \
-          R__b.ReadFastArray((_NAME2_(type,_t) *)(row+nextCol->fOffset),nextCol->fSize/sizeof(_NAME2_(type,_t)));   \
-       } else {                                        \
-           _NAME2_(type,_t) *readPtrV = new _NAME2_(type,_t)[nextCol->fSize/sizeof(_NAME2_(type,_t))];              \
-           R__b.ReadFastArray((_NAME2_(type,_t) *)(row+nextCol->fOffset),nextCol->fSize/sizeof(_NAME2_(type,_t)));  \
-           delete [] readPtrV;                       \
-           readPtrV = 0;                             \
-       }                                             \
-     }                                               \
-     else  {                                         \
-       _NAME2_(type,_t) skipBuffer;                  \
-       _NAME2_(type,_t) *readPtr =  (_NAME2_(type,_t) *)(row+nextCol->fOffset); \
-       if (nextCol->fOffset == UInt_t(-1)) readPtr = &skipBuffer;               \
-       R__b >> *readPtr;                             \
-     }                                               \
- } else {                                            \
-   if (nextCol->fDimensions)  {                      \
-     R__b.ReadFastArray  ((_NAME2_(type,_t) *)(row+nextCol->fOffset),nextCol->fSize/sizeof(_NAME2_(type,_t)));  \
-   } else                                                       \
-     R__b >> *(_NAME2_(type,_t) *)(row+nextCol->fOffset);       \
- }                                                              \
- break
+#define StreamElementIn(type)  case TTableDescriptor::_NAME2_(k,type): \
+   if (evolutionOn) {							\
+   if (nextCol->fDimensions) {					\
+     _NAME2_(type,_t) *readPtrV = new _NAME2_(type,_t)[nextCol->fSize/sizeof(_NAME2_(type,_t))]; \
+     R__b.ReadFastArray(readPtrV,nextCol->fSize/sizeof(_NAME2_(type,_t))); \
+     if (nextCol->fOffset != UInt_t(-1)) {				\
+       UInt_t x[3];							\
+       _NAME2_(type,_t) *writePtrV = (_NAME2_(type,_t) *)(row+currentDescriptor->Offset(colCounter)); \
+       memset(writePtrV, 0, currentDescriptor->ColumnSize(colCounter)); \
+       for (UInt_t i = 0; i < nextCol->fSize/sizeof(_NAME2_(type,_t)); i++) { \
+         UInt_t ii = i;						\
+         for (Int_t d = nextCol->fDimensions-1; d >=0; d--) {	\
+           x[d] = ii% nextCol->fIndexArray[d]; ii /= nextCol->fIndexArray[d]; \
+         }								\
+         Int_t j = -1;						\
+         for (UInt_t d = 0; d < currentDescriptor->Dimensions(colCounter); d++) { \
+           if (x[d] >= currentDescriptor->IndexArray(colCounter)[d]) {j = -1; break;} \
+           if (d == 0) j = x[d];					\
+           else        j = currentDescriptor->IndexArray(colCounter)[d]*j + x[d]; \
+         }								\
+         if (j >= 0) writePtrV[j] = readPtrV[i];			\
+       }								\
+     }								\
+     delete [] readPtrV;						\
+     readPtrV = 0;							\
+   } else {								\
+     _NAME2_(type,_t) skipBuffer;					\
+     _NAME2_(type,_t) *readPtr = (_NAME2_(type,_t) *)(row+nextCol->fOffset);	\
+     if (nextCol->fOffset == UInt_t(-1)) readPtr = &skipBuffer; R__b >> *readPtr; \
+   }									\
+ } else { if (nextCol->fDimensions) {				\
+     R__b.ReadFastArray ((_NAME2_(type,_t) *)(row+nextCol->fOffset),nextCol->fSize/sizeof(_NAME2_(type,_t))); \
+   } else R__b >> *(_NAME2_(type,_t) *)(row+nextCol->fOffset);	\
+ }									\
+ break;
 
 #define StreamElementOut(type) case TTableDescriptor::_NAME2_(k,type):    \
  if (nextCol->fDimensions)                                    \
diff --git a/misc/table/src/TTableDescriptor.cxx b/misc/table/src/TTableDescriptor.cxx
index e83fa1f..04d5232 100644
--- a/misc/table/src/TTableDescriptor.cxx
+++ b/misc/table/src/TTableDescriptor.cxx
@@ -1,4 +1,4 @@
-// @(#)root/table:$Id: TTableDescriptor.cxx 41244 2011-10-06 19:42:35Z pcanal $
+// @(#)root/table:$Id: TTableDescriptor.cxx 44540 2012-06-04 20:18:03Z pcanal $
 // Author: Valery Fine   09/08/99  (E-mail: fine at bnl.gov)
 
 /*************************************************************************
@@ -349,15 +349,25 @@ Int_t TTableDescriptor::UpdateOffsets(const TTableDescriptor *newDescriptor)
       if (newType == kInt)       newType = kLong;
       else if (newType == kUInt) newType = kULong;
 #endif
-      if (    colNewIndx >=0
-         && Dimensions(colCounter) == newDescriptor->Dimensions(colNewIndx)
-         && ColumnType(colCounter) == newType)  {
+      if ( colNewIndx >=0
+	   && Dimensions(colCounter) == newDescriptor->Dimensions(colNewIndx)
+	   && ColumnType(colCounter) == newType) {
+     Bool_t same = kFALSE;
+      if ( Dimensions(colCounter)) {
+	for (UInt_t d = 0; d < Dimensions(colCounter); ++d) {
+	  if (IndexArray(colCounter)[d] != newDescriptor->IndexArray(colNewIndx)[d]){  same = kTRUE; break; }
+	}
+      }
          SetOffset(newDescriptor->Offset(colNewIndx),colCounter);
          if (colNewIndx != colCounter) {
             Printf("Schema evolution: \t%d column of the \"%s\" table has been moved to %d-th column\n",
             colCounter,ColumnName(colCounter),colNewIndx);
             mismathes++;
-         }
+         } else if (same) { 
+	   Printf("Schema evolution: \t%d column \"%s\" size has been changed\n",
+		  colNewIndx, ColumnName(colCounter));
+	   mismathes++; 
+	 }
       } else {
          Printf("Schema evolution: \t%d column \"%s\" of %d type has been lost\n",
          colCounter,ColumnName(colCounter),ColumnType(colCounter));
diff --git a/net/auth/src/TAuthenticate.cxx b/net/auth/src/TAuthenticate.cxx
index 7c9fcbf..f619246 100644
--- a/net/auth/src/TAuthenticate.cxx
+++ b/net/auth/src/TAuthenticate.cxx
@@ -1,4 +1,4 @@
-// @(#)root/auth:$Id: TAuthenticate.cxx 43081 2012-02-22 10:04:08Z rdm $
+// @(#)root/auth:$Id: TAuthenticate.cxx 44523 2012-06-04 15:17:29Z ganis $
 // Author: Fons Rademakers   26/11/2000
 
 /*************************************************************************
@@ -502,8 +502,11 @@ negotia:
       if (user != "")
          CheckNetrc(user, passwd, pwhash, kTRUE);
       if (passwd == "") {
-         if (fgPromptUser)
-            user = PromptUser(fRemote);
+         if (fgPromptUser) {
+            char *p = PromptUser(fRemote);
+            user = p;
+            delete [] p;
+         }
          rc = GetUserPasswd(user, passwd, pwhash, kTRUE);
       }
       fUser = user;
diff --git a/net/krb5auth/src/TKSocket.cxx b/net/krb5auth/src/TKSocket.cxx
index 0c042b2..3de8700 100644
--- a/net/krb5auth/src/TKSocket.cxx
+++ b/net/krb5auth/src/TKSocket.cxx
@@ -1,10 +1,13 @@
-// @(#)root/krb5auth:$Id: TKSocket.cxx 41644 2011-10-29 22:38:37Z rdm $
+// @(#)root/krb5auth:$Id: TKSocket.cxx 44287 2012-05-18 10:28:12Z rdm $
 // Author: Maarten Ballintijn   27/10/2003
 
 #include <stdlib.h>
 #include <errno.h>
 #include <sys/types.h>
 #include <netinet/in.h>
+#ifndef WIN32
+#   include <unistd.h>
+#endif
 
 #include "TKSocket.h"
 #include "TSocket.h"
diff --git a/net/net/inc/TMessage.h b/net/net/inc/TMessage.h
index 420a3a9..f3b3e3a 100644
--- a/net/net/inc/TMessage.h
+++ b/net/net/inc/TMessage.h
@@ -1,4 +1,4 @@
-// @(#)root/net:$Id: TMessage.h 41637 2011-10-28 15:34:35Z rdm $
+// @(#)root/net:$Id: TMessage.h 44489 2012-06-04 00:52:12Z rdm $
 // Author: Fons Rademakers   19/12/96
 
 /*************************************************************************
@@ -44,7 +44,7 @@ friend class TPSocket;
 friend class TXSocket;
 
 private:
-   TList   *fInfos;       //Array of TStreamerInfo used in WriteObject
+   TList   *fInfos;       //List of TStreamerInfo used in WriteObject
    TBits    fBitsPIDs;    //Array of bits to mark the TProcessIDs uids written to the message
    UInt_t   fWhat;        //Message type
    TClass  *fClass;       //If message is kMESS_OBJECT pointer to object's class
@@ -82,6 +82,7 @@ public:
 
    void     EnableSchemaEvolution(Bool_t enable = kTRUE) { fEvolution = enable; }
    Bool_t   UsesSchemaEvolution() const { return fEvolution; }
+   TList   *GetStreamerInfos() const { return fInfos; }
    Int_t    GetCompressionAlgorithm() const;
    Int_t    GetCompressionLevel() const;
    Int_t    GetCompressionSettings() const;
diff --git a/net/net/src/TSSLSocket.cxx b/net/net/src/TSSLSocket.cxx
index 3191930..1f8c354 100644
--- a/net/net/src/TSSLSocket.cxx
+++ b/net/net/src/TSSLSocket.cxx
@@ -38,40 +38,40 @@ void TSSLSocket::WrapWithSSL(void)
 
    // New context
    if (!(fSSLCtx = SSL_CTX_new(SSLv23_method()))) {
-      Error("TSSLSocket::WrapWithSSL()", "the context could not be created");
+      Error("WrapWithSSL", "the context could not be created");
       goto wrapFailed;
    }
 
    if ((fgSSLCAFile[0] || fgSSLCAPath[0]) && SSL_CTX_load_verify_locations(fSSLCtx, fgSSLCAFile, fgSSLCAPath) == 0) {
-      Error("TSSLSocket::WrapWithSSL", "Could not set the CA file and/or the CA path");
+      Error("WrapWithSSL", "could not set the CA file and/or the CA path");
       goto wrapFailed;
    }
 
    if (fgSSLUCert[0] && SSL_CTX_use_certificate_chain_file(fSSLCtx, fgSSLUCert) == 0) {
-      Error("TSSLSocket::WrapWithSSL", "Could not set the client certificate");
+      Error("WrapWithSSL", "could not set the client certificate");
       goto wrapFailed;
    }
 
    if (fgSSLUKey[0] && SSL_CTX_use_PrivateKey_file(fSSLCtx, fgSSLUKey, SSL_FILETYPE_PEM) == 0) {
-      Error("TSSLSocket::WrapWithSSL", "Could not set the client private key");
+      Error("WrapWithSSL", "could not set the client private key");
       goto wrapFailed;
    }
 
    // New SSL structure
    if (!(fSSL = SSL_new(fSSLCtx))) {
-      Error("TSSLSocket::WrapWithSSL()", "cannot create the ssl struct");
+      Error("WrapWithSSL", "cannot create the ssl struct");
       goto wrapFailed;
    }
 
    // Bind to the socket
    if (SSL_set_fd(fSSL, fSocket) != 1) {
-      Error("TSSLSocket::WrapWithSSL()", "cannot bind to the socket %d", fSocket);
+      Error("WrapWithSSL", "cannot bind to the socket %d", fSocket);
       goto wrapFailed;
    }
 
    // Open connection
    if (SSL_connect(fSSL) != 1) {
-      Error("TSSLSocket::WrapWithSSL()", "cannot connect");
+      Error("WrapWithSSL", "cannot connect");
       goto wrapFailed;
    }
 
@@ -178,7 +178,7 @@ void TSSLSocket::SetUpSSL(const char *cafile, const char *capath,
 //______________________________________________________________________________
 Int_t TSSLSocket::Recv(TMessage *& /*mess */)
 {
-   Error("TSSLSocket::Recv(TMessage*&)", "Not implemented");
+   Error("Recv", "not implemented");
    return -1;
 }
 
@@ -195,34 +195,45 @@ Int_t TSSLSocket::RecvRaw(void *buffer, Int_t length, ESendRecvOptions opt)
    ResetBit(TSocket::kBrokenConn);
 
    Int_t n;
-
-   if (opt == kPeek)
-      n = SSL_peek(fSSL, buffer, (int)length);
-   else
-      n = SSL_read(fSSL, buffer, (int)length);
-
-   if (n <= 0) {
-      if (SSL_get_error(fSSL, n) == SSL_ERROR_ZERO_RETURN || SSL_get_error(fSSL, n) == SSL_ERROR_SYSCALL) {
-         // Connection closed, reset or broken
-         SetBit(TSocket::kBrokenConn);
-         SSL_set_quiet_shutdown(fSSL, 1); // Socket is gone, sending "close notify" will fail
-         Close();
-      }
-      return n;
+   Int_t offset = 0;
+   Int_t remain = length;
+
+   // SSL_read/SSL_peek may not return the total length at once
+   while (remain > 0) {
+     if (opt == kPeek)
+        n = SSL_peek(fSSL, (char*)buffer + offset, (int)remain);
+     else
+        n = SSL_read(fSSL, (char*)buffer + offset, (int)remain);
+
+     if (n <= 0) {
+        if (gDebug > 0)
+           Error("RecvRaw", "failed to read from the socket");
+
+        if (SSL_get_error(fSSL, n) == SSL_ERROR_ZERO_RETURN || SSL_get_error(fSSL, n) == SSL_ERROR_SYSCALL) {
+           // Connection closed, reset or broken
+           SetBit(TSocket::kBrokenConn);
+           SSL_set_quiet_shutdown(fSSL, 1); // Socket is gone, sending "close notify" will fail
+           Close();
+        }
+        return n;
+     }
+     
+     offset += n;
+     remain -= n;
    }
 
-   fBytesRecv  += n;
-   fgBytesRecv += n;
+   fBytesRecv  += length;
+   fgBytesRecv += length;
 
    Touch();  // update usage timestamp
 
-   return n;
+   return offset;
 }
 
 //______________________________________________________________________________
 Int_t TSSLSocket::Send(const TMessage & /* mess */)
 {
-   Error("TSSLSocket::Send(TMessage*&)", "Not implemented");
+   Error("Send", "not implemented");
    return -1;
 }
 
diff --git a/net/net/src/TWebFile.cxx b/net/net/src/TWebFile.cxx
index ca6af79..10959ea 100644
--- a/net/net/src/TWebFile.cxx
+++ b/net/net/src/TWebFile.cxx
@@ -1,4 +1,4 @@
-// @(#)root/net:$Id: TWebFile.cxx 43125 2012-02-26 14:12:12Z rdm $
+// @(#)root/net:$Id: TWebFile.cxx 44247 2012-05-15 09:12:06Z rdm $
 // Author: Fons Rademakers   17/01/97
 
 /*************************************************************************
@@ -671,10 +671,15 @@ Int_t TWebFile::GetFromWeb10(char *buf, Int_t len, const TString &msg)
 
          if (first >= 0) {
             Int_t ll = Int_t(last - first) + 1;
-            if (fSocket->RecvRaw(&buf[ltot], ll) == -1) {
+            Int_t rsize;
+            if ((rsize = fSocket->RecvRaw(&buf[ltot], ll)) == -1) {
                Error("GetFromWeb10", "error receiving data from host %s", fUrl.GetHost());
                return -1;
             }
+            else if (ll != rsize) {
+               Error("GetFromWeb10", "expected %d bytes, got %d", ll, rsize);
+               return -1;
+            }
             ltot += ll;
 
             first = -1;
diff --git a/net/rootd/src/rootd.cxx b/net/rootd/src/rootd.cxx
index 1304f6e..2bcf668 100644
--- a/net/rootd/src/rootd.cxx
+++ b/net/rootd/src/rootd.cxx
@@ -1,4 +1,4 @@
-// @(#)root/rootd:$Id: rootd.cxx 38593 2011-03-23 22:48:30Z ganis $
+// @(#)root/rootd:$Id: rootd.cxx 44523 2012-06-04 15:17:29Z ganis $
 // Author: Fons Rademakers   11/08/97
 
 /*************************************************************************
@@ -745,6 +745,7 @@ again:
    // lock the file
    if (lockf(fid, F_LOCK, (off_t)1) == -1) {
       ErrorInfo("RootdCloseTab: error locking %s", sfile);
+      close(fid);
       return;
    }
    if (gDebug > 2)
@@ -814,6 +815,7 @@ again:
    lseek(fid, 0, SEEK_SET);
    if (lockf(fid, F_ULOCK, (off_t)1) == -1) {
       ErrorInfo("RootdCloseTab: error unlocking %s", sfile);
+      close(fid);
       return;
    }
    if (gDebug > 2)
diff --git a/net/rpdutils/src/rpdutils.cxx b/net/rpdutils/src/rpdutils.cxx
index 6fdf9d1..bca7fb3 100644
--- a/net/rpdutils/src/rpdutils.cxx
+++ b/net/rpdutils/src/rpdutils.cxx
@@ -1,4 +1,4 @@
-// @(#)root/rpdutils:$Id: rpdutils.cxx 43081 2012-02-22 10:04:08Z rdm $
+// @(#)root/rpdutils:$Id: rpdutils.cxx 44523 2012-06-04 15:17:29Z ganis $
 // Author: Gerardo Ganis    7/4/2003
 
 /*************************************************************************
@@ -944,7 +944,7 @@ int RpdUpdateAuthTab(int opt, const char *line, char **token, int ilck)
    }
 
    goingout:
-   if (ilck == 0) {
+   if (itab != ilck) {
       // unlock the file
       lseek(itab, 0, SEEK_SET);
       if (lockf(itab, F_ULOCK, (off_t) 1) == -1) {
@@ -2450,6 +2450,7 @@ int RpdSshAuth(const char *sstr)
          NetSend(kErrNoPipeInfo, kROOTD_ERR);
          delete[] uniquePipe;
          delete[] pipeFile;
+         close(unixFd);
          return auth;
       } else {
          // File open: fill it
@@ -4516,14 +4517,17 @@ int RpdCheckSshd(int opt)
       localAddr.sin_port = htons(0);
       if (bind(sd, (struct sockaddr *) &localAddr, sizeof(localAddr)) < 0) {
          ErrorInfo("RpdCheckSshd: cannot bind to local port %u", gSshdPort);
+         close(sd);
          return 0;
       }
       // connect to server
       if (connect(sd, (struct sockaddr *) &servAddr, sizeof(servAddr)) < 0) {
          ErrorInfo("RpdCheckSshd: cannot connect to local port %u",
                    gSshdPort);
+         close(sd);
          return 0;
       }
+      close(sd);
       // Sshd successfully contacted
       if (gDebug > 2)
          ErrorInfo("RpdCheckSshd: success!");
@@ -6634,6 +6638,7 @@ int RpdRetrieveSpecialPass(const char *usr, const char *fpw, char *pass, int lpw
    if (fstat(fid, &st) == -1) {
       ErrorInfo("RpdRetrieveSpecialPass: cannot stat descriptor %d"
                   " %s (errno: %d)", fid, GetErrno());
+      close(fid);
       rc = -1;
       goto back;
    }
@@ -6643,6 +6648,7 @@ int RpdRetrieveSpecialPass(const char *usr, const char *fpw, char *pass, int lpw
                 " 0%o (should be 0600)", rootdpass, (st.st_mode & 0777));
       ErrorInfo("RpdRetrieveSpecialPass: %d %d",
                 S_ISREG(st.st_mode),S_ISDIR(st.st_mode));
+      close(fid);
       rc = -2;
       goto back;
    }
diff --git a/net/rpdutils/src/ssh.cxx b/net/rpdutils/src/ssh.cxx
index dd16251..1644ccc 100644
--- a/net/rpdutils/src/ssh.cxx
+++ b/net/rpdutils/src/ssh.cxx
@@ -1,4 +1,4 @@
-// @(#)root/rpdutils:$Id: ssh.cxx 41954 2011-11-13 18:17:49Z rdm $
+// @(#)root/rpdutils:$Id: ssh.cxx 44523 2012-06-04 15:17:29Z ganis $
 // Author: Gerardo Ganis    7/4/2003
 
 /*************************************************************************
@@ -227,6 +227,7 @@ int SshToolNotifyFailure(const char *Pipe)
         connect(sd, (struct sockaddr *) &servAddr,
                 sizeof(servAddr))) < 0) {
       ErrorInfo("SshToolNotifyFailure: cannot connect socket: exiting ");
+      close(sd);
       return 1;
    }
    // Sending "KO" ...
@@ -237,6 +238,7 @@ int SshToolNotifyFailure(const char *Pipe)
           ("SshToolNotifyFailure: sending might have been unsuccessful (bytes send: %d)",
            rc);
    }
+   close(sd);
 
    return 0;
 }
diff --git a/proof/CMakeLists.txt b/proof/CMakeLists.txt
index 5a630eb..69540d1 100644
--- a/proof/CMakeLists.txt
+++ b/proof/CMakeLists.txt
@@ -1,5 +1,8 @@
 add_subdirectory(proof)
 add_subdirectory(proofplayer) # special CMakeListst.txt
+if(afdsmgrd)
+  add_subdirectory(afdsmgrd)
+endif()
 if(xrootd)
   add_subdirectory(proofd)
   add_subdirectory(proofx)
diff --git a/proof/afdsmgrd/CMakeLists.txt b/proof/afdsmgrd/CMakeLists.txt
new file mode 100644
index 0000000..02eaaa8
--- /dev/null
+++ b/proof/afdsmgrd/CMakeLists.txt
@@ -0,0 +1,142 @@
+############################################################################
+# CMakeLists.txt file for building PROOF's afdsmgrd
+# @author Dario Berzano
+############################################################################
+
+#
+# Variables for afdsmgrd: all of them are *absolute* paths
+#
+
+set(AFDSMGRD_UNPACK_DIR  ${CMAKE_CURRENT_BINARY_DIR}/afdsmgrdUnpack)
+set(AFDSMGRD_INSTALL_DIR ${AFDSMGRD_UNPACK_DIR}/install)
+set(AFDSMGRD_BUILD_DIR   ${AFDSMGRD_UNPACK_DIR}/build)
+set(AFDSMGRD_BIN         ${AFDSMGRD_INSTALL_DIR}/bin/afdsmgrd)
+
+# Taking MonALISA from MONALISA_DIR, if defined, or from AliEn. If neither
+# MonALISA nor AliEn are enabled, don't build afdsmgrd with MonALISA support
+if(monalisa)
+  set(AFDSMGRD_MONALISA_DIR "${MONALISA_DIR}")
+elseif(alien)
+  set(AFDSMGRD_MONALISA_DIR "${ALIEN_DIR}")
+endif()
+
+#
+# Pass all possible ROOT include paths to underlying CMake
+#
+
+# Get all possible include paths into a variable (one path per line)
+execute_process(
+  COMMAND find "${CMAKE_SOURCE_DIR}" -maxdepth 3 -name inc -type d
+  OUTPUT_VARIABLE AFDSMGRD_INCDIR_Raw
+  OUTPUT_STRIP_TRAILING_WHITESPACE
+)
+
+# Separate paths with colons
+string(REPLACE "\n" ":" AFDSMGRD_INCDIR_Path ${AFDSMGRD_INCDIR_Raw})
+
+#
+# Build targets
+#
+
+# afdsmgrd steering target, always built (i.e., "phony", i.e., always ood). Let
+# this target depend on ALL known ROOT libraries (TODO: Maybe there is a better
+# way to get the list of ROOT libs?)
+add_custom_target(afdsmgrd ALL
+  DEPENDS Core Cint RIO Net Hist Graf Graf3d Gpad Tree Rint Postscript Matrix
+    Physics MathCore Thread Proof afdsmgrdInstall)
+
+# make install on afdsmgrd
+add_custom_command(
+  OUTPUT afdsmgrdInstall
+  COMMENT "Building afdsmgrd"
+  DEPENDS afdsmgrdPrepare
+  COMMAND ${CMAKE_COMMAND} -E remove -f afdsmgrdInstall
+  COMMAND make install -C ${AFDSMGRD_BUILD_DIR}
+
+  # Workaround: on some configurations libdir is not created (because there is
+  # no need to) causing subsequent "install" command to fail
+  COMMAND ${CMAKE_COMMAND} -E make_directory ${AFDSMGRD_INSTALL_DIR}/lib
+
+  COMMAND ${CMAKE_COMMAND} -E touch afdsmgrdInstall
+)
+
+# CMake configuration of afdsmgrd
+add_custom_command(
+  OUTPUT afdsmgrdPrepare
+  COMMENT "Preparing afdsmgrd"
+  DEPENDS ${AFDSMGRD_UNPACK_DIR}
+
+  # The file afdsmgrdPrepare is created to signal a success: reset it
+  COMMAND ${CMAKE_COMMAND} -E remove -f afdsmgrdPrepare
+
+  # Create build directory
+  COMMAND ${CMAKE_COMMAND} -E make_directory ${AFDSMGRD_BUILD_DIR}
+
+  # Run cmake on the afdsmgrd project: mind the EXTRA_INCDIR variable
+  COMMAND ${CMAKE_COMMAND} -E chdir ${AFDSMGRD_BUILD_DIR} ${CMAKE_COMMAND} ..
+    -DCMAKE_INSTALL_PREFIX="${AFDSMGRD_INSTALL_DIR}"
+    -DROOTSYS="${CMAKE_BINARY_DIR}"
+    -DApMon_PREFIX="${AFDSMGRD_MONALISA_DIR}"
+    -DCMAKE_BUILD_TYPE=Release
+    -DEXTRA_INCDIR="${AFDSMGRD_INCDIR_Path}"
+
+  # The following command won't be executed if previous command has failed
+  COMMAND ${CMAKE_COMMAND} -E touch afdsmgrdPrepare
+)
+
+# Unpacks afdsmgrd tar.gz found in source directory into build directory (which
+# is current working directory by default)
+add_custom_command(
+  OUTPUT ${AFDSMGRD_UNPACK_DIR}
+  COMMENT "Unpacking afdsmgrd tarball"
+  COMMAND ${CMAKE_COMMAND} -E tar xzf
+    ${CMAKE_CURRENT_SOURCE_DIR}/afdsmgrd-v*.tar.gz
+  COMMAND ${CMAKE_COMMAND} -E rename afdsmgrd ${AFDSMGRD_UNPACK_DIR}
+)
+
+#
+# Install targets -- note that the trailing slashes are fundamental
+#
+
+# etc --> <prefix>/etc/proof
+install(
+  DIRECTORY ${AFDSMGRD_INSTALL_DIR}/etc/
+  DESTINATION ${CMAKE_INSTALL_PREFIX}/etc/proof
+  USE_SOURCE_PERMISSIONS
+)
+
+# bin --> <prefix>/bin
+install(
+  DIRECTORY ${AFDSMGRD_INSTALL_DIR}/bin/
+  DESTINATION ${CMAKE_INSTALL_PREFIX}/bin
+  USE_SOURCE_PERMISSIONS
+)
+
+# lib --> <prefix>/etc/proof/lib
+install(
+  DIRECTORY ${AFDSMGRD_INSTALL_DIR}/lib/
+  DESTINATION ${CMAKE_INSTALL_PREFIX}/etc/proof/lib
+  USE_SOURCE_PERMISSIONS
+)
+
+# libexec --> <prefix>/etc/proof
+install(
+  DIRECTORY ${AFDSMGRD_INSTALL_DIR}/libexec/
+  DESTINATION ${CMAKE_INSTALL_PREFIX}/etc/proof
+  USE_SOURCE_PERMISSIONS
+)
+
+# var --> <prefix>/etc/proof/var
+# Nothing goes here for the moment!
+#install(
+#  DIRECTORY ${AFDSMGRD_INSTALL_DIR}/var/
+#  DESTINATION ${CMAKE_INSTALL_PREFIX}/etc/proof/var
+#  USE_SOURCE_PERMISSIONS
+#)
+
+# share --> <prefix>/etc/proof/utils/afdsmgrd
+install(
+  DIRECTORY ${AFDSMGRD_INSTALL_DIR}/share/
+  DESTINATION ${CMAKE_INSTALL_PREFIX}/etc/proof/utils/afdsmgrd
+  USE_SOURCE_PERMISSIONS
+)
diff --git a/proof/afdsmgrd/afdsmgrd-v0.9.6.tar.gz b/proof/afdsmgrd/afdsmgrd-v0.9.6.tar.gz
deleted file mode 100644
index 8ba0555..0000000
Binary files a/proof/afdsmgrd/afdsmgrd-v0.9.6.tar.gz and /dev/null differ
diff --git a/proof/afdsmgrd/afdsmgrd-v1.0.2.tar.gz b/proof/afdsmgrd/afdsmgrd-v1.0.2.tar.gz
new file mode 100644
index 0000000..1bfdcdb
Binary files /dev/null and b/proof/afdsmgrd/afdsmgrd-v1.0.2.tar.gz differ
diff --git a/proof/doc/v534/index.html b/proof/doc/v534/index.html
index 44bfb1b..a400515 100644
--- a/proof/doc/v534/index.html
+++ b/proof/doc/v534/index.html
@@ -3,7 +3,7 @@
 <a name="proof"></a>
 <h3>PROOF System</h3>
 <ul>
-  <li style="font-style: italic;">Added functionality</li>
+  <li style="font-style: italic;">Added functionality
   <ul>
     <li>Added interface to simplify the creation of the performance
 tree: two new methods TProof::SetPerfTree("<file>") and
@@ -47,7 +47,8 @@ special name 'stats' enables the three feedback histograms required by
 a dedicated new class TStatsFeedback, and uses a TStatsFeedback instead
 of TDrawFeedback to display the feedback. </li>
   </ul>
-  <li style="font-style: italic;">Improvements</li>
+  </li>
+  <li style="font-style: italic;">Improvements
   <ul>
     <li>Add to TProofMgr two static functions to upload files. These
 functions are both called UploadFiles and differ in the first argument,
@@ -83,7 +84,8 @@ include path. This solves the longstanding annoying problem of failure
 when a directory or file with the name of the package did already exist
 in the local working directory. </li>
   </ul>
-  <li style="font-style: italic;">Fixes</li>
+  </li>
+  <li style="font-style: italic;">Fixes
   <ul>
     <li>Fix merging issue affecting automatic dataset creation when
 only one worker is active.</li>
@@ -99,5 +101,6 @@ is different from the one o the master, e.g. PoD on gLite.</li>
 template in 'xpd.multiuser'.
     </li>
   </ul>
+  </li>
 </ul>
 
diff --git a/proof/proof/src/TDataSetManager.cxx b/proof/proof/src/TDataSetManager.cxx
index 7b38781..156352b 100644
--- a/proof/proof/src/TDataSetManager.cxx
+++ b/proof/proof/src/TDataSetManager.cxx
@@ -1,4 +1,4 @@
-// @(#)root/base:$Id: TDataSetManager.cxx 44065 2012-05-02 12:41:50Z ganis $
+// @(#)root/base:$Id: TDataSetManager.cxx 44555 2012-06-05 09:01:20Z ganis $
 // Author: Jan Fiete Grosse-Oetringhaus, 04.06.07
 
 /*************************************************************************
@@ -1408,7 +1408,7 @@ Bool_t TDataSetManager::CheckStagedStatus(TFileInfo *fileInfo, Int_t fopt, Int_t
 
       fileInfo->ResetUrl();
       if (!fileInfo->GetCurrentUrl()) {
-         ::Error("TDataSetManager::ScanDataSet", "GetCurrentUrl() returned 0 for %s",
+         ::Error("TDataSetManager::CheckStagedStatus", "GetCurrentUrl() returned 0 for %s",
                                                 fileInfo->GetFirstUrl()->GetUrl());
          return kFALSE;
       }
@@ -1441,7 +1441,7 @@ Bool_t TDataSetManager::CheckStagedStatus(TFileInfo *fileInfo, Int_t fopt, Int_t
                // Actually access the file
                char tmpChar = 0;
                if (file->ReadBuffer(&tmpChar, 1))
-                  ::Warning("TDataSetManager::ScanDataSet", "problems reading 1 byte from open file");
+                  ::Warning("TDataSetManager::CheckStagedStatus", "problems reading 1 byte from open file");
                // Count
                touched = kTRUE;
             }
@@ -1449,7 +1449,7 @@ Bool_t TDataSetManager::CheckStagedStatus(TFileInfo *fileInfo, Int_t fopt, Int_t
             delete file;
          } else {
             // File could not be opened, reset staged bit
-            if (dbg) ::Info("TDataSetManager::ScanDataSet", "file %s disappeared", url.GetUrl());
+            if (dbg) ::Info("TDataSetManager::CheckStagedStatus", "file %s disappeared", url.GetUrl());
             fileInfo->ResetBit(TFileInfo::kStaged);
             disappeared = kTRUE;
             changed = kTRUE;
@@ -1492,11 +1492,11 @@ Bool_t TDataSetManager::CheckStagedStatus(TFileInfo *fileInfo, Int_t fopt, Int_t
       if (stager) {
          result = stager->IsStaged(url.GetUrl());
          if (gDebug > 0)
-            ::Info("TDataSetManager::ScanDataSet", "IsStaged: %s: %d", url.GetUrl(), result);
+            ::Info("TDataSetManager::CheckStagedStatus", "IsStaged: %s: %d", url.GetUrl(), result);
          if (createStager)
             SafeDelete(stager);
       } else {
-         ::Warning("TDataSetManager::ScanDataSet",
+         ::Warning("TDataSetManager::CheckStagedStatus",
                   "could not get stager instance for '%s'", url.GetUrl());
       }
 
@@ -1667,12 +1667,18 @@ Int_t TDataSetManager::ScanFile(TFileInfo *fileinfo, Bool_t dbg)
       
       // Add url of the disk server in front of the list
       if (file->GetEndpointUrl()) {
+         // add endpoint url if it is not a local file
          TUrl eurl(*(file->GetEndpointUrl()));
-         eurl.SetOptions(url->GetOptions());
-         eurl.SetAnchor(url->GetAnchor());
-         fileinfo->AddUrl(eurl.GetUrl(), kTRUE);
 
-         if (gDebug > 0) ::Info("TDataSetManager::ScanFile", "added URL %s", eurl.GetUrl());
+         if (strcmp(eurl.GetProtocol(), "file") ||
+            !strcmp(eurl.GetProtocol(), url->GetProtocol())) { 
+            
+            eurl.SetOptions(url->GetOptions());
+            eurl.SetAnchor(url->GetAnchor());
+            fileinfo->AddUrl(eurl.GetUrl(), kTRUE);
+
+            if (gDebug > 0) ::Info("TDataSetManager::ScanFile", "added URL %s", eurl.GetUrl());
+         }
       } else {
          ::Warning("TDataSetManager::ScanFile", "end-point URL undefined for file %s", file->GetName());
       }
@@ -1701,14 +1707,18 @@ Int_t TDataSetManager::ScanFile(TFileInfo *fileinfo, Bool_t dbg)
       if (file->GetSize() > 0) fileinfo->SetSize(file->GetSize());
       fileinfo->SetBit(TFileInfo::kStaged);
 
-      // Add url of the disk server in front of the list
+      // Add url of the disk server in front of the list if it is not a local file
       TUrl eurl(*(file->GetEndpointUrl()));
-      eurl.SetOptions(url->GetOptions());
-      eurl.SetAnchor(url->GetAnchor());
-      fileinfo->AddUrl(eurl.GetUrl(), kTRUE);
 
-      if (gDebug > 0) ::Info("TDataSetManager::ScanFile", "added URL %s", eurl.GetUrl());
+      if (strcmp(eurl.GetProtocol(), "file") ||
+         !strcmp(eurl.GetProtocol(), url->GetProtocol())) { 
 
+         eurl.SetOptions(url->GetOptions());
+         eurl.SetAnchor(url->GetAnchor());
+         fileinfo->AddUrl(eurl.GetUrl(), kTRUE);
+
+         if (gDebug > 0) ::Info("TDataSetManager::ScanFile", "added URL %s", eurl.GetUrl());
+      }
       fileinfo->SetUUID(file->GetUUID().AsString());
    }
    rc = 0;
diff --git a/proof/proofd/src/XrdProofConn.cxx b/proof/proofd/src/XrdProofConn.cxx
index 190f21e..3aa43db 100644
--- a/proof/proofd/src/XrdProofConn.cxx
+++ b/proof/proofd/src/XrdProofConn.cxx
@@ -1,4 +1,4 @@
-// @(#)root/proofd:$Id: XrdProofConn.cxx 44103 2012-05-03 23:11:44Z ganis $
+// @(#)root/proofd:$Id: XrdProofConn.cxx 44523 2012-06-04 15:17:29Z ganis $
 // Author: Gerardo Ganis  12/12/2005
 
 /*************************************************************************
@@ -27,6 +27,7 @@
 #include "XpdSysPthread.h"
 
 #include "XrdProofConn.h"
+#include "XrdProofdAux.h"
 #include "XProofProtocol.h"
 
 #include "XrdClient/XrdClientConnMgr.hh"
@@ -85,9 +86,6 @@ int XrdProofConn::fgTimeWait = 2;  // seconds
 XrdSysPlugin *XrdProofConn::fgSecPlugin = 0;       // Sec library plugin
 void         *XrdProofConn::fgSecGetProtocol = 0;  // Sec protocol getter
 
-#ifndef SafeDelete
-#define SafeDelete(x) { if (x) { delete x; x = 0; } }
-#endif
 #define URLTAG "["<<fUrl.Host<<":"<<fUrl.Port<<"]"
 
 //_____________________________________________________________________________
@@ -297,8 +295,8 @@ XrdProofConn::~XrdProofConn()
    }
 
    // Cleanup mutex
-   SafeDelete(fMutex);
-   SafeDelete(fConnectInterruptMtx);
+   SafeDel(fMutex);
+   SafeDel(fConnectInterruptMtx);
 }
 
 //_____________________________________________________________________________
@@ -553,7 +551,7 @@ XrdClientMessage *XrdProofConn::SendRecv(XPClientRequest *req, const void *reqDa
                   TRACE(XERR, "reallocating "<<dataRecvSize<<" bytes");
                   free((void *) *answData);
                   *answData = 0;
-                  SafeDelete(xmsg);
+                  SafeDel(xmsg);
                   return xmsg;
                }
             }
@@ -581,7 +579,7 @@ XrdClientMessage *XrdProofConn::SendRecv(XPClientRequest *req, const void *reqDa
                XPD::convertRespStatusToChar(xmsg->fHdr.status)<<
                "] (server "<<URLTAG<<") - Abort");
          // We cannot continue
-         SafeDelete(xmsg);
+         SafeDel(xmsg);
          return xmsg;
       }
       // The last message may be empty: not an error
@@ -672,7 +670,7 @@ XrdClientMessage *XrdProofConn::SendReq(XPClientRequest *req, const void *reqDat
       }
       if (abortcmd) {
          // Cleanup if failed
-         SafeDelete(answMex);
+         SafeDel(answMex);
       } else if (!resp) {
          // Sleep a while before retrying
          int sleeptime = 1;
@@ -1055,7 +1053,7 @@ bool XrdProofConn::Login()
    if (ug.length() > 8) {
       // The name must go in the attached buffer because the login structure
       // can accomodate at most 8 chars
-      strcpy( (char *)reqhdr.login.username, "?>buf" );
+      strncpy( (char *)reqhdr.login.username, "?>buf", sizeof(reqhdr.login.username));
       // Add the name to the login buffer, if not already done during
       // a previous login (for example if we are reconnecting ...)
       if (fLoginBuffer.find("|usr:") == STR_NPOS) {
@@ -1066,7 +1064,7 @@ bool XrdProofConn::Login()
       memcpy((void *)reqhdr.login.username, (void *)(ug.c_str()), ug.length());
       if (ug.length() < 8) reqhdr.login.username[ug.length()] = '\0';
    } else {
-      strcpy((char *)reqhdr.login.username, "????" );
+      strncpy((char *)reqhdr.login.username, "????", sizeof(reqhdr.login.username));
    }
 
    // This is the place to send a token for fast authentication
@@ -1183,15 +1181,14 @@ bool XrdProofConn::Login()
                // We failed the aythentication attempt: cannot continue
                notdone = 0;
 
-            if (plist)
-               delete[] plist;
+            delete[] plist;
          } else {
             // We are successfully done
             resp = 1;
             notdone = 0;
          }
          // Cleanup
-         SafeDelete(xrsp);
+         SafeDel(xrsp);
       } else {
          // We failed but we are done with this attempt
          resp = 0;
@@ -1321,7 +1318,7 @@ XrdSecProtocol *XrdProofConn::Authenticate(char *plist, int plsiz)
          reqhdr.header.dlen = (credentials) ? credentials->size : 0;
          char *credbuf = (credentials) ? credentials->buffer : 0;
          xrsp = SendReq(&reqhdr, credbuf, &srvans, "XrdProofConn::Authenticate");
-         SafeDelete(credentials);
+         SafeDel(credentials);
          status = (xrsp) ? xrsp->HeaderStatus() : kXR_error;
          dlen = (xrsp) ? xrsp->DataLen() : 0;
          TRACE(HDBG, "server reply: status: "<<status<<" dlen: "<<dlen);
@@ -1335,7 +1332,7 @@ XrdSecProtocol *XrdProofConn::Authenticate(char *plist, int plsiz)
             //
             // then get next part of the credentials
             credentials = protocol->getCredentials(secToken, &ei);
-            SafeDelete(secToken); // nb: srvans is released here
+            SafeDel(secToken); // nb: srvans is released here
             srvans = 0;
             if (!credentials) {
                TRACE(XERR, "cannot obtain credentials");
@@ -1349,7 +1346,7 @@ XrdSecProtocol *XrdProofConn::Authenticate(char *plist, int plsiz)
                // Server does not implement yet full cycling, so we are
                // allowed to try the handshake only for one protocol; we
                // cleanup the message and fail;
-               SafeDelete(xrsp);
+               SafeDel(xrsp);
                failed = 1;
                break;
             } else {
@@ -1365,7 +1362,7 @@ XrdSecProtocol *XrdProofConn::Authenticate(char *plist, int plsiz)
             }
          }
          // Cleanup message
-         SafeDelete(xrsp);
+         SafeDel(xrsp);
       }
 
       // If we are done
diff --git a/proof/proofd/src/XrdProofGroup.cxx b/proof/proofd/src/XrdProofGroup.cxx
index 8814e04..08a679a 100644
--- a/proof/proofd/src/XrdProofGroup.cxx
+++ b/proof/proofd/src/XrdProofGroup.cxx
@@ -1,4 +1,4 @@
-// @(#)root/proofd:$Id: XrdProofGroup.cxx 44085 2012-05-03 10:21:07Z ganis $
+// @(#)root/proofd:$Id: XrdProofGroup.cxx 44412 2012-05-31 14:47:23Z ganis $
 // Author: Gerardo Ganis  June 2007
 
 /*************************************************************************
@@ -324,15 +324,20 @@ int XrdProofGroupMgr::Config(const char *fn)
    // Return the number of active groups or -1 in case of error.
    XPDLOC(GMGR, "GroupMgr::Config")
 
-   if (!fn || strlen(fn) <= 0) {
-      // This call is to reset existing info and remain with
-      // the 'default' group only
-      XrdSysMutexHelper mhp(fMutex);
-      // Reset existing info
-      fGroups.Purge();
-      // Create "default" group
-      fGroups.Add("default", new XrdProofGroup("default"));
-      return fGroups.Num();;
+   if ((!fn || strlen(fn) <= 0)) {
+      if (fCfgFile.fName != fn) {
+         // This call is to reset existing info and remain with
+         // the 'default' group only
+         XrdSysMutexHelper mhp(fMutex);
+         // Reset existing info
+         fGroups.Purge();
+         // Create "default" group
+         fGroups.Add("default", new XrdProofGroup("default"));
+         // Reset fCfgFile
+         fCfgFile.fName = "";
+         fCfgFile.fMtime = 0;
+      }
+      return fGroups.Num();
    }
 
    // Did the file changed ?
diff --git a/proof/proofd/src/XrdProofSched.cxx b/proof/proofd/src/XrdProofSched.cxx
index fce6c53..a0c1c97 100644
--- a/proof/proofd/src/XrdProofSched.cxx
+++ b/proof/proofd/src/XrdProofSched.cxx
@@ -1,4 +1,4 @@
-// @(#)root/proofd:$Id: XrdProofSched.cxx 41550 2011-10-24 15:30:04Z rdm $
+// @(#)root/proofd:$Id: XrdProofSched.cxx 44523 2012-06-04 15:17:29Z ganis $
 // Author: G. Ganis  September 2007
 
 /*************************************************************************
@@ -531,7 +531,7 @@ int XrdProofSched::GetWorkers(XrdProofdProofServ *xps,
    }
 
    // Make sure that something has been found
-   if (!acws || acws->size() <= 1) {
+   if (!acws || (acws && acws->size() <= 1)) {
       if (fUseFIFO) {
          // Enqueue the query/session
          // the returned list of workers was not filled
@@ -540,10 +540,11 @@ int XrdProofSched::GetWorkers(XrdProofdProofServ *xps,
          if (TRACING(REQ)) xps->DumpQueries();
          // Notify enqueing
          TRACE(REQ, "no workers currently available: session enqueued");
+         SafeDel(acwseff);
          return 2;
       } else {
          TRACE(XERR, "no worker available: do nothing");
-         if (acwseff) { delete acwseff; acwseff = 0; }
+         SafeDel(acwseff);
          return -1;
       }
    }
@@ -551,6 +552,7 @@ int XrdProofSched::GetWorkers(XrdProofdProofServ *xps,
    // If the session has already assigned workers just return
    if (xps->Workers()->Num() > 0) {
       // Current assignement is valid
+      SafeDel(acwseff);
       return 1;
    }
 
@@ -692,7 +694,8 @@ int XrdProofSched::Reschedule()
    // resume, assigning it workers and sending a resume message.
    // In this way there is not possibility of interference with other GetWorkers
    // return 0 in case of success and -1 in case of an error
-   XPDDOM(SCHED)
+
+   XPDLOC(SCHED, "Sched::Reschedule")
 
    if (fUseFIFO && TRACING(DBG)) DumpQueues("Reschedule");
 
@@ -700,6 +703,10 @@ int XrdProofSched::Reschedule()
       // Any advanced scheduling algorithms can be done here
 
       XrdProofdProofServ *xps = FirstSession();
+      if (!xps) {
+         TRACE(XERR, "got undefined session: protocol error!");
+         return -1;
+      }
       XrdOucString wrks;
       // Call GetWorkers in the manager to mark the assignment.
       XrdOucString qtag;
@@ -712,6 +719,7 @@ int XrdProofSched::Reschedule()
       }
       if (fMgr->GetWorkers(wrks, xps, qtag.c_str()) < 0 ) {
          // Something wrong
+         TRACE(XERR, "failure from GetWorkers: protocol error!");
          return -1;
       } else {
          // Send buffer
diff --git a/proof/proofd/src/XrdProofWorker.cxx b/proof/proofd/src/XrdProofWorker.cxx
index ec3abb4..1d52a12 100644
--- a/proof/proofd/src/XrdProofWorker.cxx
+++ b/proof/proofd/src/XrdProofWorker.cxx
@@ -1,4 +1,4 @@
-// @(#)root/proofd:$Id: XrdProofWorker.cxx 41550 2011-10-24 15:30:04Z rdm $
+// @(#)root/proofd:$Id: XrdProofWorker.cxx 44523 2012-06-04 15:17:29Z ganis $
 // Author: Gerardo Ganis  June 2007
 
 /*************************************************************************
@@ -53,7 +53,7 @@ XrdProofWorker::~XrdProofWorker()
 {
    // Destructor
 
-   SafeDelete(fMutex);
+   SafeDel(fMutex);
 }
 
 //______________________________________________________________________________
diff --git a/proof/proofd/src/XrdProofdAdmin.cxx b/proof/proofd/src/XrdProofdAdmin.cxx
index 857fee7..2a3ac90 100644
--- a/proof/proofd/src/XrdProofdAdmin.cxx
+++ b/proof/proofd/src/XrdProofdAdmin.cxx
@@ -1,4 +1,4 @@
-// @(#)root/proofd:$Id: XrdProofdAdmin.cxx 42858 2012-02-03 11:34:05Z ganis $
+// @(#)root/proofd:$Id: XrdProofdAdmin.cxx 44523 2012-06-04 15:17:29Z ganis $
 // Author: G. Ganis Feb 2008
 
 /*************************************************************************
@@ -543,6 +543,7 @@ int XrdProofdAdmin::SetGroupProperties(XrdProofdProtocol *p)
       TRACEP(p, XERR, "received group does not match the user's one");
       response->Send(kXR_InvalidRequest,
                      "SetGroupProperties: received group does not match the user's one");
+      SafeDelArray(grp);
       return 0;
    }
 
@@ -558,6 +559,7 @@ int XrdProofdAdmin::SetGroupProperties(XrdProofdProtocol *p)
          TRACEP(p, XERR, "problem sending message on the pipe");
          response->Send(kXR_ServerError,
                              "SetGroupProperties: problem sending message on the pipe");
+         SafeDelArray(grp);
          return 0;
       }
    }
@@ -565,6 +567,8 @@ int XrdProofdAdmin::SetGroupProperties(XrdProofdProtocol *p)
    // Notify
    TRACEP(p, REQ, "priority for group '"<< grp<<"' has been set to "<<priority);
 
+   SafeDelArray(grp);
+
    // Acknowledge user
    response->Send();
 
@@ -1250,7 +1254,7 @@ int XrdProofdAdmin::Exec(XrdProofdProtocol *p)
             }
          }
          // Cleanup answer
-         SafeDelete(xrsp);
+         SafeDel(xrsp);
       }
    }
 
@@ -1497,7 +1501,7 @@ int XrdProofdAdmin::ExecCmd(XrdProofdProtocol *p, XrdProofdResponse *r,
                // Fill the buffer and go
                char msg[256];
                int  islink = S_ISLNK(st.st_mode);
-               sprintf(msg, "%ld %ld %d %d %d %lld %ld %d", (long)st.st_dev,
+               snprintf(msg, 256, "%ld %ld %d %d %d %lld %ld %d", (long)st.st_dev,
                         (long)st.st_ino, st.st_mode, (int)(st.st_uid),
                         (int)(st.st_gid), (kXR_int64)st.st_size, st.st_mtime, islink);
                emsg = msg;
@@ -1582,7 +1586,7 @@ int XrdProofdAdmin::ExecCmd(XrdProofdProtocol *p, XrdProofdResponse *r,
                }
                // Close the pipe
                int rcpc = 0;
-               if (rc == 0 && (rcpc = pclose(fp)) == -1) {
+               if ((rcpc = pclose(fp)) == -1) {
                   emsg = "could not close the command pipe";
                   rc = 1;
                }
@@ -1823,52 +1827,53 @@ int XrdProofdAdmin::GetFile(XrdProofdProtocol *p)
          } else {
             // Send the size as OK message
             char sizmsg[64];
-            sprintf(sizmsg, "%lld", (kXR_int64) st.st_size);
+            snprintf(sizmsg, 64, "%lld", (kXR_int64) st.st_size);
             response->Send((const char *) &sizmsg[0]);
             TRACEP(p, XERR, "size is "<<sizmsg<<" bytes");
-         }
-         // Now we send the content
-         const int kMAXBUF = 16384;
-         char buf[kMAXBUF];
-         off_t pos = 0;
-         lseek(fd, pos, SEEK_SET);
-
-         while (rc == 0 && pos < st.st_size) {
-            off_t left = st.st_size - pos;
-            if (left > kMAXBUF) left = kMAXBUF;
-
-            int siz;
-            while ((siz = read(fd, &buf[0], left)) < 0 && errno == EINTR)
-               errno = 0;
-            if (siz < 0 || siz != left) {
-               emsg = "error reading from file: errno: ";
-               emsg += (int) errno;
-               rc = 1;
-               break;
-            }
 
-            int src = 0;
-            if ((src = response->Send(kXR_attn, kXPD_msg, (void *)&buf[0], left)) != 0) {
-               emsg = "error reading from file: errno: ";
-               emsg += src;
-               rc = 1;
-               break;
+            // Now we send the content
+            const int kMAXBUF = 16384;
+            char buf[kMAXBUF];
+            off_t pos = 0;
+            lseek(fd, pos, SEEK_SET);
+
+            while (rc == 0 && pos < st.st_size) {
+               off_t left = st.st_size - pos;
+               if (left > kMAXBUF) left = kMAXBUF;
+
+               int siz;
+               while ((siz = read(fd, &buf[0], left)) < 0 && errno == EINTR)
+                  errno = 0;
+               if (siz < 0 || siz != left) {
+                  emsg = "error reading from file: errno: ";
+                  emsg += (int) errno;
+                  rc = 1;
+                  break;
+               }
+
+               int src = 0;
+               if ((src = response->Send(kXR_attn, kXPD_msg, (void *)&buf[0], left)) != 0) {
+                  emsg = "error reading from file: errno: ";
+                  emsg += src;
+                  rc = 1;
+                  break;
+               }
+               // Re-position
+               pos += left;
+               // Reset the timeout
+               if (pp.Post(0, "") != 0) {
+                  rc = 1;
+                  break;
+               }
             }
-            // Re-position
-            pos += left;
-            // Reset the timeout
-            if (pp.Post(0, "") != 0) {
-               rc = 1;
-               break;
+            // Close the file
+            close(fd);
+            // Send error, if any
+            if (rc != 0) {
+               TRACEP(p, XERR, emsg);
+               response->Send(kXR_attn, kXPD_srvmsg, 0, (char *) emsg.c_str(), emsg.length());
             }
          }
-         // Close the file
-         close(fd);
-         // Send error, if any
-         if (rc != 0) {
-            TRACEP(p, XERR, emsg);
-            response->Send(kXR_attn, kXPD_srvmsg, 0, (char *) emsg.c_str(), emsg.length());
-         }
       }
 
       // Send error, if any
@@ -1983,7 +1988,7 @@ int XrdProofdAdmin::PutFile(XrdProofdProtocol *p)
          return 0;
       }
       // Extract size
-      sscanf(ssiz.c_str(), "%lld", &size);
+      size = atoll(ssiz.c_str());
       if (size < 0) {
          TRACEP(p, XERR, "cannot resolve size!");
          response->Send(kXR_InvalidRequest, "cannot resolve size!");
@@ -2419,7 +2424,7 @@ int XrdProofdAdmin::CpFile(XrdProofdProtocol *p)
             }
             // Close the pipe if not in error state (otherwise we may block here)
             int rcpc = 0;
-            if (rc == 0 && (rcpc = pclose(fp)) == -1) {
+            if ((rcpc = pclose(fp)) == -1) {
                emsg = "error while trying to close the command pipe";
                rc = 1;
             }
diff --git a/proof/proofd/src/XrdProofdAux.cxx b/proof/proofd/src/XrdProofdAux.cxx
index ec9da5f..3823766 100644
--- a/proof/proofd/src/XrdProofdAux.cxx
+++ b/proof/proofd/src/XrdProofdAux.cxx
@@ -1,4 +1,4 @@
-// @(#)root/proofd:$Id: XrdProofdAux.cxx 44103 2012-05-03 23:11:44Z ganis $
+// @(#)root/proofd:$Id: XrdProofdAux.cxx 44523 2012-06-04 15:17:29Z ganis $
 // Author: G. Ganis  June 2007
 
 /*************************************************************************
@@ -395,7 +395,7 @@ void XrdProofdAux::LogEmsgToFile(const char *flog, const char *emsg, const char
    if (flog && strlen(flog)) {
       // Open the file in write-only, append mode
       int logfd = open(flog, O_WRONLY|O_APPEND, 0644);
-      if (logfd > 0) {
+      if (logfd >= 0) {
          fcntl(logfd, F_SETFD, FD_CLOEXEC);
          // Attach a logger to the file
          XrdSysLogger logger(logfd, 0);
@@ -431,43 +431,18 @@ int XrdProofdAux::AssertDir(const char *path, XrdProofUI ui, bool changeown)
 
    if (!path || strlen(path) <= 0)
       return -1;
-
-   struct stat st;
-   if (stat(path,&st) != 0) {
-      if (errno == ENOENT) {
-
-         {  XrdSysPrivGuard pGuard((uid_t)0, (gid_t)0);
-            if (XpdBadPGuard(pGuard, ui.fUid) && changeown) {
-               TRACE(XERR, "could not get privileges to create dir");
-               return -1;
-            }
-
-            if (mkdir(path, 0755) != 0) {
-               TRACE(XERR, "unable to create dir: "<<path<<" (errno: "<<errno<<")");
-               return -1;
-            }
-         }
-         if (stat(path,&st) != 0) {
-            TRACE(XERR, "unable to stat dir: "<<path<<" (errno: "<<errno<<")");
-            return -1;
-         }
-      } else {
-         // Failure: stop
-         TRACE(XERR, "unable to stat dir: "<<path<<" (errno: "<<errno<<")");
-         return -1;
-      }
+   XrdSysPrivGuard pGuard((uid_t)0, (gid_t)0);
+   if (XpdBadPGuard(pGuard, ui.fUid) && changeown) {
+      TRACE(XERR, "could not get privileges to change ownership");
+      return -1;
    }
 
-   // Make sure the ownership is right
-   if (changeown &&
-      ((int) st.st_uid != ui.fUid || (int) st.st_gid != ui.fGid)) {
-
-      XrdSysPrivGuard pGuard((uid_t)0, (gid_t)0);
-      if (XpdBadPGuard(pGuard, ui.fUid)) {
-         TRACE(XERR, "could not get privileges to change ownership");
-         return -1;
-      }
+   if (mkdir(path, 0755) != 0 && (errno != EEXIST)) {
+      TRACE(XERR, "unable to create dir: "<<path<<" (errno: "<<errno<<")");
+      return -1;
+   }
 
+   if (changeown) {
       // Set ownership of the path to the client
       if (chown(path, ui.fUid, ui.fGid) == -1) {
          TRACE(XERR, "cannot set user ownership on path (errno: "<<errno<<")");
@@ -535,22 +510,9 @@ int XrdProofdAux::ChangeOwn(const char *path, XrdProofUI ui)
 
    if (!path || strlen(path) <= 0)
       return -1;
-
-   struct stat st;
-   if (stat(path,&st) != 0) {
-      // Failure: stop
-      TRACE(XERR, "unable to stat path: "<<path<<" (errno: "<<errno<<")");
-      return -1;
-   }
-
-   // If is a directory apply this on it
-   if (S_ISDIR(st.st_mode)) {
+   DIR *dir = opendir(path);
+   if (dir) {
       // Loop over the dir
-      DIR *dir = opendir(path);
-      if (!dir) {
-         TRACE(XERR,"cannot open "<<path<< "- errno: "<< errno);
-         return -1;
-      }
       XrdOucString proot(path);
       if (!proot.endswith('/')) proot += "/";
 
@@ -560,38 +522,22 @@ int XrdProofdAux::ChangeOwn(const char *path, XrdProofUI ui)
          XrdOucString fn(proot);
          fn += ent->d_name;
 
-         struct stat xst;
-         if (stat(fn.c_str(),&xst) == 0) {
-            // If is a directory apply this on it
-            if (S_ISDIR(xst.st_mode)) {
-               if (XrdProofdAux::ChangeOwn(fn.c_str(), ui) != 0) {
-                  TRACE(XERR, "problems changing recursively ownership of: "<<fn);
-                  closedir(dir);
-                  return -1;
-               }
-            } else {
-               // Get the privileges, if needed
-               XrdSysPrivGuard pGuard((uid_t)0, (gid_t)0);
-               if (XpdBadPGuard(pGuard, ui.fUid)) {
-                  TRACE(XERR, "could not get privileges to change ownership");
-                  closedir(dir);
-                  return -1;
-               }
-               // Set ownership of the path to the client
-               if (chown(fn.c_str(), ui.fUid, ui.fGid) == -1) {
-                  closedir(dir);
-                  TRACE(XERR, "cannot set user ownership on path (errno: "<<errno<<")");
-                  return -1;
-               }
-            }
-         } else {
-            TRACE(XERR, "unable to stat dir: "<<fn<<" (errno: "<<errno<<")");
+         // Apply recursively
+         if (XrdProofdAux::ChangeOwn(fn.c_str(), ui) != 0) {
+            TRACE(XERR, "problems changing recursively ownership of: "<<fn);
+            closedir(dir);
+            return -1;
          }
       }
       // Close the directory
       closedir(dir);
 
-   } else if (((int) st.st_uid != ui.fUid) || ((int) st.st_gid != ui.fGid)) {
+   } else {
+      // If it was a directory and opening failed, we fail
+      if (errno != 0 && (errno != ENOTDIR)) {
+         TRACE(XERR,"cannot open "<<path<< "- errno: "<< errno);
+         return -1;
+      }
       // Get the privileges, if needed
       XrdSysPrivGuard pGuard((uid_t)0, (gid_t)0);
       if (XpdBadPGuard(pGuard, ui.fUid)) {
@@ -604,7 +550,6 @@ int XrdProofdAux::ChangeOwn(const char *path, XrdProofUI ui)
          return -1;
       }
    }
-
    // We are done
    return 0;
 }
@@ -1157,8 +1102,10 @@ int XrdProofdAux::GetIDFromPath(const char *path, XrdOucString &emsg)
    FILE *fid = fopen(path, "r");
    if (fid) {
       char line[64];
-      if (fgets(line, sizeof(line), fid))
-         sscanf(line, "%d", &id);
+      if (fgets(line, sizeof(line), fid)) {
+         if (line[strlen(line)-1] == '\n') line[strlen(line)-1] = 0;
+         id = atoi(line);
+      }
       fclose(fid);
    } else if (errno != ENOENT) {
       XPDFORM(emsg, "GetIDFromPath: error reading id from: %s (errno: %d)",
@@ -1485,18 +1432,10 @@ int XrdProofdAux::MvDir(const char *oldpath, const char *newpath)
       if (S_ISDIR(st.st_mode)) {
          mode_t srcmode = st.st_mode;
          // Create dest sub-dir
-         if (stat(dstentry.c_str(), &st) == 0) {
-            if (!S_ISDIR(st.st_mode)) {
-               TRACE(XERR, "destination path already exists and is not a directory: "<<dstentry);
-               rc = -ENOTDIR;
-               break;
-            }
-         } else {
-            if (mkdir(dstentry.c_str(), srcmode) != 0) {
-               TRACE(XERR, "cannot create entry "<<dstentry<<" ; error: "<<errno);
-               rc = -errno;
-               break;
-            }
+         if (mkdir(dstentry.c_str(), srcmode) != 0 && (errno != EEXIST)) {
+            TRACE(XERR, "cannot create entry "<<dstentry<<" ; error: "<<errno);
+            rc = -errno;
+            break;
          }
          if ((rc = XrdProofdAux::MvDir(srcentry.c_str(), dstentry.c_str())) != 0) {
             TRACE(XERR, "problems moving "<<srcentry<<" to "<<dstentry<<"; error: "<<-rc);
@@ -1584,7 +1523,7 @@ int XrdProofdAux::ReadMsg(int fd, XrdOucString &msg)
             msg += buf;
          }
          // Update counters
-         len -= nr;
+         len = (nr >= len) ? 0 : len - nr;
       } while (nr > 0 && len > 0);
 
       TRACE(HDBG,fd<<": buf: "<<buf);
@@ -1640,7 +1579,8 @@ int XrdProofdAux::ParsePidPath(const char *path,
       }
    }
 
-   TRACE(HDBG,"path: "<<path<<" --> before: '"<<before<<"', pid: "<<pid<<", after: '"<<after<<"'");
+   TRACE(HDBG,"path: "<<(path ? path : "<nul>")<<" --> before: '"<<before
+                      <<"', pid: "<<pid<<", after: '"<<after<<"'");
 
    // Done
    return pid;
@@ -2321,19 +2261,19 @@ void XrdProofdAux::Form(XrdOucString &s, const char *fmt,
          }
       } else if (s[k+1] == 'd') {
          if (nii < ni) {
-            sprintf(si,"%d", ii[nii++]);
+            snprintf(si, 32, "%d", ii[nii++]);
             s.replace("%d", si, k, k + 1);
             replaced = 1;
          }
       } else if (s[k+1] == 'u') {
          if (nui < nu) {
-            sprintf(si,"%u", ui);
+            snprintf(si, 32, "%u", ui);
             s.replace("%u", si, k, k + 1);
             replaced = 1;
          }
       } else if (s[k+1] == 'p') {
          if (npp < np) {
-            sprintf(sp,"%p", pp[npp++]);
+            snprintf(sp, 32, "%p", pp[npp++]);
             s.replace("%p", sp, k, k + 1);
             replaced = 1;
          }
diff --git a/proof/proofd/src/XrdProofdClient.cxx b/proof/proofd/src/XrdProofdClient.cxx
index 645a6ca..5bbe9f1 100644
--- a/proof/proofd/src/XrdProofdClient.cxx
+++ b/proof/proofd/src/XrdProofdClient.cxx
@@ -1,4 +1,4 @@
-// @(#)root/proofd:$Id: XrdProofdClient.cxx 44103 2012-05-03 23:11:44Z ganis $
+// @(#)root/proofd:$Id: XrdProofdClient.cxx 44523 2012-06-04 15:17:29Z ganis $
 // Author: G. Ganis  June 2007
 
 /*************************************************************************
@@ -64,7 +64,7 @@ XrdProofdClient::XrdProofdClient(XrdProofUI ui, bool master, bool changeown,
    // We must have a valid sandbox
    if (fSandbox.IsValid()) fIsValid = 1;
    
-   // The session launcher (we may have a plugin here, on day ...)
+   // The session launcher (we may have a plugin here, one day ...)
    fLauncher = new XrdProofdLauncher(this);
 }
 
@@ -73,6 +73,7 @@ XrdProofdClient::~XrdProofdClient()
 {
    // Destructor
 
+   SafeDel(fLauncher);
 }
 
 //__________________________________________________________________________
@@ -266,8 +267,10 @@ XrdProofdProofServ *XrdProofdClient::GetServObj(int id)
          xps = fProofServs[id];
       }
    }
-   xps->SetID(id);
-   xps->SetValid();
+   if (xps) {
+      xps->SetID(id);
+      xps->SetValid();
+   }
    if (TRACING(DBG)) {
       {  XrdSysMutexHelper mh(fMutex);
          if (fIsValid) {
diff --git a/proof/proofd/src/XrdProofdClientMgr.cxx b/proof/proofd/src/XrdProofdClientMgr.cxx
index f6a5b5e..e1a3093 100644
--- a/proof/proofd/src/XrdProofdClientMgr.cxx
+++ b/proof/proofd/src/XrdProofdClientMgr.cxx
@@ -1,4 +1,4 @@
-// @(#)root/proofd:$Id: XrdProofdClientMgr.cxx 44103 2012-05-03 23:11:44Z ganis $
+// @(#)root/proofd:$Id: XrdProofdClientMgr.cxx 44523 2012-06-04 15:17:29Z ganis $
 // Author: G. Ganis Jan 2008
 
 /*************************************************************************
@@ -595,7 +595,7 @@ int XrdProofdClientMgr::CheckClient(XrdProofdProtocol *p,
          c->SetROOT(fMgr->ROOTMgr()->DefaultVersion());
       if (c->IsValid()) {
          // Set the group, if any
-         c->SetGroup(g->Name());
+         c->SetGroup(gname.c_str());
       }
    } else {
       emsg = "unable to instantiate object for client ";
@@ -901,8 +901,9 @@ int XrdProofdClientMgr::ParsePreviousClients(XrdOucString &emsg)
                   if (!fd) {
                      TRACE(XERR, "unable to create path: " <<discpath);
                      xrm = 1;
+                  } else {
+                     fclose(fd);
                   }
-                  fclose(fd);
                   if (!xrm)
                      fNDisconnected++;
                }
@@ -1113,8 +1114,9 @@ int XrdProofdClientMgr::Auth(XrdProofdProtocol *p)
       p->AuthProt()->Entity.tident = p->Link()->ID;
    }
    // Set the wanted login name
-   char *u = new char[strlen("XrdSecLOGINUSER=")+strlen(p->UserIn())+2];
-   sprintf(u, "XrdSecLOGINUSER=%s", p->UserIn());
+   size_t len = strlen("XrdSecLOGINUSER=")+strlen(p->UserIn())+2;
+   char *u = new char[len];
+   snprintf(u, len, "XrdSecLOGINUSER=%s", p->UserIn());
    putenv(u);
 
    // Now try to authenticate the client using the current protocol
@@ -1229,6 +1231,7 @@ XrdSecService *XrdProofdClientMgr::LoadSecurity()
    XrdSecServLoader_t ep = 0;
    if (!(ep = (XrdSecServLoader_t)dlsym(lh, "XrdSecgetService"))) {
       TRACE(XERR, dlerror() <<" finding XrdSecgetService() in "<<seclib);
+      dlclose(lh);
       return 0;
    }
 
@@ -1237,6 +1240,7 @@ XrdSecService *XrdProofdClientMgr::LoadSecurity()
    int nd = 0;
    char *rcfn = FilterSecConfig(nd);
    if (!rcfn) {
+      dlclose(lh);
       if (nd == 0) {
          // No directives to be processed
          TRACE(XERR, "no security directives: strong authentication disabled");
@@ -1251,6 +1255,9 @@ XrdSecService *XrdProofdClientMgr::LoadSecurity()
    XrdSecService *cia = 0;
    if (!(cia = (*ep)((fEDest ? fEDest->logger() : (XrdSysLogger *)0), rcfn))) {
       TRACE(XERR, "Unable to create security service object via " << seclib);
+      dlclose(lh);
+      unlink(rcfn);
+      delete[] rcfn;
       return 0;
    }
    // Notify
@@ -1259,6 +1266,7 @@ XrdSecService *XrdProofdClientMgr::LoadSecurity()
    // Unlink the temporary file and cleanup its path
    unlink(rcfn);
    delete[] rcfn;
+   dlclose(lh);
 
    // All done
    return cia;
@@ -1305,15 +1313,19 @@ char *XrdProofdClientMgr::FilterSecConfig(int &nd)
          nd++;
          // Create the output file, if not yet done
          if (!rcfn) {
-            rcfn = new char[strlen(fMgr->TMPdir()) + strlen("/xpdcfn_XXXXXX") + 2];
-            sprintf(rcfn, "%s/xpdcfn_XXXXXX", fMgr->TMPdir());
+            size_t len = strlen(fMgr->TMPdir()) + strlen("/xpdcfn_XXXXXX") + 2;
+            rcfn = new char[len];
+            snprintf(rcfn, len, "%s/xpdcfn_XXXXXX", fMgr->TMPdir());
+            mode_t oldum = umask(022);
             if ((fd = mkstemp(rcfn)) < 0) {
                delete[] rcfn;
                nd = (errno > 0) ? -errno : -1;
                fclose(fin);
                rcfn = 0;
+               oldum = umask(oldum);
                return rcfn;
             }
+            oldum = umask(oldum);
          }
          XrdOucString slin = lin;
          // Strip the prefix "xpd."
@@ -1327,7 +1339,7 @@ char *XrdProofdClientMgr::FilterSecConfig(int &nd)
 
    // Close files
    fclose(fin);
-   close(fd);
+   if (fd >= 0) close(fd);
 
    return rcfn;
 }
diff --git a/proof/proofd/src/XrdProofdConfig.cxx b/proof/proofd/src/XrdProofdConfig.cxx
index 7d816ff..9030df3 100644
--- a/proof/proofd/src/XrdProofdConfig.cxx
+++ b/proof/proofd/src/XrdProofdConfig.cxx
@@ -1,4 +1,4 @@
-// @(#)root/proofd:$Id: XrdProofdConfig.cxx 41550 2011-10-24 15:30:04Z rdm $
+// @(#)root/proofd:$Id: XrdProofdConfig.cxx 44412 2012-05-31 14:47:23Z ganis $
 // Author: G. Ganis Jan 2008
 
 /*************************************************************************
@@ -156,6 +156,7 @@ int XrdProofdConfig::ParseFile(bool rcf)
          }
       }
    }
+   close(cfgFD);
 
    // Done
    return 0;
diff --git a/proof/proofd/src/XrdProofdLauncher.cxx b/proof/proofd/src/XrdProofdLauncher.cxx
index e33c095..781f16f 100644
--- a/proof/proofd/src/XrdProofdLauncher.cxx
+++ b/proof/proofd/src/XrdProofdLauncher.cxx
@@ -1,4 +1,4 @@
-// @(#)root/proofd:$Id: XrdProofdLauncher.cxx 39178 2011-05-13 10:30:30Z ganis $
+// @(#)root/proofd:$Id: XrdProofdLauncher.cxx 44523 2012-06-04 15:17:29Z ganis $
 // Author: G. Ganis March 2011
 
 /*************************************************************************
@@ -73,11 +73,12 @@ XrdNetPeer *XrdProofdLauncher::Launch(ProofdLaunch_t *in, int &pid)
    
    // Create server socket to get the call back
    rpdunixsrv *unixsrv = new rpdunixsrv(xps->UNIXSockPath());
-   if (!unixsrv || !unixsrv->isvalid(0)) {
+   if (!unixsrv || (unixsrv && !unixsrv->isvalid(0))) {
       XPDFORM(emsg, "could not start unix server connection on path '%s' (errno: %d)",
                     xps->UNIXSockPath(), (int)errno);
       TRACE(XERR, emsg);      
       XrdProofdAux::LogEmsgToFile(in->fErrLog.c_str(), emsg.c_str(), npfx.c_str());
+      SafeDel(unixsrv);
       return peer;
    }
 
@@ -92,6 +93,7 @@ XrdNetPeer *XrdProofdLauncher::Launch(ProofdLaunch_t *in, int &pid)
       XPDFORM(emsg, "failure from 'system' (errno: %d)", (int)errno);
       TRACE(XERR, emsg);
       XrdProofdAux::LogEmsgToFile(in->fErrLog.c_str(), emsg.c_str(), npfx.c_str());
+      SafeDel(unixsrv);
       return peer;
    }
 
@@ -99,12 +101,14 @@ XrdNetPeer *XrdProofdLauncher::Launch(ProofdLaunch_t *in, int &pid)
    // Accept a connection from the second server
    int err;
    rpdunix *uconn = unixsrv->accept(in->fIntWait, &err);
-   if (!uconn || !uconn->isvalid(0)) {
+   if (!uconn || (uconn && !uconn->isvalid(0))) {
       XPDFORM(emsg, "failure accepting callback (errno: %d)", -err);
       TRACE(XERR, emsg);
       XrdProofdAux::LogEmsgToFile(in->fErrLog.c_str(), emsg.c_str(), npfx.c_str());
+      SafeDel(uconn);
       return peer;
    }
+   SafeDel(unixsrv);
    TRACE(ALL, "proofserv connected!");
 
    //   
diff --git a/proof/proofd/src/XrdProofdManager.cxx b/proof/proofd/src/XrdProofdManager.cxx
index 6aa7afd..925b95a 100644
--- a/proof/proofd/src/XrdProofdManager.cxx
+++ b/proof/proofd/src/XrdProofdManager.cxx
@@ -1,4 +1,4 @@
-// @(#)root/proofd:$Id: XrdProofdManager.cxx 44029 2012-04-30 13:19:15Z ganis $
+// @(#)root/proofd:$Id: XrdProofdManager.cxx 44523 2012-06-04 15:17:29Z ganis $
 // Author: G. Ganis June 2007
 
 /*************************************************************************
@@ -473,6 +473,7 @@ XrdProofSched *XrdProofdManager::LoadScheduler()
                }
             }
          }
+         close(cfgFD);
       } else {
          XPDFORM(m, "failure opening config file; errno: %d", errno);
          TRACE(XERR, m);
@@ -504,12 +505,14 @@ XrdProofSched *XrdProofdManager::LoadScheduler()
       // Get the scheduler object
       if (!(sched = (*ep)(cfn, this, fGroupsMgr, cfn, fEDest))) {
          TRACE(XERR, "unable to create scheduler object from " << lib);
+         delete h;
          return (XrdProofSched *)0;
       }
+      delete h;
    }
    // Check result
    if (!(sched->IsValid())) {
-      TRACE(XERR, " unable to instantiate the " << sched->Name() << " scheduler using " << cfn);
+      TRACE(XERR, " unable to instantiate the " << sched->Name() << " scheduler using " << (cfn ? cfn : "<nul>"));
       delete sched;
       return (XrdProofSched *)0;
    }
@@ -1106,12 +1109,13 @@ bool XrdProofdManager::ValidateLocalDataSetSrc(XrdOucString &url, bool &local)
             // Assert the file with lock file path
             if (goodsrc) {
                fnpath.replace("/dataset.list", "/lock.location");
-               if (access(fnpath.c_str(), F_OK) != 0) {
-                  FILE *flck = fopen(fnpath.c_str(), "w");
-                  if (!flck) {
-                     TRACE(XERR, "Cannot open file '" << fnpath << "' with the lock file path; errno: " << errno);
-                  } else {
-                     // Write the default lock file path
+               FILE *flck = fopen(fnpath.c_str(), "a");
+               if (!flck) {
+                  TRACE(XERR, "Cannot open file '" << fnpath << "' with the lock file path; errno: " << errno);
+               } else {
+                  off_t ofs = lseek(fileno(flck), 0, SEEK_CUR);
+                  if (ofs == 0) {
+                     // New file: write the default lock file path
                      XrdOucString fnlock(url);
                      fnlock.replace("/", "%");
                      fnlock.replace(":", "%");
@@ -1122,7 +1126,10 @@ bool XrdProofdManager::ValidateLocalDataSetSrc(XrdOucString &url, bool &local)
                      if (XrdProofdAux::ChangeOwn(fnpath.c_str(), ui) != 0) {
                         TRACE(XERR, "Problems asserting ownership of " << fnpath);
                      }
+                  } else if (ofs != (off_t)(-1)) {
+                     TRACE(XERR, "Problems getting current position on file '" << fnpath << "'; errno: " << errno);
                   }
+                  fclose(flck);
                }
             }
             // Make sure that everybody can modify the file for updates
@@ -1634,6 +1641,8 @@ int XrdProofdManager::DoDirectiveDataSetSrc(char *val, XrdOucStream *cfg, bool)
          rw = 1;
       } else if (!strncmp(nxt, "url:", 4)) {
          url = nxt + 4;
+         XrdClientUrlInfo u(url);
+         if (u.Proto == "" && u.HostWPort == "") local = 1;
       } else if (!strncmp(nxt, "opt:", 4)) {
          opts = nxt + 4;
       }
diff --git a/proof/proofd/src/XrdProofdNetMgr.cxx b/proof/proofd/src/XrdProofdNetMgr.cxx
index 6848580..247feeb 100644
--- a/proof/proofd/src/XrdProofdNetMgr.cxx
+++ b/proof/proofd/src/XrdProofdNetMgr.cxx
@@ -1,4 +1,4 @@
-// @(#)root/proofd:$Id: XrdProofdNetMgr.cxx 44029 2012-04-30 13:19:15Z ganis $
+// @(#)root/proofd:$Id: XrdProofdNetMgr.cxx 44523 2012-06-04 15:17:29Z ganis $
 // Author: G. Ganis  Jan 2008
 
 /*************************************************************************
@@ -1156,12 +1156,16 @@ int XrdProofdNetMgr::ReadBuffer(XrdProofdProtocol *p)
                TRACEP(p, DBG, emsg);
             }
             response->Send();
+            SafeDelArray(pattern);
+            SafeFree(filen);
             return 0;
          } else {
             XPDFORM(emsg, "could not read buffer from %s %s",
                     (local) ? "local file " : "remote file ", file);
             TRACEP(p, XERR, emsg);
             response->Send(kXR_InvalidRequest, emsg.c_str());
+            SafeDelArray(pattern);
+            SafeFree(filen);
             return 0;
          }
       } else {
@@ -1387,14 +1391,14 @@ char *XrdProofdNetMgr::ReadBufferLocal(const char *path,
       lcmd = strlen(pat) + strlen(file) + 20;
       cmd = new char[lcmd];
       if (opt == 2) {
-         sprintf(cmd, "grep -v %s %s", pat, file);
+         snprintf(cmd, lcmd, "grep -v %s %s", pat, file);
       } else {
-         sprintf(cmd, "grep %s %s", pat, file);
+         snprintf(cmd, lcmd, "grep %s %s", pat, file);
       }
    } else {
       lcmd = strlen(file) + 10;
       cmd = new char[lcmd];
-      sprintf(cmd, "cat %s", file);
+      snprintf(cmd, lcmd, "cat %s", file);
    }
    TRACE(DBG, "cmd: " << cmd);
 
@@ -1555,7 +1559,7 @@ char *XrdProofdNetMgr::ReadLogPaths(const char *url, const char *msg, int isess)
       reqhdr.proof.int1 = kQueryLogPaths;
       reqhdr.proof.int2 = isess;
       reqhdr.proof.sid = -1;
-      reqhdr.header.dlen = strlen(msg);
+      reqhdr.header.dlen = msg ? strlen(msg) : 0;
       const void *btmp = (const void *) msg;
       char **vout = &buf;
       // Send over
diff --git a/proof/proofd/src/XrdProofdPriorityMgr.cxx b/proof/proofd/src/XrdProofdPriorityMgr.cxx
index f513b69..23051d3 100644
--- a/proof/proofd/src/XrdProofdPriorityMgr.cxx
+++ b/proof/proofd/src/XrdProofdPriorityMgr.cxx
@@ -1,4 +1,4 @@
-// @(#)root/proofd:$Id: XrdProofdPriorityMgr.cxx 44103 2012-05-03 23:11:44Z ganis $
+// @(#)root/proofd:$Id: XrdProofdPriorityMgr.cxx 44498 2012-06-04 09:06:32Z ganis $
 // Author: G. Ganis Feb 2008
 
 /*************************************************************************
@@ -451,11 +451,11 @@ int XrdProofdPriorityMgr::DoDirectiveSchedOpt(char *val, XrdOucStream *cfg, bool
       if (o.beginswith("min:")) {
          // The overall inflating factor
          o.replace("min:","");
-         sscanf(o.c_str(), "%d", &pmin);
+         pmin = o.atoi();
       } else if (o.beginswith("max:")) {
          // The overall inflating factor
          o.replace("max:","");
-         sscanf(o.c_str(), "%d", &pmax);
+         pmax = o.atoi();
       } else {
          if (o == "central")
             opt = kXPD_sched_central;
diff --git a/proof/proofd/src/XrdProofdProofServ.cxx b/proof/proofd/src/XrdProofdProofServ.cxx
index abab68e..43a6e67 100644
--- a/proof/proofd/src/XrdProofdProofServ.cxx
+++ b/proof/proofd/src/XrdProofdProofServ.cxx
@@ -1,4 +1,4 @@
-// @(#)root/proofd:$Id: XrdProofdProofServ.cxx 41313 2011-10-10 15:44:18Z ganis $
+// @(#)root/proofd:$Id: XrdProofdProofServ.cxx 44523 2012-06-04 15:17:29Z ganis $
 // Author: Gerardo Ganis  12/12/2005
 
 /*************************************************************************
@@ -21,13 +21,6 @@
 // Tracing utils
 #include "XrdProofdTrace.h"
 
-#ifndef SafeDelete
-#define SafeDelete(x) { if (x) { delete x; x = 0; } }
-#endif
-#ifndef SafeDelArray
-#define SafeDelArray(x) { if (x) { delete[] x; x = 0; } }
-#endif
-
 //__________________________________________________________________________
 XrdProofdProofServ::XrdProofdProofServ()
 {
@@ -71,8 +64,8 @@ XrdProofdProofServ::~XrdProofdProofServ()
 {
    // Destructor
 
-   SafeDelete(fStartMsg);
-   SafeDelete(fPingSem);
+   SafeDel(fStartMsg);
+   SafeDel(fPingSem);
 
    std::vector<XrdClientID *>::iterator i;
    for (i = fClients.begin(); i != fClients.end(); i++)
@@ -89,7 +82,7 @@ XrdProofdProofServ::~XrdProofdProofServ()
    // Remove the associated UNIX socket path
    unlink(fUNIXSockPath.c_str());
 
-   SafeDelete(fMutex);
+   SafeDel(fMutex);
 }
 
 //__________________________________________________________________________
@@ -183,8 +176,13 @@ int XrdProofdProofServ::Reset(const char *msg, int type)
    XPDFORM(fn, "%s.status", fAdminPath.c_str());
    FILE *fpid = fopen(fn.c_str(), "r");
    if (fpid) {
-      if (fscanf(fpid, "%d", &st) <= 0)
+      char line[64];
+      if (fgets(line, sizeof(line), fpid)) {
+         if (line[strlen(line)-1] == '\n') line[strlen(line)-1] = 0;
+         st = atoi(line);
+      } else {
          TRACE(XERR,"problems reading from file "<<fn);
+      }
       fclose(fpid);
    }
    TRACE(DBG,"file: "<<fn<<", st:"<<st);
@@ -212,8 +210,8 @@ void XrdProofdProofServ::Reset()
    fResponse = 0;
    fProtocol = 0;
    fParent = 0;
-   SafeDelete(fStartMsg);
-   SafeDelete(fPingSem);
+   SafeDel(fStartMsg);
+   SafeDel(fPingSem);
    fSrvPID = -1;
    fID = -1;
    fIsShutdown = false;
@@ -249,7 +247,7 @@ void XrdProofdProofServ::DeleteUNIXSock()
 {
    // Delete the current UNIX socket
 
-   SafeDelete(fUNIXSock);
+   SafeDel(fUNIXSock);
    unlink(fUNIXSockPath.c_str());
    fUNIXSockPath = "";
 }
@@ -565,8 +563,10 @@ int XrdProofdProofServ::BroadcastPriority(int priority)
    if (!fResponse || fResponse->Send(kXR_attn, kXPD_priority, buf, len) != 0) {
       // Failure
       TRACE(XERR,"problems telling proofserv");
+      SafeDelArray(buf);
       return -1;
    }
+   SafeDelArray(buf);
    TRACE(DBG, "priority "<<priority<<" sent over");
    // Done
    return 0;
@@ -682,25 +682,22 @@ int XrdProofdProofServ::CreateUNIXSock(XrdSysError *edest)
    fUNIXSock = new XrdNet(edest);
 
    // Make sure the admin path exists
-   struct stat st;
-   if (fAdminPath.length() > 0 &&
-       stat(fAdminPath.c_str(), &st) != 0 && (errno == ENOENT)) {;
-      FILE *fadm = fopen(fAdminPath.c_str(), "w");
-      fclose(fadm);
+   if (fAdminPath.length() > 0) {
+      FILE *fadm = fopen(fAdminPath.c_str(), "a");
+      if (fadm) {
+         fclose(fadm);
+      } else {
+         TRACE(XERR, "unable to open / create admin path "<< fAdminPath << "; errno = "<<errno);
+         return -1;
+      }
    }
 
    // Check the path
-   bool rm = 0, ok = 0;
-   if (stat(fUNIXSockPath.c_str(), &st) == 0 || (errno != ENOENT)) rm = 1;
-   if (rm  && unlink(fUNIXSockPath.c_str()) != 0) {
-      if (!S_ISSOCK(st.st_mode)) {
-         TRACE(XERR, "non-socket path exists: unable to delete it: " <<fUNIXSockPath);
-         return -1;
-      } else {
-         XPDPRT("WARNING: socket path exists: unable to delete it:"
-                " try to use it anyway " <<fUNIXSockPath);
-         ok = 1;
-      }
+   bool ok = 0;
+   if (unlink(fUNIXSockPath.c_str()) != 0 && (errno != ENOENT)) {
+      XPDPRT("WARNING: path exists: unable to delete it:"
+               " try to use it anyway " <<fUNIXSockPath);
+      ok = 1;
    }
 
    // Create the path
@@ -752,32 +749,24 @@ int XrdProofdProofServ::SetAdminPath(const char *a, bool assert, bool setown)
    // If we are not asked to assert the file we are done
    if (!assert) return 0;
 
-   // The session file
-   struct stat st;
-   if (stat(a, &st) != 0 && errno == ENOENT) {
-      // Create the file
-      FILE *fpid = fopen(a, "w");
-      if (fpid) {
-         fclose(fpid);
-      } else {
-         TRACE(XERR, "unable to open / create admin path "<< fAdminPath << "; errno = "<<errno);
-         return -1;
-      }
+   // Check if the session file exists
+   FILE *fpid = fopen(a, "a");
+   if (fpid) {
+      fclose(fpid);
+   } else {
+      TRACE(XERR, "unable to open / create admin path "<< fAdminPath << "; errno = "<<errno);
+      return -1;
    }
 
-   // The status file
+   // Check if the status file exists
    XrdOucString fn;
    XPDFORM(fn, "%s.status", a);
-   if (stat(fn.c_str(), &st) != 0 && errno == ENOENT) {
-      // Create the file
-      FILE *fpid = fopen(fn.c_str(), "w");
-      if (fpid) {
-         fprintf(fpid, "%d", fStatus);
-         fclose(fpid);
-      } else {
-         TRACE(XERR, "unable to open / create status path "<< fn << "; errno = "<<errno);
-         return -1;
-      }
+   if ((fpid = fopen(fn.c_str(), "a"))) {
+      fprintf(fpid, "%d", fStatus);
+      fclose(fpid);
+   } else {
+      TRACE(XERR, "unable to open / create status path "<< fn << "; errno = "<<errno);
+      return -1;
    }
    
    if (setown) {
@@ -791,13 +780,6 @@ int XrdProofdProofServ::SetAdminPath(const char *a, bool assert, bool setown)
          TRACE(XERR, "unable to give ownership of the status file "<< fn << " to user; errno = "<<errno);
          return -1;
       }
-      // Check
-      if (stat(fn.c_str(), &st) != 0) {
-         TRACE(XERR, "creation/assertion of the status path "<< fn << " failed; errno = "<<errno);
-         return -1;
-      } else {
-         TRACE(ALL, "creation/assertion of the status path "<< fn << " was successful!");
-      }
    }
 
    // Done
@@ -995,7 +977,7 @@ void XrdProofdProofServ::SendClusterInfo(int nsess, int nacti)
       // Failure
       TRACE(XERR,"problems sending proofserv");
    }
-
+   SafeDelArray(buf);
 }
 
 //__________________________________________________________________________
diff --git a/proof/proofd/src/XrdProofdProofServMgr.cxx b/proof/proofd/src/XrdProofdProofServMgr.cxx
index 3f1627b..689c6b7 100644
--- a/proof/proofd/src/XrdProofdProofServMgr.cxx
+++ b/proof/proofd/src/XrdProofdProofServMgr.cxx
@@ -1,4 +1,4 @@
-// @(#)root/proofd:$Id: XrdProofdProofServMgr.cxx 44103 2012-05-03 23:11:44Z ganis $
+// @(#)root/proofd:$Id: XrdProofdProofServMgr.cxx 44523 2012-06-04 15:17:29Z ganis $
 // Author: G. Ganis Jan 2008
 
 /*************************************************************************
@@ -442,8 +442,8 @@ int XrdProofdProofServMgr::AddSession(XrdProofdProtocol *p, XrdProofdProofServ *
    TRACE(REQ, "adding new active session ...");
 
    // Check inputs
-   if (!s || !p || !p->Client()) {
-      TRACE(XERR,"invalid inputs: "<<p<<", "<<s<<", "<<p->Client());
+   if (!s || !p->Client()) {
+      TRACE(XERR,"invalid inputs: "<<(s ? "" : "s, ") <<", "<< (p->Client() ? "" : "p->Client()"));
       return -1;
    }
    XrdProofdClient *c = p->Client();
@@ -470,7 +470,7 @@ bool XrdProofdProofServMgr::IsSessionSocket(const char *fpid)
 
    // Check inputs
    if (!fpid || strlen(fpid) <= 0) {
-      TRACE(XERR, "invalid input: "<<fpid);
+      TRACE(XERR, "invalid input: "<<(fpid ? fpid : "<nul>"));
       return 0;
    }
 
@@ -508,7 +508,7 @@ int XrdProofdProofServMgr::MvSession(const char *fpid)
 
    // Check inputs
    if (!fpid || strlen(fpid) <= 0) {
-      TRACE(XERR, "invalid input: "<<fpid);
+      TRACE(XERR, "invalid input: "<<(fpid ? fpid : "<nul>"));
       return -1;
    }
 
@@ -560,7 +560,7 @@ int XrdProofdProofServMgr::RmSession(const char *fpid)
 
    // Check inputs
    if (!fpid || strlen(fpid) <= 0) {
-      TRACE(XERR, "invalid input: "<<fpid);
+      TRACE(XERR, "invalid input: "<< (fpid ? fpid : "<nul>"));
       return -1;
    }
 
@@ -583,11 +583,11 @@ int XrdProofdProofServMgr::TouchSession(const char *fpid, const char *fpath)
    // Update the access time for the session pid file to the current time
    XPDLOC(SMGR, "ProofServMgr::TouchSession")
 
-   TRACE(REQ, "touching "<<fpid<<", "<<fpath<<" ...");
+   TRACE(REQ, "touching "<<(fpid ? fpid : "<nul>")<<", "<<(fpath ? fpath : "<nul>")<<" ...");
 
    // Check inputs
    if (!fpid || strlen(fpid) <= 0) {
-      TRACE(XERR, "invalid input: "<<fpid);
+      TRACE(XERR, "invalid input: "<<(fpid ? fpid : "<nul>"));
       return -1;
    }
 
@@ -617,7 +617,7 @@ int XrdProofdProofServMgr::VerifySession(const char *fpid,
 
    // Check inputs
    if (!fpid || strlen(fpid) <= 0) {
-      TRACE(XERR, "invalid input: "<<fpid);
+      TRACE(XERR, "invalid input: "<<(fpid ? fpid : "<nul>"));
       return -1;
    }
 
@@ -675,7 +675,7 @@ int XrdProofdProofServMgr::DeleteFromSessions(const char *fpid)
 
    // Check inputs
    if (!fpid || strlen(fpid) <= 0) {
-      TRACE(XERR, "invalid input: "<<fpid);
+      TRACE(XERR, "invalid input: "<<(fpid ? fpid : "<nul>"));
       return -1;
    }
 
@@ -861,7 +861,7 @@ bool XrdProofdProofServMgr::IsClientRecovering(const char *usr, const char *grp,
    XPDLOC(SMGR, "ProofServMgr::IsClientRecovering")
 
    if (!usr || !grp) {
-      TRACE(XERR, "invalid inputs: usr: "<<usr<<", grp:"<<grp<<" ...");
+      TRACE(XERR, "invalid inputs: usr: "<<(usr ? usr : "")<<", grp:"<<(grp ? grp : "")<<" ...");
       return false;
    }
 
@@ -1654,7 +1654,7 @@ XrdProofdProofServ *XrdProofdProofServMgr::PrepareProofServ(XrdProofdProtocol *p
    TRACEP(p, REQ, msg);
    if (p->ConnType() == kXPD_ClientMaster) {
       // Notify the client if using a version different from the default one
-      if (p->Client()->ROOT() != fMgr->ROOTMgr()->DefaultVersion()) {
+      if (fMgr && p->Client()->ROOT() != fMgr->ROOTMgr()->DefaultVersion()) {
          XPDFORM(msg, "++++ Using NON-default ROOT version: %s ++++\n", xps->ROOT()->Export());
          r->Send(kXR_attn, kXPD_srvmsg, (char *) msg.c_str(), msg.length());
       }
@@ -1905,20 +1905,29 @@ int XrdProofdProofServMgr::CreateFork(XrdProofdProtocol *p)
 
       char *argvv[6] = {0};
 
+      // We set to the user environment
+      if (!fMgr) {
+         emsg = "XrdProofdManager instance undefined!";
+         TRACE(XERR, emsg);
+         if (fcp.Post(0, emsg.c_str()) != 0)
+            TRACE(XERR, "cannot write to internal pipe; errno: "<<errno);
+         exit(1);
+      }
       char *sxpd = 0;
-      if (fMgr && fMgr->AdminPath()) {
+      if (fMgr->AdminPath()) {
          // We add our admin path to be able to identify processes coming from us
-         sxpd = new char[strlen(fMgr->AdminPath()) + strlen("xpdpath:") + 1];
-         sprintf(sxpd, "xpdpath:%s", fMgr->AdminPath());
+         size_t len = strlen(fMgr->AdminPath()) + strlen("xpdpath:") + 1;
+         sxpd = new char[len];
+         snprintf(sxpd, len, "xpdpath:%s", fMgr->AdminPath());
       } else {
          // We add our PID to be able to identify processes coming from us
          sxpd = new char[10];
-         sprintf(sxpd, "%d", getppid());
+         snprintf(sxpd, 10, "%d", getppid());
       }
 
       // Log level
       char slog[10] = {0};
-      sprintf(slog, "%d", loglevel);
+      snprintf(slog, 10, "%d", loglevel);
 
       // start server
       argvv[0] = (char *) xps->ROOT()->PrgmSrv();
@@ -2489,6 +2498,7 @@ int XrdProofdProofServMgr::Create(XrdProofdProtocol *p)
       emsg += errlog;
       emsg.insert(npfx, 0);
       response->Send(kXP_ServerError, emsg.c_str());
+      SafeDel(peersrv);
       return 0;
    }
 
@@ -2531,9 +2541,10 @@ int XrdProofdProofServMgr::Create(XrdProofdProtocol *p)
       TRACEP(p, XERR, emsg.c_str());
       emsg.insert(npfx, 0);
       response->Send(kXR_attn, kXPD_errmsg, (char *) emsg.c_str(), emsg.length());
+      SafeDel(peersrv);
       return 0;
    }
-   SafeDelete(peersrv);
+   SafeDel(peersrv);
    // Set the group, if any
    xps->SetGroup(p->Client()->Group());
 
@@ -2633,11 +2644,11 @@ int XrdProofdProofServMgr::ResolveSession(const char *fpid)
    // Handle a request to recover a session after stop&restart
    XPDLOC(SMGR, "ProofServMgr::ResolveSession")
 
-   TRACE(REQ,  "resolving "<< fpid<<" ...");
+   TRACE(REQ,  "resolving "<< (fpid ? fpid : "<nul>")<<" ...");
 
    // Check inputs
    if (!fpid || strlen(fpid)<= 0 || !(fMgr->ClientMgr()) || !fRecoverClients) {
-      TRACE(XERR, "invalid inputs: "<<fpid<<", "<<fMgr->ClientMgr()<<
+      TRACE(XERR, "invalid inputs: "<<(fpid ? fpid : "<nul>")<<", "<<fMgr->ClientMgr()<<
                   ", "<<fRecoverClients);
       return -1;
    }
@@ -3007,26 +3018,30 @@ int XrdProofdProofServMgr::SetProofServEnvOld(XrdProofdProtocol *p, void *input)
    XrdOucString udir = p->Client()->Sandbox()->Dir();
    TRACE(DBG, "working dir for "<<p->Client()->User()<<" is: "<<udir);
 
-   ev = new char[strlen("ROOTPROOFSESSDIR=") + in->fWrkDir.length() + 2];
-   sprintf(ev, "ROOTPROOFSESSDIR=%s", in->fWrkDir.c_str());
+   size_t len = strlen("ROOTPROOFSESSDIR=") + in->fWrkDir.length() + 2;
+   ev = new char[len];
+   snprintf(ev, len, "ROOTPROOFSESSDIR=%s", in->fWrkDir.c_str());
    putenv(ev);
    TRACE(DBG, ev);
 
    // Log level
-   ev = new char[strlen("ROOTPROOFLOGLEVEL=")+5];
-   sprintf(ev, "ROOTPROOFLOGLEVEL=%d", in->fLogLevel);
+   len = strlen("ROOTPROOFLOGLEVEL=") + 5;
+   ev = new char[len];
+   snprintf(ev, len, "ROOTPROOFLOGLEVEL=%d", in->fLogLevel);
    putenv(ev);
    TRACE(DBG, ev);
 
    // Ordinal number
-   ev = new char[strlen("ROOTPROOFORDINAL=")+strlen(xps->Ordinal())+2];
-   sprintf(ev, "ROOTPROOFORDINAL=%s", xps->Ordinal());
+   len = strlen("ROOTPROOFORDINAL=")+strlen(xps->Ordinal()) + 2;
+   ev = new char[len];
+   snprintf(ev, len, "ROOTPROOFORDINAL=%s", xps->Ordinal());
    putenv(ev);
    TRACE(DBG, ev);
 
    // ROOT Version tag if not the default one
-   ev = new char[strlen("ROOTVERSIONTAG=")+strlen(p->Client()->ROOT()->Tag())+2];
-   sprintf(ev, "ROOTVERSIONTAG=%s", p->Client()->ROOT()->Tag());
+   len = strlen("ROOTVERSIONTAG=")+strlen(p->Client()->ROOT()->Tag())+2;
+   ev = new char[len];
+   snprintf(ev, len, "ROOTVERSIONTAG=%s", p->Client()->ROOT()->Tag());
    putenv(ev);
    TRACE(DBG, ev);
 
@@ -3067,11 +3082,11 @@ int XrdProofdProofServMgr::SetProofServEnvOld(XrdProofdProtocol *p, void *input)
       // The credential buffer, if any
       XrdSecCredentials *creds = p->AuthProt()->getCredentials();
       if (creds) {
-         int lev = strlen("XrdSecCREDS=")+creds->size;
-         ev = new char[lev+1];
+         len = strlen("XrdSecCREDS=")+creds->size;
+         ev = new char[len + 1];
          strcpy(ev, "XrdSecCREDS=");
-         memcpy(ev+strlen("XrdSecCREDS="), creds->buffer, creds->size);
-         ev[lev] = 0;
+         memcpy(ev + strlen("XrdSecCREDS="), creds->buffer, creds->size);
+         ev[len] = 0;
          putenv(ev);
          TRACE(DBG, "XrdSecCREDS set");
 
@@ -3082,8 +3097,9 @@ int XrdProofdProofServMgr::SetProofServEnvOld(XrdProofdProtocol *p, void *input)
             // Make sure the directory exists
             if (!XrdProofdAux::AssertDir(credsdir.c_str(), p->Client()->UI(), fMgr->ChangeOwn())) {
                if (SaveAFSkey(creds, credsdir.c_str(), p->Client()->UI()) == 0) {
-                  ev = new char[strlen("ROOTPROOFAFSCREDS=")+credsdir.length()+strlen("/.afs")+2];
-                  sprintf(ev, "ROOTPROOFAFSCREDS=%s/.afs", credsdir.c_str());
+                  len = strlen("ROOTPROOFAFSCREDS=")+credsdir.length()+strlen("/.afs")+2;
+                  ev = new char[len];
+                  snprintf(ev, len, "ROOTPROOFAFSCREDS=%s/.afs", credsdir.c_str());
                   putenv(ev);
                   fprintf(fenv, "ROOTPROOFAFSCREDS has been set\n");
                   TRACE(DBG, ev);
@@ -3209,8 +3225,9 @@ int XrdProofdProofServMgr::SetProofServEnvOld(XrdProofdProtocol *p, void *input)
          }
       }
       // The list of names, ','-separated
-      ev = new char[strlen("PROOF_ALLVARS=") + namelist.length() + 2];
-      sprintf(ev, "PROOF_ALLVARS=%s", namelist.c_str());
+      len = strlen("PROOF_ALLVARS=") + namelist.length() + 2;
+      ev = new char[len];
+      snprintf(ev, len, "PROOF_ALLVARS=%s", namelist.c_str());
       putenv(ev);
       fprintf(fenv, "%s\n", ev);
       TRACE(DBG, ev);
@@ -3242,6 +3259,7 @@ int XrdProofdProofServMgr::SetProofServEnv(XrdProofdManager *mgr, XrdROOT *r)
    XPDLOC(SMGR, "ProofServMgr::SetProofServEnv")
 
    char *ev = 0;
+   size_t len = 0;
 
    TRACE(REQ,  "ROOT dir: "<< (r ? r->Dir() : "*** undef ***"));
 
@@ -3249,34 +3267,40 @@ int XrdProofdProofServMgr::SetProofServEnv(XrdProofdManager *mgr, XrdROOT *r)
       char *libdir = (char *) r->LibDir();
       char *ldpath = 0;
       if (mgr->BareLibPath() && strlen(mgr->BareLibPath()) > 0) {
-         ldpath = new char[32 + strlen(libdir) + strlen(mgr->BareLibPath())];
-         sprintf(ldpath, "%s=%s:%s", XPD_LIBPATH, libdir, mgr->BareLibPath());
+         len = 32 + strlen(libdir) + strlen(mgr->BareLibPath());
+         ldpath = new char[len];
+         snprintf(ldpath, len, "%s=%s:%s", XPD_LIBPATH, libdir, mgr->BareLibPath());
       } else {
-         ldpath = new char[32 + strlen(libdir)];
-         sprintf(ldpath, "%s=%s", XPD_LIBPATH, libdir);
+         len = 32 + strlen(libdir);
+         ldpath = new char[len];
+         snprintf(ldpath, len, "%s=%s", XPD_LIBPATH, libdir);
       }
       putenv(ldpath);
       // Set ROOTSYS
       char *rootsys = (char *) r->Dir();
-      ev = new char[15 + strlen(rootsys)];
-      sprintf(ev, "ROOTSYS=%s", rootsys);
+      len = 15 + strlen(rootsys);
+      ev = new char[len];
+      snprintf(ev, len, "ROOTSYS=%s", rootsys);
       putenv(ev);
 
       // Set bin directory
       char *bindir = (char *) r->BinDir();
-      ev = new char[15 + strlen(bindir)];
-      sprintf(ev, "ROOTBINDIR=%s", bindir);
+      len = 15 + strlen(bindir);
+      ev = new char[len];
+      snprintf(ev, len, "ROOTBINDIR=%s", bindir);
       putenv(ev);
 
       // Set conf dir
       char *confdir = (char *) r->DataDir();
-      ev = new char[20 + strlen(confdir)];
-      sprintf(ev, "ROOTCONFDIR=%s", confdir);
+      len = 20 + strlen(confdir);
+      ev = new char[len];
+      snprintf(ev, len, "ROOTCONFDIR=%s", confdir);
       putenv(ev);
 
       // Set TMPDIR
-      ev = new char[20 + strlen(mgr->TMPdir())];
-      sprintf(ev, "TMPDIR=%s", mgr->TMPdir());
+      len = 20 + strlen(mgr->TMPdir());
+      ev = new char[len];
+      snprintf(ev, len, "TMPDIR=%s", mgr->TMPdir());
       putenv(ev);
 
       // Done
@@ -3508,6 +3532,7 @@ int XrdProofdProofServMgr::CreateProofServEnvFile(XrdProofdProtocol *p, void *in
    TRACE(REQ, "environment file: "<< envfn);
 
    char *ev = 0;
+   size_t len = 0;
    // Forwarded sec credentials, if any
    if (p->AuthProt()) {
 
@@ -3533,9 +3558,9 @@ int XrdProofdProofServMgr::CreateProofServEnvFile(XrdProofdProtocol *p, void *in
       // The credential buffer, if any
       XrdSecCredentials *creds = p->AuthProt()->getCredentials();
       if (creds) {
-         int lev = strlen("XrdSecCREDS=")+creds->size;
+         int lev = strlen("XrdSecCREDS=") + creds->size;
          ev = new char[lev+1];
-         strcpy(ev, "XrdSecCREDS=");
+         strncpy(ev, "XrdSecCREDS=", lev);
          memcpy(ev+strlen("XrdSecCREDS="), creds->buffer, creds->size);
          ev[lev] = 0;
          PutEnv(ev, in->fOld);
@@ -3548,8 +3573,9 @@ int XrdProofdProofServMgr::CreateProofServEnvFile(XrdProofdProtocol *p, void *in
             // Make sure the directory exists
             if (!XrdProofdAux::AssertDir(credsdir.c_str(), p->Client()->UI(), fMgr->ChangeOwn())) {
                if (SaveAFSkey(creds, credsdir.c_str(), p->Client()->UI()) == 0) {
-                  ev = new char[strlen("ROOTPROOFAFSCREDS=")+credsdir.length()+strlen("/.afs")+2];
-                  sprintf(ev, "ROOTPROOFAFSCREDS=%s/.afs", credsdir.c_str());
+                  len = strlen("ROOTPROOFAFSCREDS=")+credsdir.length()+strlen("/.afs")+2;
+                  ev = new char[len];
+                  snprintf(ev, len, "ROOTPROOFAFSCREDS=%s/.afs", credsdir.c_str());
                   fprintf(fenv, "ROOTPROOFAFSCREDS has been set\n");
                   TRACE(DBG, ev);
                   PutEnv(ev, in->fOld);
@@ -3579,24 +3605,27 @@ int XrdProofdProofServMgr::CreateProofServEnvFile(XrdProofdProtocol *p, void *in
 
    // RC file
    if (in->fOld) {
-      ev = new char[strlen("ROOTRCFILE=")+strlen(rcfn)+2];
-      sprintf(ev, "ROOTRCFILE=%s", rcfn);
+      len = strlen("ROOTRCFILE=") + strlen(rcfn) + 2;
+      ev = new char[len];
+      snprintf(ev, len, "ROOTRCFILE=%s", rcfn);
       fprintf(fenv, "%s\n", ev);
       TRACE(DBG, ev);
       PutEnv(ev, in->fOld);
    }
 
    // ROOT version tag (needed in building packages)
-   ev = new char[strlen("ROOTVERSIONTAG=")+strlen(p->Client()->ROOT()->Tag())+2];
-   sprintf(ev, "ROOTVERSIONTAG=%s", p->Client()->ROOT()->Tag());
+   len = strlen("ROOTVERSIONTAG=") + strlen(p->Client()->ROOT()->Tag()) + 2;
+   ev = new char[len];
+   snprintf(ev, len, "ROOTVERSIONTAG=%s", p->Client()->ROOT()->Tag());
    fprintf(fenv, "%s\n", ev);
    TRACE(DBG, ev);
    PutEnv(ev, in->fOld);
 
    // Log file in the log dir
    if (in->fOld) {
-      ev = new char[strlen("ROOTPROOFLOGFILE=") + in->fLogFile.length() + 2];
-      sprintf(ev, "ROOTPROOFLOGFILE=%s", in->fLogFile.c_str());
+      len = strlen("ROOTPROOFLOGFILE=") + in->fLogFile.length() + 2;
+      ev = new char[len];
+      snprintf(ev, len, "ROOTPROOFLOGFILE=%s", in->fLogFile.c_str());
       fprintf(fenv, "%s\n", ev);
       xps->SetFileout(in->fLogFile.c_str());
       TRACE(DBG, ev);
@@ -3610,16 +3639,18 @@ int XrdProofdProofServMgr::CreateProofServEnvFile(XrdProofdProtocol *p, void *in
    } else { 
       XPDFORM(locdatasrv, "rootd://%s:%d", fMgr->Host(), fMgr->Port());
    }
-   ev = new char[strlen("LOCALDATASERVER=") + locdatasrv.length() + 2];
-   sprintf(ev, "LOCALDATASERVER=%s", locdatasrv.c_str());
+   len = strlen("LOCALDATASERVER=") + locdatasrv.length() + 2;
+   ev = new char[len];
+   snprintf(ev, len, "LOCALDATASERVER=%s", locdatasrv.c_str());
    fprintf(fenv, "%s\n", ev);
    TRACE(DBG, ev);
    PutEnv(ev, in->fOld);
 
    // Xrootd config file
    if (CfgFile()) {
-      ev = new char[strlen("XRDCF=")+strlen(CfgFile())+2];
-      sprintf(ev, "XRDCF=%s", CfgFile());
+      len = strlen("XRDCF=") + strlen(CfgFile()) + 2;
+      ev = new char[len];
+      snprintf(ev, len, "XRDCF=%s", CfgFile());
       fprintf(fenv, "%s\n", ev);
       TRACE(DBG, ev);
       PutEnv(ev, in->fOld);
@@ -3682,8 +3713,9 @@ int XrdProofdProofServMgr::CreateProofServEnvFile(XrdProofdProtocol *p, void *in
          }
       }
       // The list of names, ','-separated
-      ev = new char[strlen("PROOF_ALLVARS=") + namelist.length() + 2];
-      sprintf(ev, "PROOF_ALLVARS=%s", namelist.c_str());
+      len = strlen("PROOF_ALLVARS=") + namelist.length() + 2;
+      ev = new char[len];
+      snprintf(ev, len, "PROOF_ALLVARS=%s", namelist.c_str());
       fprintf(fenv, "%s\n", ev);
       TRACE(DBG, ev);
       PutEnv(ev, in->fOld);
@@ -4317,7 +4349,7 @@ int XrdProofdProofServMgr::CleanupProofServ(bool all, const char *usr)
 
    // Our parent ID as a string
    char cpid[10];
-   sprintf(cpid, "%d", getpid());
+   snprintf(cpid, 10, "%d", getpid());
 
    // Run it ...
    XrdOucString pids = ":";
@@ -4432,7 +4464,9 @@ int XrdProofdProofServMgr::SetUserOwnerships(XrdProofdProtocol *p,
             for (int i = 0; i < 3; i++) {
                if (XrdProofdAux::AssertDir(dus[i].c_str(), p->Client()->UI(), fMgr->ChangeOwn()) == 0) {
                   if (XrdProofdAux::ChangeMod(dus[i].c_str(), mode) != 0) {
+                     std::ios_base::fmtflags oflags = std::cerr.flags();
                      TRACE(XERR, "problems setting permissions "<< oct << mode<<" on: "<<dus[i]);
+                     std::cerr.flags(oflags);
                   }
                } else {
                   TRACE(XERR, "problems asserting: "<<dus[i]);
@@ -4479,15 +4513,18 @@ int XrdProofdProofServMgr::SetUserEnvironment(XrdProofdProtocol *p)
       return -1;
    }
 
+   size_t len = 0;
    // set HOME env
-   char *h = new char[8 + strlen(p->Client()->Sandbox()->Dir())];
-   sprintf(h, "HOME=%s", p->Client()->Sandbox()->Dir());
+   len = 8 + strlen(p->Client()->Sandbox()->Dir());
+   char *h = new char[len];
+   snprintf(h, len, "HOME=%s", p->Client()->Sandbox()->Dir());
    putenv(h);
    TRACE(DBG, "set "<<h);
 
    // set USER env
-   char *u = new char[8 + strlen(p->Client()->User())];
-   sprintf(u, "USER=%s", p->Client()->User());
+   len = 8 + strlen(p->Client()->User());
+   char *u = new char[len];
+   snprintf(u, len, "USER=%s", p->Client()->User());
    putenv(u);
    TRACE(DBG, "set "<<u);
 
@@ -4563,33 +4600,25 @@ int XrdProofdProofServMgr::SaveAFSkey(XrdSecCredentials *c,
    // Save to file, if not existing already
    XrdOucString fn = dir;
    fn += "/.afs";
-
    int rc = 0;
-   struct stat st;
-   if (stat(fn.c_str(), &st) != 0 && errno == ENOENT) {
-
-      // Open the file, truncating if already existing
-      int fd = open(fn.c_str(), O_WRONLY | O_CREAT | O_TRUNC, 0600);
-      if (fd <= 0) {
-         TRACE(XERR, "problems creating file - errno: " << errno);
-         delete [] out;
-         return -1;
-      }
-      // Write out the key
-      int lkey = lout - 9;
-      if (XrdProofdAux::Write(fd, key, lkey) != lkey) {
-         TRACE(XERR, "problems writing to file - errno: " << errno);
-         rc = -1;
-      }
 
-      // Cleanup
-      delete [] out;
-      close(fd);
-   } else {
-      TRACE(XERR, "cannot stat existing file "<<fn<<" - errno: " << errno);
+   // Open the file, truncating if already existing
+   int fd = open(fn.c_str(), O_WRONLY | O_CREAT | O_TRUNC, 0600);
+   if (fd < 0) {
+      TRACE(XERR, "problems creating file - errno: " << errno);
       delete [] out;
       return -1;
    }
+   // Write out the key
+   int lkey = lout - 9;
+   if (XrdProofdAux::Write(fd, key, lkey) != lkey) {
+      TRACE(XERR, "problems writing to file - errno: " << errno);
+      rc = -1;
+   }
+
+   // Cleanup
+   delete [] out;
+   close(fd);
 
    // Make sure the file is owned by the user
    if (XrdProofdAux::ChangeOwn(fn.c_str(), ui) != 0) {
@@ -4894,7 +4923,7 @@ int XrdProofSessionInfo::SaveToFile(const char *file)
 
    // Check inputs
    if (!file || strlen(file) <= 0) {
-      TRACE(XERR,"invalid input: "<<file);
+      TRACE(XERR,"invalid input: "<< (file ? file : "<nul>"));
       return -1;
    }
 
@@ -4957,7 +4986,7 @@ int XrdProofSessionInfo::ReadFromFile(const char *file)
 
    // Check inputs
    if (!file || strlen(file) <= 0) {
-      TRACE(XERR,"invalid input: "<<file);
+      TRACE(XERR,"invalid input: "<<(file ? file : "<nul>"));
       return -1;
    }
 
@@ -4967,42 +4996,58 @@ int XrdProofSessionInfo::ReadFromFile(const char *file)
    FILE *fpid = fopen(file,"r");
    if (fpid) {
       char line[4096];
-      char v1[512], v2[512], v3[512];
+      XrdOucString sline, t;
+      int from  = 0;
       if (fgets(line, sizeof(line), fpid)) {
-         if (sscanf(line, "%s %s", v1, v2) == 2) {
-            fUser = v1;
-            fGroup = v2;
-         } else {
+         if (line[strlen(line)-1] == '\n') line[strlen(line)-1] = '\0';
+         sline = line;
+         if ((from = sline.tokenize(fUser, from, ' ')) == -1)
+            TRACE(XERR,"warning: corrupted line? "<<line);
+         if ((from = sline.tokenize(fGroup, from, ' ')) == -1)
             TRACE(XERR,"warning: corrupted line? "<<line);
-         }
       }
       if (fgets(line, sizeof(line), fpid)) {
-         int l = strlen(line);
-         if (line[l-1] == '\n') line[l-1] = '\0';
+         if (line[strlen(line)-1] == '\n') line[strlen(line)-1] = '\0';
          fUnixPath = line;
       }
       if (fgets(line, sizeof(line), fpid)) {
-         sscanf(line, "%d %d %d", &fPid, &fID, &fSrvType);
+         if (line[strlen(line)-1] == '\n') line[strlen(line)-1] = '\0';
+         sline = line;
+         from = 0;
+         if ((from = sline.tokenize(t, from, ' ')) == -1)
+            TRACE(XERR,"warning: corrupted line? "<<line);
+         fPid = t.atoi();
+         if ((from = sline.tokenize(t, from, ' ')) == -1)
+            TRACE(XERR,"warning: corrupted line? "<<line);
+         fID = t.atoi();
+         if ((from = sline.tokenize(t, from, ' ')) == -1)
+            TRACE(XERR,"warning: corrupted line? "<<line);
+         fSrvType = t.atoi();
       }
       if (fgets(line, sizeof(line), fpid)) {
-         int ns = 0;
-         if ((ns = sscanf(line, "%s %s %s", v1, v2, v3)) >= 2) {
-            fOrdinal = v1;
-            fTag = v2;
-            fAlias = (ns == 3) ? v3 : "";
-         } else {
+         if (line[strlen(line)-1] == '\n') line[strlen(line)-1] = '\0';
+         sline = line;
+         from = 0;
+         if ((from = sline.tokenize(fOrdinal, from, ' ')) == -1)
+            TRACE(XERR,"warning: corrupted line? "<<line);
+         if ((from = sline.tokenize(fTag, from, ' ')) == -1)
+            TRACE(XERR,"warning: corrupted line? "<<line);
+         if ((from = sline.tokenize(fAlias, from, ' ')) == -1)
             TRACE(XERR,"warning: corrupted line? "<<line);
-         }
       }
       if (fgets(line, sizeof(line), fpid)) {
+         if (line[strlen(line)-1] == '\n') line[strlen(line)-1] = '\0';
          fLogFile = line;
       }
       if (fgets(line, sizeof(line), fpid)) {
-         if (sscanf(line, "%d %s", &fSrvProtVers, v1) == 2) {
-            fROOTTag = v1;
-         } else {
+         if (line[strlen(line)-1] == '\n') line[strlen(line)-1] = '\0';
+         sline = line;
+         from = 0;
+         if ((from = sline.tokenize(t, from, ' ')) == -1)
+            TRACE(XERR,"warning: corrupted line? "<<line);
+         fSrvProtVers = t.atoi();
+         if ((from = sline.tokenize(fROOTTag, from, ' ')) == -1)
             TRACE(XERR,"warning: corrupted line? "<<line);
-         }
       }
       // All the remaining into fUserEnvs
       fUserEnvs = "";
@@ -5015,7 +5060,7 @@ int XrdProofSessionInfo::ReadFromFile(const char *file)
          while ((len = read(fileno(fpid), line, wanted)) < 0 &&
                 errno == EINTR)
             errno = 0;
-         if (len < wanted) {
+         if (len < 0 || len < wanted) {
             break;
          } else {
             line[len] = '\0';
@@ -5044,7 +5089,8 @@ int XrdProofSessionInfo::ReadFromFile(const char *file)
    if (fpid) {
       char line[64];
       if (fgets(line, sizeof(line), fpid)) {
-         sscanf(line, "%d", &fStatus);
+         if (line[strlen(line)-1] == '\n') line[strlen(line)-1] = 0;
+         fStatus = atoi(line);
       }
       // Done
       fclose(fpid);
diff --git a/proof/proofd/src/XrdProofdProtocol.cxx b/proof/proofd/src/XrdProofdProtocol.cxx
index 1db6023..a3b3666 100644
--- a/proof/proofd/src/XrdProofdProtocol.cxx
+++ b/proof/proofd/src/XrdProofdProtocol.cxx
@@ -1,4 +1,4 @@
-// @(#)root/proofd:$Id: XrdProofdProtocol.cxx 44103 2012-05-03 23:11:44Z ganis $
+// @(#)root/proofd:$Id: XrdProofdProtocol.cxx 44498 2012-06-04 09:06:32Z ganis $
 // Author: Gerardo Ganis  12/12/2005
 
 /*************************************************************************
@@ -190,20 +190,21 @@ int XrdgetProtocolPort(const char * /*pname*/, char * /*parms*/, XrdProtocol_Con
       // This function is called early on to determine the port we need to use. The
       // The default is ostensibly 1093 but can be overidden; which we allow.
 
-      XrdProofdProtCfg pcfg(pi->ConfigFN, pi->eDest);
-      // Init some relevant quantities for tracing
-      XrdProofdTrace = new XrdOucTrace(pi->eDest);
-      pcfg.Config(0);
-
       // Default XPD_DEF_PORT (1093)
       int port = XPD_DEF_PORT;
 
-      if (pcfg.fPort > 0) {
-         port = pcfg.fPort;
-      } else {
-         port = (pi && pi->Port > 0) ? pi->Port : XPD_DEF_PORT;
-      }
+      if (pi) {
+         XrdProofdProtCfg pcfg(pi->ConfigFN, pi->eDest);
+         // Init some relevant quantities for tracing
+         XrdProofdTrace = new XrdOucTrace(pi->eDest);
+         pcfg.Config(0);
 
+         if (pcfg.fPort > 0) {
+            port = pcfg.fPort;
+         } else {
+            port = (pi && pi->Port > 0) ? pi->Port : XPD_DEF_PORT;
+         }
+      }
       return port;
 }}
 
@@ -352,7 +353,7 @@ XrdProtocol *XrdProofdProtocol::Match(XrdLink *lp)
 
    // Bind the protocol to the link and return the protocol
    xp->fLink = lp;
-   strcpy(xp->fSecEntity.prot, "host");
+   snprintf(xp->fSecEntity.prot, XrdSecPROTOIDSIZE, "host");
    xp->fSecEntity.host = strdup((char *)lp->Host());
 
    // Dummy data used by 'proofd'
diff --git a/proof/proofd/src/XrdROOT.cxx b/proof/proofd/src/XrdROOT.cxx
index 6035eaa..4e2651d 100644
--- a/proof/proofd/src/XrdROOT.cxx
+++ b/proof/proofd/src/XrdROOT.cxx
@@ -1,4 +1,4 @@
-// @(#)root/proofd:$Id: XrdROOT.cxx 44103 2012-05-03 23:11:44Z ganis $
+// @(#)root/proofd:$Id: XrdROOT.cxx 44523 2012-06-04 15:17:29Z ganis $
 // Author: Gerardo Ganis  June 2007
 
 /*************************************************************************
@@ -191,7 +191,7 @@ int XrdROOT::ParseROOTVersionInfo()
 
    // Read the file
    char *pv = 0;
-   XrdOucString tkn;
+   XrdOucString tkn, sline;
    char line[1024];
    while (fgets(line, sizeof(line), fv)) {
       if (fRelease.length() <= 0 && (pv = (char *) strstr(line, "ROOT_RELEASE"))) {
@@ -201,13 +201,15 @@ int XrdROOT::ParseROOTVersionInfo()
          fRelease = pv;
          fRelease.replace("\"","");
       } else if ((pv = (char *) strstr(line, "ROOT_SVN_REVISION"))) {
-         if (line[strlen(line)-1] == '\n')
-            line[strlen(line)-1] = 0;
-         sscanf(pv, "ROOT_SVN_REVISION %d", &fSvnRevision);
+         if (line[strlen(line)-1] == '\n') line[strlen(line)-1] = 0;
+         pv += strlen("ROOT_SVN_REVISION");
+         while (pv[0] == ' ') pv++;
+         fSvnRevision = atoi(pv);
       } else if ((pv = (char *) strstr(line, "ROOT_VERSION_CODE"))) {
-         if (line[strlen(line)-1] == '\n')
-            line[strlen(line)-1] = 0;
-         sscanf(pv, "ROOT_VERSION_CODE %d", &fVersionCode);
+         if (line[strlen(line)-1] == '\n') line[strlen(line)-1] = 0;
+         pv += strlen("ROOT_VERSION_CODE");
+         while (pv[0] == ' ') pv++;
+         fVersionCode = atoi(pv);
       }
    }
 
@@ -262,11 +264,15 @@ int XrdROOT::ParseReleaseString(const char *release,
 
    if (!release || strlen(release) <= 0) return -1;
 
-   XrdOucString rel(release, 7);
-   rel.replace(".", " ");
-   rel.replace("/", " ");
-
-   sscanf(rel.c_str(), "%d %d %d", &maj, &min, &patch);
+   XrdOucString rel(release, 7), tkn;
+   int from = 0;
+   if ((from = rel.tokenize(tkn, from, '.')) == -1) return -1;
+   maj = atoi(tkn.c_str());
+   if ((from = rel.tokenize(tkn, from, '/')) == -1) return -1;
+   min = atoi(tkn.c_str());
+   if ((from = rel.tokenize(tkn, from, ' ')) == -1) return -1;
+   patch = atoi(tkn.c_str());
+   
    return 0;
 }
 
@@ -438,7 +444,7 @@ int XrdROOTMgr::DoDirectiveRootSys(char *val, XrdOucStream *cfg, bool)
          if ((*ori)->Match(rootc->Dir(), rootc->Tag())) {
             if ((*ori)->IsParked()) {
                (*ori)->SetValid();
-               SafeDelete(rootc);
+               SafeDel(rootc);
                break;
             }
          }
@@ -456,7 +462,7 @@ int XrdROOTMgr::DoDirectiveRootSys(char *val, XrdOucStream *cfg, bool)
             fROOT.push_back(rootc);
          } else {
             TRACE(XERR, "could not validate "<<rootc->Export());
-            SafeDelete(rootc);
+            SafeDel(rootc);
          }
       }
    }
@@ -522,8 +528,9 @@ int XrdROOTMgr::Validate(XrdROOT *r, XrdScheduler *sched)
          // Log to the session log file from now on
          fLogger->Bind(logfile.c_str());
          // Transfer the info to proofserv
-         char *ev = new char[strlen("ROOTPROOFLOGFILE=") + logfile.length() + 2];
-         sprintf(ev, "ROOTPROOFLOGFILE=%s", logfile.c_str());
+         size_t len = strlen("ROOTPROOFLOGFILE=") + logfile.length() + 2;
+         char *ev = new char[len];
+         snprintf(ev, len, "ROOTPROOFLOGFILE=%s", logfile.c_str());
          putenv(ev);
          if (debug && rootrc.length() > 0) {
             // Create .rootrc
@@ -533,8 +540,9 @@ int XrdROOTMgr::Validate(XrdROOT *r, XrdScheduler *sched)
                fclose(frc);
             }
             // Transfer the info to proofserv
-            ev = new char[strlen("ROOTRCFILE=") + rootrc.length() + 2];
-            sprintf(ev, "ROOTRCFILE=%s", rootrc.c_str());
+            len = strlen("ROOTRCFILE=") + rootrc.length() + 2;
+            ev = new char[len];
+            snprintf(ev, len, "ROOTRCFILE=%s", rootrc.c_str());
             putenv(ev);
          }
       }
@@ -562,7 +570,7 @@ int XrdROOTMgr::Validate(XrdROOT *r, XrdScheduler *sched)
 
       // Set Open socket
       char *ev = new char[25];
-      sprintf(ev, "ROOTOPENSOCK=%d", fp[1]);
+      snprintf(ev, 25, "ROOTOPENSOCK=%d", fp[1]);
       putenv(ev);
 
       // Prepare for execution: we need to acquire the identity of
diff --git a/proof/proofd/src/proofexecv.cxx b/proof/proofd/src/proofexecv.cxx
index 605bbe0..0b184f4 100644
--- a/proof/proofd/src/proofexecv.cxx
+++ b/proof/proofd/src/proofexecv.cxx
@@ -1,4 +1,4 @@
-// @(#)root/main:$Id: proofexecv.cxx 44085 2012-05-03 10:21:07Z ganis $
+// @(#)root/main:$Id: proofexecv.cxx 44523 2012-06-04 15:17:29Z ganis $
 // Author: Gerardo Ganis Mar 2011
 
 /*************************************************************************
@@ -161,8 +161,10 @@ void start_rootd(int argc, char **argv)
    
    // Force stdin/out to point to the socket FD (this will also bypass the
    // close on exec setting for the socket)
-   dup2(fd, STDIN_FILENO);
-   dup2(fd, STDOUT_FILENO);
+   if (dup2(fd, STDIN_FILENO) != 0)
+      Info("WARNING: failure duplicating STDIN (errno: %d)", errno);
+   if (dup2(fd, STDOUT_FILENO) != 0)
+      Info("WARNING: failure duplicating STDOUT (errno: %d)", errno);
 
    // Prepare execv
    int na = argc - 4;
@@ -182,6 +184,7 @@ void start_rootd(int argc, char **argv)
 
    // We should not be here!!!
    Info("ERROR: returned from execv: bad, bad sign !!!");
+   delete [] argvv;
    return;
 }
 
@@ -281,6 +284,7 @@ void start_ps(int argc, char **argv)
    rpdunix *uconn = new rpdunix(sockpath.c_str());
    if (!uconn || (uconn && !uconn->isvalid(0))) {
       Info("ERROR: failure calling back parent on '%s'", sockpath.c_str());
+      if (uconn) delete uconn;
       return;
    }
 
@@ -288,6 +292,7 @@ void start_ps(int argc, char **argv)
    int rcc = 0;
    if ((rcc = uconn->send((int) getpid())) != 0) {
       Info("ERROR: failure sending pid to parent (errno: %d)", -rcc);
+      delete uconn;
       return;
    }
    
@@ -295,6 +300,7 @@ void start_ps(int argc, char **argv)
    rpdmsg msg;
    if ((rcc = uconn->recv(msg)) != 0) {
       Info("ERROR: failure receiving admin path and executable from parent (errno: %d)", -rcc);
+      delete uconn;
       return;
    }
    int ppid;
@@ -309,6 +315,7 @@ void start_ps(int argc, char **argv)
    msg.reset();
    if ((rcc = uconn->recv(msg)) != 0) {
       Info("ERROR: failure receiving information about dataset and data dir(s) from parent (errno: %d)", -rcc);
+      delete uconn;
       return;
    }
    int euid;
@@ -323,6 +330,7 @@ void start_ps(int argc, char **argv)
    if (setownerships(euid, user, group, creds, datasetsrcs, datadir, ddiropts,
                      ord, stag) != 0) {
       Info("ERROR: problems setting relevant user ownerships");
+      delete uconn;
       return;
    }
 
@@ -330,29 +338,34 @@ void start_ps(int argc, char **argv)
    if (mvfile(tenvfile, envfile, uid, gid, 0644) != 0) {
       Info("ERROR: problems renaming '%s' to '%s' (errno: %d)",
            tenvfile.c_str(), envfile.c_str(), errno);
+      delete uconn;
       return;
    }
    // Move the rootrc file in the session directory
    if (mvfile(trcfile, rcfile, uid, gid, 0644) != 0) {
       Info("ERROR: problems renaming '%s' to '%s' (errno: %d)",
            trcfile.c_str(), rcfile.c_str(), errno);
+      delete uconn;
       return;
    }
 
    // Add missing information to the rc file
    if (completercfile(rcfile, userdir, stag, adminpath) != 0) {
       Info("ERROR: problems completing '%s'", rcfile.c_str());
+      delete uconn;
       return;
    }
    // Set the environment following the content of the env file
    if (setproofservenv(envfile, logfile, rcfile) != 0) {
       Info("ERROR: problems setting environment from '%s'", envfile.c_str());
+      delete uconn;
       return;
    }
 
    // Export the file descriptor
    if (exportsock(uconn) != 0) {
       Info("ERROR: problems exporting file descriptor");
+      delete uconn;
       return;
    }
    delete uconn;
@@ -383,12 +396,12 @@ void start_ps(int argc, char **argv)
    } else {
       // We add our PID to be able to identify processes coming from us
       sxpd = new char[10];
-      sprintf(sxpd, "%d", ppid);
+      snprintf(sxpd, 10, "%d", ppid);
    }
 
    // Log level
    char slog[10] = {0};
-   sprintf(slog, "%d", gDebug);
+   snprintf(slog, 10, "%d", gDebug);
 
    // Fill arguments
    argvv[0] = (char *) pspath.c_str();
@@ -428,14 +441,15 @@ int loginuser(const std::string &home, const std::string &user, uid_t uid, gid_t
    }
 
    // set HOME env
-   char *h = new char[8 + home.length()];
-   sprintf(h, "HOME=%s", home.c_str());
+   size_t len = home.length() + 8;
+   char *h = new char[len];
+   snprintf(h, len, "HOME=%s", home.c_str());
    putenv(h);
    if (gDebug > 0) Info("loginuser: set '%s'", h);
 
    // set USER env
-   char *u = new char[8 + user.length()];
-   sprintf(u, "USER=%s", user.c_str());
+   char *u = new char[len];
+   snprintf(u, len, "USER=%s", user.c_str());
    putenv(u);
    if (gDebug > 0) Info("loginuser: set '%s'", u);
 
@@ -476,32 +490,16 @@ int assertdir(const std::string &path, uid_t u, gid_t g, unsigned int mode)
       Info("assertdir: ERROR: could not get privileges (errno: %d)", errno);
       return -1;
    }
-   
-   struct stat st;
-   if (stat(path.c_str(), &st) != 0) {
-      if (errno == ENOENT) {
-         if (mkdir(path.c_str(), mode) != 0) {
-            Info("assertdir: ERROR: unable to create path: %s (errno: %d)", path.c_str(), errno);
-            return -1;
-         }
-         if (stat(path.c_str(), &st) != 0) {
-            Info("assertdir: ERROR: unable to stat path: %s after creation! (errno: %d)", path.c_str(), errno);
-            return -1;
-         }
-      } else {
-         // Failure: stop
-         Info("assertdir: ERROR: unable to stat path: %s (errno: %d)", path.c_str(), errno);
-         return -1;
-      }
-   }
 
-   // Make sure the ownership is right
-   if (st.st_uid != u || st.st_gid != g) {
-      // Set ownership of the path to the client
-      if (chown(path.c_str(), u, g) == -1) {
-         Info("assertdir: ERROR: unable to set ownership on path: %s (errno: %d)", path.c_str(), errno);
-         return -1;
-      }
+   // Make the directory: ignore failure if already existing ...
+   if (mkdir(path.c_str(), mode) != 0 && (errno != EEXIST)) {
+      Info("assertdir: ERROR: unable to create path: %s (errno: %d)", path.c_str(), errno);
+      return -1;
+   }
+   // Set ownership of the path to the client
+   if (chown(path.c_str(), u, g) == -1) {
+      Info("assertdir: ERROR: unable to set ownership on path: %s (errno: %d)", path.c_str(), errno);
+      return -1;
    }
 
    // We are done
@@ -529,35 +527,16 @@ int mvfile(const std::string &from, const std::string &to, uid_t u, gid_t g, uns
       return -1;
    }
 
-   // Check the final destination
-   struct stat st;
-   if (stat(to.c_str(), &st) != 0) {
-      if (errno == ENOENT) {
-         Info("mvfile: ERROR: operation apparently OK but final path '%s' does not exist(!)", to.c_str());
-         return -1;
-      } else {
-         // Failure: stop
-         Info("mvfile: ERROR: unable to stat final path: %s (errno: %d)", to.c_str(), errno);
-         return -1;
-      }
-   }
-
-   // Make sure the access mode is right
-   if (st.st_mode != mode) {
-      // Set ownership of the path to the client
-      if (chmod(to.c_str(), mode) == -1) {
-         Info("mvfile: ERROR: unable to set mode %o on path: %s (errno: %d)", mode, to.c_str(), errno);
-         return -1;
-      }
+   // Set ownership of the path to the client
+   if (chmod(to.c_str(), mode) == -1) {
+      Info("mvfile: ERROR: unable to set mode %o on path: %s (errno: %d)", mode, to.c_str(), errno);
+      return -1;
    }
 
    // Make sure the ownership is right
-   if (st.st_uid != u || st.st_gid != g) {
-      // Set ownership of the path to the client
-      if (chown(to.c_str(), u, g) == -1) {
-         Info("mvfile: ERROR: unable to set ownership on path: %s (errno: %d)", to.c_str(), errno);
-         return -1;
-      }
+   if (chown(to.c_str(), u, g) == -1) {
+      Info("mvfile: ERROR: unable to set ownership on path: %s (errno: %d)", to.c_str(), errno);
+      return -1;
    }
 
    // We are done
@@ -815,7 +794,6 @@ int setownerships(int euid, const std::string &us, const std::string &gr,
    return 0;
 }
 
-
 //_____________________________________________________________________________
 int changeown(const std::string &path, uid_t u, gid_t g)
 {
@@ -825,23 +803,10 @@ int changeown(const std::string &path, uid_t u, gid_t g)
 
    if (path.length() <= 0) return -1;
 
-   struct stat st;
-   if (stat(path.c_str(), &st) != 0) {
-      // Failure: stop
-      Info("changeown: ERROR: problems stat-ing '%s' (errno: %d)",
-           path.c_str(), (int)errno);
-      return -1;
-   }
-
    // If is a directory apply this on it
-   if (S_ISDIR(st.st_mode)) {
+   DIR *dir = opendir(path.c_str());
+   if (dir) {
       // Loop over the dir
-      DIR *dir = opendir(path.c_str());
-      if (!dir) {
-         Info("changeown: ERROR: problems opening '%s' (errno: %d)",
-              path.c_str(), (int)errno);
-         return -1;
-      }
       std::string proot(path);
       if (!(proot.rfind('/') !=  proot.length() - 1)) proot += "/";
 
@@ -851,42 +816,25 @@ int changeown(const std::string &path, uid_t u, gid_t g)
          std::string fn(proot);
          fn += ent->d_name;
 
-         struct stat xst;
-         if (stat(fn.c_str(), &xst) == 0) {
-            // If is a directory apply this on it
-            if (S_ISDIR(xst.st_mode)) {
-               if (changeown(fn.c_str(), u, g) != 0) {
-                  Info("changeown: ERROR: problems changing recursively ownership of '%s'",
-                       fn.c_str());
-                  closedir(dir);
-                  return -1;
-               }
-            } else {
-               // Get the privileges, if needed
-               rpdprivguard pguard((uid_t)0, (gid_t)0);
-               if (rpdbadpguard(pguard, u)) {
-                  Info("changeown: ERROR: could not get privileges (errno: %d)", errno);
-                  closedir(dir);
-                  return -1;
-               }
-               // Set ownership of the path to the client
-               if (chown(fn.c_str(), u, g) == -1) {
-                  Info("changeown: ERROR: cannot set user ownership on path '%s' (errno: %d)",
-                       fn.c_str(), errno);
-                  closedir(dir);
-                  return -1;
-               }
-            }
-         } else {
-            Info("changeown: ERROR: problems stat-ing '%s' (errno: %d)",
-                  fn.c_str(), (int)errno);
+         // Apply recursively
+         if (changeown(fn.c_str(), u, g) != 0) {
+            Info("changeown: ERROR: problems changing recursively ownership of '%s'",
+                  fn.c_str());
+            closedir(dir);
+            return -1;
          }
+
       }
       // Close the directory
       closedir(dir);
-
-   } else if ((st.st_uid != u) || (st.st_gid != g)) {
-      // Get the privileges, if needed
+   } else {
+      // If it was a directory and opening failed, we fail
+      if (errno != 0 && (errno != ENOTDIR)) {
+         Info("changeown: ERROR: problems opening '%s' (errno: %d)",
+              path.c_str(), (int)errno);
+         return -1;
+      }
+      // Else it may be a file ... get the privileges, if needed
       rpdprivguard pguard((uid_t)0, (gid_t)0);
       if (rpdbadpguard(pguard, u)) {
          Info("changeown: ERROR: could not get privileges (errno: %d)", errno);
diff --git a/proof/proofplayer/inc/TProofPlayer.h b/proof/proofplayer/inc/TProofPlayer.h
index 5c392ef..58d1f1f 100644
--- a/proof/proofplayer/inc/TProofPlayer.h
+++ b/proof/proofplayer/inc/TProofPlayer.h
@@ -1,4 +1,4 @@
-// @(#)root/proofplayer:$Id: TProofPlayer.h 44046 2012-05-01 11:34:04Z ganis $
+// @(#)root/proofplayer:$Id: TProofPlayer.h 44401 2012-05-31 13:44:58Z ganis $
 // Author: Maarten Ballintijn   07/01/02
 
 /*************************************************************************
@@ -286,7 +286,7 @@ protected:
    Bool_t              fMergeFiles;    // is True when merging output files centrally is needed
    TDSet              *fDSet;          //!tdset for current processing
    ErrorHandlerFunc_t  fErrorHandler;  // Store previous handler when redirecting output
-   Bool_t              fUseTH1Merge;   // If kTRUE forces use of TH1::Merge [kFALSE]
+   Bool_t              fMergeTH1OneByOne;  // If kTRUE forces TH1 merge one-by-one [kTRUE]
    TH1                *fProcPackets;    //!Histogram with packets being processed (owned by TPerfStats)
 
    virtual Bool_t  HandleTimer(TTimer *timer);
@@ -307,7 +307,7 @@ public:
    TProofPlayerRemote(TProof *proof = 0) : fProof(proof), fOutputLists(0), fFeedback(0),
                                            fFeedbackLists(0), fPacketizer(0),
                                            fMergeFiles(kFALSE), fDSet(0), fErrorHandler(0),
-                                           fUseTH1Merge(kFALSE), fProcPackets(0)
+                                           fMergeTH1OneByOne(kTRUE), fProcPackets(0)
                                            { fProgressStatus = new TProofProgressStatus(); }
    virtual ~TProofPlayerRemote();   // Owns the fOutput list
    virtual Long64_t Process(TDSet *set, const char *selector,
diff --git a/proof/proofplayer/src/TProofPlayer.cxx b/proof/proofplayer/src/TProofPlayer.cxx
index 93c2648..a9c4e20 100644
--- a/proof/proofplayer/src/TProofPlayer.cxx
+++ b/proof/proofplayer/src/TProofPlayer.cxx
@@ -1,4 +1,4 @@
-// @(#)root/proofplayer:$Id: TProofPlayer.cxx 44065 2012-05-02 12:41:50Z ganis $
+// @(#)root/proofplayer:$Id: TProofPlayer.cxx 44523 2012-06-04 15:17:29Z ganis $
 // Author: Maarten Ballintijn   07/01/02
 
 /*************************************************************************
@@ -1541,10 +1541,10 @@ Int_t TProofPlayerRemote::InitPacketizer(TDSet *dset, Long64_t nentries,
    fExitStatus = kFinished;
 
    // This is done here to pickup on the fly changes
-   Int_t usemerge = 0;
-   if (TProof::GetParameter(fInput, "PROOF_UseTH1Merge", usemerge) != 0)
-      usemerge = gEnv->GetValue("ProofPlayer.UseTH1Merge", 0);
-   fUseTH1Merge = (usemerge == 1) ? kTRUE : kFALSE;
+   Int_t honebyone = 1;
+   if (TProof::GetParameter(fInput, "PROOF_MergeTH1OneByOne", honebyone) != 0)
+      honebyone = gEnv->GetValue("ProofPlayer.MergeTH1OneByOne", 1);
+   fMergeTH1OneByOne = (honebyone == 1) ? kTRUE : kFALSE;
 
    Bool_t noData = dset->TestBit(TDSet::kEmpty) ? kTRUE : kFALSE;
 
@@ -2406,13 +2406,13 @@ Long64_t TProofPlayerRemote::Finalize(Bool_t force, Bool_t sync)
          if (!fCreateSelObj) {
             fInput->Remove(fSelector);
             fOutput->Remove(fSelector);
-            output->Remove(fSelector);
+            if (output) output->Remove(fSelector);
          }
 
          // We have transferred copy of the output objects in TQueryResult,
          // so now we can cleanup the selector, making sure that we do not
          // touch the output objects
-         output->SetOwner(kFALSE);
+         if (output) output->SetOwner(kFALSE);
          if (fCreateSelObj) SafeDelete(fSelector);
 
          // Delete fOutput (not needed anymore, cannot be finalized twice),
@@ -3199,70 +3199,38 @@ TObject *TProofPlayerRemote::HandleHistogram(TObject *obj, Bool_t &merged)
          return (TObject *)0;
 
       } else {
-
-         if (!fUseTH1Merge) {
-            // Check if we can 'Add' the histogram to an existing one; this is more efficient
-            // then using Merge
-            TH1 *hout = (TH1*) fOutput->FindObject(h->GetName());
-            if (hout) {
-               // Do they have the same binning and ranges?
-               Bool_t samebin = HistoSameAxis(hout, h);
-               if (samebin) {
-                  hout->Add(h);
-                  PDB(kOutput,2)
-                     Info("HandleHistogram", "histogram '%s' just added", h->GetName());
-                  merged = kTRUE; // So it will be deleted
-                  return (TObject *)0;
-               } else {
-                  // Remove the existing histo from the output list ...
-                  fOutput->Remove(hout);
-                  // ... and create either the list to merge in one-go at the end
-                  // (more efficient than merging one by one) or, if too big, merge
-                  // these two and start the 'one-by-one' technology
-                  Int_t hsz = h->GetNbinsX() * h->GetNbinsY() * h->GetNbinsZ();
-                  if (gProofServ && hsz > gProofServ->GetMsgSizeHWM()) {
-                     list = new TList;
-                     list->Add(hout);
-                     h->Merge(list);
-                     list->SetOwner();
-                     delete list;
-                     return h;
-                  } else {
-                     list = new TList;
-                     list->SetName(h->GetName());
-                     list->SetOwner();
-                     fOutputLists->Add(list);
-                     // Add the existing and the incoming histos
-                     list->Add(hout);
-                     list->Add(h);
-                     // Done
-                     return (TObject *)0;
-                  }
-               }
-            } else {
-               // This is the first one; add it to the output list
-               fOutput->Add(h);
-               return (TObject *)0;
-            }
-
-         } else {
-
-            // Histogram has already been projected
+         // Check if we can 'Add' the histogram to an existing one; this is more efficient
+         // then using Merge
+         TH1 *hout = (TH1*) fOutput->FindObject(h->GetName());
+         if (hout) {
+            // Remove the existing histo from the output list ...
+            fOutput->Remove(hout);
+            // ... and create either the list to merge in one-go at the end
+            // (more efficient than merging one by one) or, if too big, merge
+            // these two and start the 'one-by-one' technology
             Int_t hsz = h->GetNbinsX() * h->GetNbinsY() * h->GetNbinsZ();
-            if (gProofServ && hsz > gProofServ->GetMsgSizeHWM()) {
-               // Large histo: merge one-by-one
-               return obj;
+            if (fMergeTH1OneByOne || (gProofServ && hsz > gProofServ->GetMsgSizeHWM())) {
+               list = new TList;
+               list->Add(hout);
+               h->Merge(list);
+               list->SetOwner();
+               delete list;
+               return h;
             } else {
-               // Create the list to merge in one-go at the end (more efficient
-               // than merging one by one)
                list = new TList;
                list->SetName(h->GetName());
                list->SetOwner();
                fOutputLists->Add(list);
+               // Add the existing and the incoming histos
+               list->Add(hout);
                list->Add(h);
                // Done
                return (TObject *)0;
             }
+         } else {
+            // This is the first one; add it to the output list
+            fOutput->Add(h);
+            return (TObject *)0;
          }
       }
    }
diff --git a/proof/proofplayer/src/TProofPlayerLite.cxx b/proof/proofplayer/src/TProofPlayerLite.cxx
index 67d8eb5..7d7ca8a 100644
--- a/proof/proofplayer/src/TProofPlayerLite.cxx
+++ b/proof/proofplayer/src/TProofPlayerLite.cxx
@@ -1,4 +1,4 @@
-// @(#)root/proofplayer:$Id: TProofPlayerLite.cxx 44065 2012-05-02 12:41:50Z ganis $
+// @(#)root/proofplayer:$Id: TProofPlayerLite.cxx 44523 2012-06-04 15:17:29Z ganis $
 // Author: G. Ganis Mar 2008
 
 /*************************************************************************
@@ -386,13 +386,13 @@ Long64_t TProofPlayerLite::Finalize(Bool_t force, Bool_t sync)
       if (!fCreateSelObj) {
          fInput->Remove(fSelector);
          fOutput->Remove(fSelector);
-         output->Remove(fSelector);
+         if (output) output->Remove(fSelector);
       }
 
       // We have transferred copy of the output objects in TQueryResult,
       // so now we can cleanup the selector, making sure that we do not
       // touch the output objects
-      output->SetOwner(kFALSE);
+      if (output) output->SetOwner(kFALSE);
       if (fCreateSelObj) SafeDelete(fSelector);
 
       // Delete fOutput (not needed anymore, cannot be finalized twice),
diff --git a/proof/proofx/src/TXProofMgr.cxx b/proof/proofx/src/TXProofMgr.cxx
index 5ee0247..4786f0a 100644
--- a/proof/proofx/src/TXProofMgr.cxx
+++ b/proof/proofx/src/TXProofMgr.cxx
@@ -1,4 +1,4 @@
-// @(#)root/proofx:$Id: TXProofMgr.cxx 44104 2012-05-03 23:25:39Z ganis $
+// @(#)root/proofx:$Id: TXProofMgr.cxx 44523 2012-06-04 15:17:29Z ganis $
 // Author: Gerardo Ganis  12/12/2005
 
 /*************************************************************************
@@ -772,18 +772,18 @@ Int_t TXProofMgr::SendMsgToUsers(const char *msg, const char *usr)
    const Int_t kMAXBUF = 32768;
    char buf[kMAXBUF] = {0};
    char *p = &buf[0];
-   Int_t space = kMAXBUF - 1;
-   Int_t len = 0;
+   size_t space = kMAXBUF - 1;
    Int_t lusr = 0;
 
    // A specific user?
    if (usr && strlen(usr) > 0 && (strlen(usr) != 1 || usr[0] != '*')) {
       lusr = (strlen(usr) + 3);
-      sprintf(buf, "u:%s ", usr);
+      snprintf(buf, kMAXBUF, "u:%s ", usr);
       p += lusr;
       space -= lusr;
    }
 
+   ssize_t len = 0;
    // Is it from file ?
    if (!gSystem->AccessPathName(msg, kFileExists)) {
       // From file: can we read it ?
@@ -798,14 +798,27 @@ Int_t TXProofMgr::SendMsgToUsers(const char *msg, const char *usr)
          return -1;
       }
       // Determine the number of bytes to be read from the file.
-      Int_t left = (Int_t) lseek(fileno(f), (off_t) 0, SEEK_END);
-      lseek(fileno(f), (off_t) 0, SEEK_SET);
+      size_t left = 0;
+      off_t rcsk = lseek(fileno(f), (off_t) 0, SEEK_END);
+      if ((rcsk != (off_t)(-1))) {
+         left = (size_t) rcsk;
+         if ((lseek(fileno(f), (off_t) 0, SEEK_SET) == (off_t)(-1))) {
+            Error("SendMsgToUsers", "cannot rewind open file (seek to 0)");
+            fclose(f);      
+            return -1;
+         }
+      } else {
+         Error("SendMsgToUsers", "cannot get size of open file (seek to END)");
+         fclose(f);      
+         return -1;
+      }
       // Now readout from file
-      Int_t wanted = left;
+      size_t wanted = left;
       if (wanted > space) {
          wanted = space;
          Warning("SendMsgToUsers",
-                 "requested to send %d bytes: max size is %d bytes: truncating", left, space);
+                 "requested to send %lld bytes: max size is %lld bytes: truncating",
+                 (Long64_t)left, (Long64_t)space);
       }
       do {
          while ((len = read(fileno(f), p, wanted)) < 0 &&
@@ -817,17 +830,20 @@ Int_t TXProofMgr::SendMsgToUsers(const char *msg, const char *usr)
          }
 
          // Update counters
-         left -= len;
+         left = (len >= (ssize_t)left) ? 0 : left - len;
          p += len;
          wanted = (left > kMAXBUF-1) ? kMAXBUF-1 : left;
 
       } while (len > 0 && left > 0);
+      // Close file
+      fclose(f);
    } else {
       // Add the message to the buffer
       len = strlen(msg);
-      if (len > space) {
+      if (len > (ssize_t)space) {
          Warning("SendMsgToUsers",
-                 "requested to send %d bytes: max size is %d bytes: truncating", len, space);
+                 "requested to send %lld bytes: max size is %lld bytes: truncating",
+                 (Long64_t)len, (Long64_t)space);
          len = space;
       }
       memcpy(p, msg, len);
@@ -1101,6 +1117,7 @@ Int_t TXProofMgr::Stat(const char *what, FileStat_t &st, const char *where)
    // Show the result, if any
    if (os) {
       if (gDebug > 1) Printf("%s", os->GetName());
+#if 0
       Int_t    mode, uid, gid, islink;
       Long_t   dev, ino, mtime;
       Long64_t size;
@@ -1121,6 +1138,27 @@ Int_t TXProofMgr::Stat(const char *what, FileStat_t &st, const char *where)
       st.fSize   = size;
       st.fMtime  = mtime;
       st.fIsLink = (islink == 1);
+#else
+      TString tkn;
+      Ssiz_t from = 0;
+      if (!os->GetString().Tokenize(tkn, from, "[ ]+") || !tkn.IsDigit()) return -1;
+      st.fDev = tkn.Atoi();
+      if (st.fDev == -1) return -1;
+      if (!os->GetString().Tokenize(tkn, from, "[ ]+") || !tkn.IsDigit()) return -1;
+      st.fIno = tkn.Atoi();
+      if (!os->GetString().Tokenize(tkn, from, "[ ]+") || !tkn.IsDigit()) return -1;
+      st.fMode = tkn.Atoi();
+      if (!os->GetString().Tokenize(tkn, from, "[ ]+") || !tkn.IsDigit()) return -1;
+      st.fUid = tkn.Atoi();
+      if (!os->GetString().Tokenize(tkn, from, "[ ]+") || !tkn.IsDigit()) return -1;
+      st.fGid = tkn.Atoi();
+      if (!os->GetString().Tokenize(tkn, from, "[ ]+") || !tkn.IsDigit()) return -1;
+      st.fSize = tkn.Atoll();
+      if (!os->GetString().Tokenize(tkn, from, "[ ]+") || !tkn.IsDigit()) return -1;
+      st.fMtime = tkn.Atoi();
+      if (!os->GetString().Tokenize(tkn, from, "[ ]+") || !tkn.IsDigit()) return -1;
+      st.fIsLink = (tkn.Atoi() == 1) ? kTRUE : kFALSE;
+#endif
 
       // Cleanup
       SafeDelete(os);
@@ -1368,8 +1406,14 @@ Int_t TXProofMgr::GetFile(const char *remote, const char *local, const char *opt
 
    if (os) {
       // The message contains the size
-      Long64_t size;
-      sscanf(os->GetName(), "%lld", &size);
+      TString ssz(os->GetName());
+      ssz.ReplaceAll(" ", "");
+      if (!ssz.IsDigit()) {
+         Error("GetFile", "received non-digit size string: '%s' ('%s')", os->GetName(), ssz.Data());
+         close(fdout);
+         return rc;
+      }
+      Long64_t size = ssz.Atoll();
       if (size <= 0) {
          Error("GetFile", "received null or negative size: %lld", size);
          close(fdout);
diff --git a/proof/proofx/src/TXProofServ.cxx b/proof/proofx/src/TXProofServ.cxx
index 9673b26..9fade6c 100644
--- a/proof/proofx/src/TXProofServ.cxx
+++ b/proof/proofx/src/TXProofServ.cxx
@@ -1,4 +1,4 @@
-// @(#)root/proofx:$Id: TXProofServ.cxx 39696 2011-06-13 21:35:34Z pcanal $
+// @(#)root/proofx:$Id: TXProofServ.cxx 44523 2012-06-04 15:17:29Z ganis $
 // Author: Gerardo Ganis  12/12/2005
 
 /*************************************************************************
@@ -634,9 +634,9 @@ Int_t TXProofServ::Setup()
    char str[512];
 
    if (IsMaster()) {
-      sprintf(str, "**** Welcome to the PROOF server @ %s ****", gSystem->HostName());
+      snprintf(str, 512, "**** Welcome to the PROOF server @ %s ****", gSystem->HostName());
    } else {
-      sprintf(str, "**** PROOF worker server @ %s started ****", gSystem->HostName());
+      snprintf(str, 512, "**** PROOF worker server @ %s started ****", gSystem->HostName());
    }
 
    if (fSocket->Send(str) != 1+static_cast<Int_t>(strlen(str))) {
@@ -891,7 +891,7 @@ Bool_t TXProofServ::HandleError(const void *)
       fProof->Close("S");
 
    // Avoid communicating back anything to the coordinator (it is gone)
-   ((TXSocket *)fSocket)->SetSessionID(-1);
+   if (fSocket) ((TXSocket *)fSocket)->SetSessionID(-1);
 
    Terminate(0);
 
diff --git a/proof/proofx/src/TXSocket.cxx b/proof/proofx/src/TXSocket.cxx
index 104705c..3a4125a 100644
--- a/proof/proofx/src/TXSocket.cxx
+++ b/proof/proofx/src/TXSocket.cxx
@@ -1,4 +1,4 @@
-// @(#)root/proofx:$Id: TXSocket.cxx 44103 2012-05-03 23:11:44Z ganis $
+// @(#)root/proofx:$Id: TXSocket.cxx 44523 2012-06-04 15:17:29Z ganis $
 // Author: Gerardo Ganis  12/12/2005
 
 /*************************************************************************
@@ -445,12 +445,6 @@ UnsolRespProcResult TXSocket::ProcessUnsolicitedMsg(XrdClientUnsolMsgSender *,
    }
 
    // Local processing ...
-   if (!m) {
-      Error("ProcessUnsolicitedMsg", "undefined message - disabling");
-      PostMsg(kPROOF_STOP);
-      return rc;
-   }
-
    Int_t len = 0;
    if ((len = m->DataLen()) < (int)sizeof(kXR_int32)) {
       Error("ProcessUnsolicitedMsg", "empty or bad-formed message - disabling");
@@ -1000,8 +994,10 @@ Int_t TXSocket::Flush()
          }
 
          // Reset the asynchronous queue
-         while (sz--)
-            fASem.TryWait();
+         while (sz--) {
+            if (fASem.TryWait() == 1)
+               Printf("Warning in TXSocket::Flush: semaphore counter already 0 (sz: %d)", sz);
+         }
          fAQue.clear();
       }
    }
@@ -1088,6 +1084,7 @@ Bool_t TXSocket::Create(Bool_t attach)
          } else {
             Error("Create","session ID is undefined!");
             fSessionID = -1;
+            if (srvresp) free(srvresp);
             return kFALSE;
          }
 
@@ -1134,8 +1131,7 @@ Bool_t TXSocket::Create(Bool_t attach)
 
          // Cleanup
          SafeDelete(xrsp);
-         if (srvresp)
-            free(srvresp);
+         if (srvresp) free(srvresp);
 
          // Notify
          return kTRUE;
@@ -1150,6 +1146,7 @@ Bool_t TXSocket::Create(Bool_t attach)
          if (fConn->GetOpenError() == kXP_TooManySess) {
             // Avoid to contact the server any more
             fSessionID = -1;
+            if (srvresp) free(srvresp);
             return kFALSE;
          } else {
             // Print error msg, if any
@@ -1167,6 +1164,7 @@ Bool_t TXSocket::Create(Bool_t attach)
          Error("Create", "%d creation/attachment attempts failed: no attempts left",
                          gEnv->GetValue("XProof.CreationRetries", 4));
 
+      if (srvresp) free(srvresp);
    } // Creation retries
    
    // The session is invalid: reset the sessionID to invalid state (it was our protocol
@@ -1290,6 +1288,7 @@ Bool_t TXSocket::Ping(const char *ord)
 
       // Cleanup
       SafeDelete(xrsp);
+      if (pans) free(pans);
 
    } else {
       if (XPD::clientMarshall(&Request) == 0) {
@@ -1446,12 +1445,15 @@ Int_t TXSocket::PickUpReady()
       Error("PickUpReady","queue is empty - protocol error ?");
       return -1;
    }
-   fBufCur = fAQue.front();
+   if (!(fBufCur = fAQue.front())) {
+      Error("PickUpReady","got invalid buffer - protocol error ?");
+      return -1;
+   }
    // Remove message from the queue
    fAQue.pop_front();
+
    // Set number of available bytes
-   if (fBufCur)
-      fByteLeft = fBufCur->fLen;
+   fByteLeft = fBufCur->fLen;
 
    if (gDebug > 2)
       Info("PickUpReady", "%p: %s: got message (%d bytes)",
@@ -1511,10 +1513,9 @@ TXSockBuf *TXSocket::PopUpSpare(Int_t size)
    }
 
    // Create a new buffer
-   char *b = (char *)malloc(size);
-   if (b)
-      buf = new TXSockBuf(b, size);
+   buf = new TXSockBuf((char *)malloc(size), size);
    nBuf++;
+
    if (gDebug > 2)
       Info("PopUpSpare","asked: %d, spare: %d/%d, maxsz: %d, NEW buf %p, sz: %d",
                         size, (int) fgSQue.size(), nBuf, maxsz, buf, buf->fSiz);
@@ -2121,9 +2122,13 @@ Int_t TXSocket::Reconnect()
    }
 
    if (gDebug > 0) {
-      Info("Reconnect", "%p (c:%p): attempt %s (logid: %d)", this, fConn,
-                        ((fConn && fConn->IsValid()) ? "succeeded!" : "failed"),
-                        fConn->GetLogConnID() );
+      if (fConn) {
+         Info("Reconnect", "%p (c:%p): attempt %s (logid: %d)", this, fConn,
+                           (fConn->IsValid() ? "succeeded!" : "failed"),
+                           fConn->GetLogConnID() );
+      } else {
+         Info("Reconnect", "%p (c:0x0): attempt failed", this);
+      }
    }
 
    // Done
diff --git a/roofit/histfactory/Module.mk b/roofit/histfactory/Module.mk
index 82b28fc..29a6fc0 100644
--- a/roofit/histfactory/Module.mk
+++ b/roofit/histfactory/Module.mk
@@ -49,6 +49,7 @@ HF_LIBS = -Llib -lRooFit -lRooFitCore -lTree -lRIO -lMatrix \
 HF_LIBS += -lHistFactory 
 ifeq ($(BUILDMATHMORE),yes)
 HF_LIBS += -lMathMore
+HF_LIBS += $(GSLLIBDIR) $(GSLLIBS)
 endif
 endif
 
@@ -91,7 +92,6 @@ include/RooStats/HistFactory/%.h:    $(HISTFACTORYDIRI)/RooStats/HistFactory/%.h
 		fi)
 		cp $< $@
 
-
 $(HISTFACTORYLIB): $(HISTFACTORYO) $(HISTFACTORYDO) $(ORDER_) $(MAINLIBS) \
                 $(HISTFACTORYLIBDEP) 
 		@$(MAKELIB) $(PLATFORM) $(LD) "$(LDFLAGS)" \
@@ -108,27 +108,19 @@ $(HISTFACTORYMAP): $(RLIBMAP) $(MAKEFILEDEP) $(HISTFACTORYL)
 		$(RLIBMAP) -o  $@ -l $(HISTFACTORYLIB) \
 		   -d $(HISTFACTORYLIBDEPM) -c $(HISTFACTORYL)
 
-
-$(HF_MAKEWORKSPACEEXE): $(HF_MAKEWORKSPACEEXEO) $(ROOTLIBSDEP) $(RINTLIB) $(HISTFACTORYLIBDEPM) \
-		$(HF_PREPAREHISTFACTORY) $(HISTFACTORYLIB)
+$(HF_MAKEWORKSPACEEXE): $(HF_MAKEWORKSPACEEXEO) $(ROOTLIBSDEP) $(RINTLIB) \
+                $(HISTFACTORYLIBDEPM) $(HF_PREPAREHISTFACTORY) $(HISTFACTORYLIB)
 		$(LD) $(LDFLAGS) -o $@ $(HF_MAKEWORKSPACEEXEO) $(ROOTICON) \
-		   $(ROOTULIBS) $(RPATH) $(ROOTLIBS) $(RINTLIBS) $(HF_LIBS) $(SYSLIBS)  
-
-#$(HF_MAKEWORKSPACEEXE2): $(HF_MAKEWORKSPACEEXEO) $(ROOTLIBSDEP) $(RINTLIB) $(HISTFACTORYLIBDEPM) \
-#		$(HF_PREPAREHISTFACTORY) $(HISTFACTORYLIB)
-#		$(LD) $(LDFLAGS) -o $@ $(HF_MAKEWORKSPACEEXEO) $(ROOTICON) \
-#		   $(ROOTULIBS) $(RPATH) $(ROOTLIBS) $(RINTLIBS) $(HF_LIBS) $(SYSLIBS)  
+		   $(ROOTULIBS) $(RPATH) $(ROOTLIBS) $(RINTLIBS) $(HF_LIBS) \
+		   $(SYSLIBS)
 
 $(HF_PREPAREHISTFACTORY): $(MODDIRC)/prepareHistFactory
 		cp $(MODDIRC)/prepareHistFactory $@
 		chmod +x $@
 
+ALLEXECS     += $(HF_MAKEWORKSPACEEXE)
 
-ALLEXECS     += $(HF_MAKEWORKSPACEEXE) # $(HF_MAKEWORKSPACEEXE2) 
-
-
-
-all-$(MODNAME): $(HISTFACTORYLIB) $(HISTFACTORYMAP) $(HF_MAKEWORKSPACEEXE) #$(HF_MAKEWORKSPACEEXE2)
+all-$(MODNAME): $(HISTFACTORYLIB) $(HISTFACTORYMAP) $(HF_MAKEWORKSPACEEXE)
 
 clean-$(MODNAME):
 		@rm -f $(HISTFACTORYO) $(HISTFACTORYDO)
diff --git a/roofit/histfactory/inc/LinkDef.h b/roofit/histfactory/inc/LinkDef.h
index 85142bd..df7c3a5 100644
--- a/roofit/histfactory/inc/LinkDef.h
+++ b/roofit/histfactory/inc/LinkDef.h
@@ -12,7 +12,8 @@
 #pragma link C++ class RooStats::HistFactory::EstimateSummary+ ;
 #pragma link C++ class RooStats::HistFactory::HistoToWorkspaceFactory+ ;
 #pragma link C++ class RooStats::HistFactory::HistoToWorkspaceFactoryFast+ ;
-//#pragma link C++ class RooStats::HistFactory::HistoToWorkspaceFactoryNew+ ;
+#pragma link C++ class RooStats::HistFactory::RooBarlowBeestonLL+ ;  
+#pragma link C++ class RooStats::HistFactory::HistFactorySimultaneous+ ;  
 
 #pragma link C++ class RooStats::HistFactory::ConfigParser+ ;
 
@@ -31,7 +32,7 @@
 
 #pragma link C++ defined_in "include/RooStats/HistFactory/MakeModelAndMeasurementsFast.h"; 
 #pragma link C++ defined_in "include/RooStats/HistFactory/Systematics.h"; 
-
+#pragma link C++ defined_in "include/RooStats/HistFactory/HistFactoryModelUtils.h"; 
 
 
 #endif
diff --git a/roofit/histfactory/inc/RooStats/HistFactory/ConfigParser.h b/roofit/histfactory/inc/RooStats/HistFactory/ConfigParser.h
index 530a21b..ab79c47 100644
--- a/roofit/histfactory/inc/RooStats/HistFactory/ConfigParser.h
+++ b/roofit/histfactory/inc/RooStats/HistFactory/ConfigParser.h
@@ -1,4 +1,4 @@
-// @(#)root/roostats:$Id: ConfigParser.h 44159 2012-05-07 17:16:40Z moneta $
+// @(#)root/roostats:$Id: ConfigParser.h 44376 2012-05-30 21:47:29Z moneta $
 // Author: Kyle Cranmer, Akira Shibata
 /*************************************************************************
  * Copyright (C) 1995-2008, Rene Brun and Fons Rademakers.               *
@@ -71,9 +71,9 @@ namespace RooStats{
 
        // To be deprecated
        /*
-       typedef pair<double,double> UncertPair;
-       void AddSystematic( RooStats::HistFactory::EstimateSummary &, TXMLNode*, string, string,string);
-       void ReadXmlConfig( string, vector<RooStats::HistFactory::Channel>& , Double_t );
+       typedef std::pair<double,double> UncertPair;
+       void AddSystematic( RooStats::HistFactory::EstimateSummary &, TXMLNode*, std::string, std::string,std::string);
+       void ReadXmlConfig( std::string, std::vector<RooStats::HistFactory::Channel>& , Double_t );
        */
 
      protected:
diff --git a/roofit/histfactory/inc/RooStats/HistFactory/FlexibleInterpVar.h b/roofit/histfactory/inc/RooStats/HistFactory/FlexibleInterpVar.h
index 4c6a2f7..e98ba46 100644
--- a/roofit/histfactory/inc/RooStats/HistFactory/FlexibleInterpVar.h
+++ b/roofit/histfactory/inc/RooStats/HistFactory/FlexibleInterpVar.h
@@ -27,11 +27,11 @@ namespace HistFactory{
     FlexibleInterpVar() ;
     FlexibleInterpVar(const char *name, const char *title,
 		      const RooArgList& _paramList, 
-		      double nominal, vector<double> low, vector<double> high);
+		      double nominal, std::vector<double> low, std::vector<double> high);
 
     FlexibleInterpVar(const char *name, const char *title,
-		      const RooArgList& _paramList, double nominal, vector<double> low, 
-		      vector<double> high,vector<int> code);
+		      const RooArgList& _paramList, double nominal, std::vector<double> low, 
+		      std::vector<double> high,std::vector<int> code);
 
     FlexibleInterpVar(const char *name, const char *title);
     FlexibleInterpVar(const FlexibleInterpVar&, const char*);
@@ -50,9 +50,9 @@ namespace HistFactory{
 
     RooListProxy _paramList ;
     Double_t _nominal;
-    vector<double> _low;
-    vector<double> _high;
-    vector<int> _interpCode;
+    std::vector<double> _low;
+    std::vector<double> _high;
+    std::vector<int> _interpCode;
     Double_t _interpBoundary;
 
     TIterator* _paramIter ;  //! do not persist
diff --git a/roofit/histfactory/inc/RooStats/HistFactory/HistFactoryException.h b/roofit/histfactory/inc/RooStats/HistFactory/HistFactoryException.h
index 7df687e..8a291c7 100644
--- a/roofit/histfactory/inc/RooStats/HistFactory/HistFactoryException.h
+++ b/roofit/histfactory/inc/RooStats/HistFactory/HistFactoryException.h
@@ -2,19 +2,24 @@
 #ifndef HISTFACTORY_EXCEPTION
 #define HISTFACTORY_EXCEPTION
 
-
 #include <iostream>
 #include <exception>
-using namespace std;
 
-class hf_exc: public exception
-{
-  virtual const char* what() const throw()
-  {
-    return "HistFactory - Exception";
+
+namespace RooStats{
+  namespace HistFactory{
+
+    class hf_exc: public std::exception
+    {
+      virtual const char* what() const throw()
+      {
+	return "HistFactory - Exception";
+      }
+    };
+
   }
-};
+}
 
-static hf_exc bad_hf;
+//static hf_exc bad_hf;
 
 #endif
diff --git a/roofit/histfactory/inc/RooStats/HistFactory/HistFactoryModelUtils.h b/roofit/histfactory/inc/RooStats/HistFactory/HistFactoryModelUtils.h
new file mode 100644
index 0000000..e56a960
--- /dev/null
+++ b/roofit/histfactory/inc/RooStats/HistFactory/HistFactoryModelUtils.h
@@ -0,0 +1,37 @@
+
+#ifndef HIST_FACTORY_MODEL_UTILS_H
+#define HIST_FACTORY_MODEL_UTILS_H
+
+#include "RooAbsPdf.h"
+#include "RooArgSet.h"
+#include "RooDataSet.h"
+#include "RooStats/HistFactory/ParamHistFunc.h"
+
+namespace RooStats {
+namespace HistFactory {
+  
+  std::string channelNameFromPdf( RooAbsPdf* channelPdf );
+
+//   void getChannelsFromModel( RooAbsPdf* model, RooArgSet* channels, 
+// 			     RooArgSet* channelsWithConstraints );
+
+
+  void FactorizeHistFactoryPdf(const RooArgSet&, RooAbsPdf&, RooArgList&, RooArgList&);
+  bool getStatUncertaintyFromChannel( RooAbsPdf* channel, ParamHistFunc*& paramfunc, 
+				      RooArgList* gammaList );
+
+  RooAbsPdf* getSumPdfFromChannel( RooAbsPdf* channel );
+
+  void getDataValuesForObservables( std::map< std::string, std::vector<double> >& ChannelBinDataMap, 
+				    RooAbsData* data, RooAbsPdf* simPdf );
+
+
+  int getStatUncertaintyConstraintTerm( RooArgList* constraints, RooRealVar* gamma_stat, 
+					RooAbsReal*& pois_mean, RooRealVar*& tau );
+
+}
+}
+
+
+
+#endif
diff --git a/roofit/histfactory/inc/RooStats/HistFactory/HistFactorySimultaneous.h b/roofit/histfactory/inc/RooStats/HistFactory/HistFactorySimultaneous.h
new file mode 100644
index 0000000..ea47996
--- /dev/null
+++ b/roofit/histfactory/inc/RooStats/HistFactory/HistFactorySimultaneous.h
@@ -0,0 +1,57 @@
+/*****************************************************************************
+ * Project: RooFit                                                           *
+ * Package: RooFitCore                                                       *
+ *    File: $Id: HistFactorySimultaneous.h 44543 2012-06-04 20:25:32Z moneta $
+ * Authors:                                                                  *
+ *   WV, Wouter Verkerke, UC Santa Barbara, verkerke at slac.stanford.edu       *
+ *   DK, David Kirkby,    UC Irvine,         dkirkby at uci.edu                 *
+ *                                                                           *
+ * Copyright (c) 2000-2005, Regents of the University of California          *
+ *                          and Stanford University. All rights reserved.    *
+ *                                                                           *
+ * Redistribution and use in source and binary forms,                        *
+ * with or without modification, are permitted according to the terms        *
+ * listed in LICENSE (http://roofit.sourceforge.net/license.txt)             *
+ *****************************************************************************/
+#ifndef HISTFACTORY_SIMULTANEOUS
+#define HISTFACTORY_SIMULTANEOUS
+
+//#include "THashList.h"
+#include "RooSimultaneous.h"
+
+namespace RooStats{
+namespace HistFactory{
+
+
+class HistFactorySimultaneous : public RooSimultaneous {
+public:
+
+  // Constructors, assignment etc
+  inline HistFactorySimultaneous() : RooSimultaneous() {} //_plotCoefNormRange(0) { }
+  HistFactorySimultaneous(const char *name, const char *title, RooAbsCategoryLValue& indexCat) ;
+  HistFactorySimultaneous(const char *name, const char *title, std::map<std::string,RooAbsPdf*> pdfMap, RooAbsCategoryLValue& inIndexCat) ;
+  HistFactorySimultaneous(const char *name, const char *title, const RooArgList& pdfList, RooAbsCategoryLValue& indexCat) ;
+  HistFactorySimultaneous(const HistFactorySimultaneous& other, const char* name=0);
+  HistFactorySimultaneous(const RooSimultaneous& other, const char* name=0);
+  ~HistFactorySimultaneous();
+
+  virtual TObject* clone(const char* newname) const { return new HistFactorySimultaneous(*this,newname) ; }
+
+  virtual RooAbsReal* createNLL(RooAbsData& data, const RooLinkedList& cmdList);
+
+  virtual RooAbsReal* createNLL(RooAbsData& data, 
+				const RooCmdArg& arg1 = RooCmdArg::none(), const RooCmdArg& arg2 = RooCmdArg::none(), 
+				const RooCmdArg& arg3 = RooCmdArg::none(), const RooCmdArg& arg4 = RooCmdArg::none(), 
+				const RooCmdArg& arg5 = RooCmdArg::none(), const RooCmdArg& arg6 = RooCmdArg::none(), 
+				const RooCmdArg& arg7 = RooCmdArg::none(), const RooCmdArg& arg8 = RooCmdArg::none());
+    
+  
+protected:
+
+  ClassDef(RooStats::HistFactory::HistFactorySimultaneous,2)  // Simultaneous operator p.d.f, functions like C++  'switch()' on input p.d.fs operating on index category5A
+};
+
+}
+}
+
+#endif
diff --git a/roofit/histfactory/inc/RooStats/HistFactory/HistoToWorkspaceFactory.h b/roofit/histfactory/inc/RooStats/HistFactory/HistoToWorkspaceFactory.h
index 2b19df2..4c656ae 100644
--- a/roofit/histfactory/inc/RooStats/HistFactory/HistoToWorkspaceFactory.h
+++ b/roofit/histfactory/inc/RooStats/HistFactory/HistoToWorkspaceFactory.h
@@ -37,58 +37,58 @@ namespace HistFactory{
 
     public:
 
-    HistoToWorkspaceFactory(  string, string , vector<string> , double =200, double =20, int =0, int =6, TFile * =0);
+     HistoToWorkspaceFactory(  std::string, std::string , std::vector<std::string> , double =200, double =20, int =0, int =6, TFile * =0);
       HistoToWorkspaceFactory();
       virtual ~HistoToWorkspaceFactory();
 
-      void AddEfficiencyTerms(RooWorkspace* proto, string prefix, string interpName,
-            map<string,pair<double,double> > systMap,
-            vector<string>& likelihoodTermNames, vector<string>& totSystTermNames);
+      void AddEfficiencyTerms(RooWorkspace* proto, std::string prefix, std::string interpName,
+            std::map<std::string,std::pair<double,double> > systMap,
+            std::vector<std::string>& likelihoodTermNames, std::vector<std::string>& totSystTermNames);
 
-      string AddNormFactor(RooWorkspace *, string & , string & , EstimateSummary & , bool );
+      std::string AddNormFactor(RooWorkspace *, std::string & , std::string & , EstimateSummary & , bool );
 
-      void AddMultiVarGaussConstraint(RooWorkspace* proto, string prefix,int lowBin, int highBin, vector<string>& likelihoodTermNames);
+      void AddMultiVarGaussConstraint(RooWorkspace* proto, std::string prefix,int lowBin, int highBin, std::vector<std::string>& likelihoodTermNames);
 
-      void AddPoissonTerms(RooWorkspace* proto, string prefix, string obsPrefix, string expPrefix, int lowBin, int highBin,
-               vector<string>& likelihoodTermNames);
+      void AddPoissonTerms(RooWorkspace* proto, std::string prefix, std::string obsPrefix, std::string expPrefix, int lowBin, int highBin,
+               std::vector<std::string>& likelihoodTermNames);
 
       //void Combine_old();
 
-      RooWorkspace *  MakeCombinedModel(vector<string>, vector<RooWorkspace*>);
+      RooWorkspace *  MakeCombinedModel(std::vector<std::string>, std::vector<RooWorkspace*>);
 
-      //void Combine_ratio(vector<string> , vector<RooWorkspace*>);
+      //void Combine_ratio(std::vector<std::string> , std::vector<RooWorkspace*>);
 
-      void Customize(RooWorkspace* proto, const char* pdfNameChar, map<string,string> renameMap);
+      void Customize(RooWorkspace* proto, const char* pdfNameChar, std::map<std::string,std::string> renameMap);
 
-      void EditSyst(RooWorkspace* proto, const char* pdfNameChar, map<string,double> gammaSyst, map<string,double> uniformSyst, map<string,double> logNormSyst);
+      void EditSyst(RooWorkspace* proto, const char* pdfNameChar, std::map<std::string,double> gammaSyst, std::map<std::string,double> uniformSyst, std::map<std::string,double> logNormSyst);
 
-      void FormatFrameForLikelihood(RooPlot* frame, string XTitle=string("#sigma / #sigma_{SM}"), string YTitle=string("-log likelihood"));
+      void FormatFrameForLikelihood(RooPlot* frame, std::string XTitle=std::string("#sigma / #sigma_{SM}"), std::string YTitle=std::string("-log likelihood"));
 
 
-      void LinInterpWithConstraint(RooWorkspace* proto, TH1* nominal, vector<TH1*> lowHist, vector<TH1*> highHist,
-                 vector<string> sourceName, string prefix, string productPrefix, string systTerm,
-                 int lowBin, int highBin, vector<string>& likelihoodTermNames);
+      void LinInterpWithConstraint(RooWorkspace* proto, TH1* nominal, std::vector<TH1*> lowHist, std::vector<TH1*> highHist,
+                 std::vector<std::string> sourceName, std::string prefix, std::string productPrefix, std::string systTerm,
+                 int lowBin, int highBin, std::vector<std::string>& likelihoodTermNames);
 
-      TDirectory* Makedirs( TDirectory* file, vector<string> names );
+      TDirectory* Makedirs( TDirectory* file, std::vector<std::string> names );
 
-      RooWorkspace* MakeSingleChannelModel(vector<RooStats::HistFactory::EstimateSummary> summary, vector<string> systToFix, bool doRatio=false);
+      RooWorkspace* MakeSingleChannelModel(std::vector<RooStats::HistFactory::EstimateSummary> summary, std::vector<std::string> systToFix, bool doRatio=false);
 
-      void  MakeTotalExpected(RooWorkspace* proto, string totName, string /**/, string /**/,
-            int lowBin, int highBin, vector<string>& syst_x_expectedPrefixNames,
-            vector<string>& normByNames);
+      void  MakeTotalExpected(RooWorkspace* proto, std::string totName, std::string /**/, std::string /**/,
+            int lowBin, int highBin, std::vector<std::string>& syst_x_expectedPrefixNames,
+            std::vector<std::string>& normByNames);
 
-      TDirectory* Mkdir( TDirectory * file, string name );
+      TDirectory* Mkdir( TDirectory * file, std::string name );
 
-      void PrintCovarianceMatrix(RooFitResult* result, RooArgSet* params, string filename);
-      void ProcessExpectedHisto(TH1* hist,RooWorkspace* proto, string prefix, string productPrefix, string systTerm, double low, double high, int lowBin, int highBin);
-      void SetObsToExpected(RooWorkspace* proto, string obsPrefix, string expPrefix, int lowBin, int highBin);
-      void FitModel(RooWorkspace *, string, string, string, bool=false  );
+      void PrintCovarianceMatrix(RooFitResult* result, RooArgSet* params, std::string filename);
+      void ProcessExpectedHisto(TH1* hist,RooWorkspace* proto, std::string prefix, std::string productPrefix, std::string systTerm, double low, double high, int lowBin, int highBin);
+      void SetObsToExpected(RooWorkspace* proto, std::string obsPrefix, std::string expPrefix, int lowBin, int highBin);
+      void FitModel(RooWorkspace *, std::string, std::string, std::string, bool=false  );
       std::string FilePrefixStr(std::string);
 
-      string fFileNamePrefix;
-      string fRowTitle;
-      vector<string> fSystToFix;
-     double fNomLumi, fLumiError;
+      std::string fFileNamePrefix;
+      std::string fRowTitle;
+      std::vector<std::string> fSystToFix;
+      double fNomLumi, fLumiError;
       int  fLowBin, fHighBin;    
       std::stringstream fResultsPrefixStr;
       TFile * fOut_f;
diff --git a/roofit/histfactory/inc/RooStats/HistFactory/HistoToWorkspaceFactoryFast.h b/roofit/histfactory/inc/RooStats/HistFactory/HistoToWorkspaceFactoryFast.h
index 2c5c9c2..e47ae39 100644
--- a/roofit/histfactory/inc/RooStats/HistFactory/HistoToWorkspaceFactoryFast.h
+++ b/roofit/histfactory/inc/RooStats/HistFactory/HistoToWorkspaceFactoryFast.h
@@ -40,7 +40,7 @@ namespace HistFactory{
     
   public:
     
-    HistoToWorkspaceFactoryFast(  string, string , vector<string> , double =200, double =20, int =0, int =6, TFile* =NULL);
+    HistoToWorkspaceFactoryFast(  std::string, std::string , std::vector<std::string> , double =200, double =20, int =0, int =6, TFile* =NULL);
     HistoToWorkspaceFactoryFast(  RooStats::HistFactory::Measurement& Meas );
     static void ConfigureWorkspaceForMeasurement( const std::string& ModelName, RooWorkspace* ws_single, Measurement& measurement );
     
@@ -50,56 +50,56 @@ namespace HistFactory{
     RooWorkspace* MakeSingleChannelModel( Measurement& measurement, Channel& channel );
     static RooWorkspace* MakeCombinedModel( Measurement& measurement );
     
-    void SetFunctionsToPreprocess(vector<string> lines){ fPreprocessFunctions = lines;}
+    void SetFunctionsToPreprocess(std::vector<std::string> lines){ fPreprocessFunctions = lines;}
     
-    void AddEfficiencyTerms(RooWorkspace* proto, string prefix, string interpName,
-			    map<string,pair<double,double> > systMap,
-			    vector<string>& likelihoodTermNames, vector<string>& totSystTermNames);
+    void AddEfficiencyTerms(RooWorkspace* proto, std::string prefix, std::string interpName,
+			    std::map<std::string,std::pair<double,double> > systMap,
+			    std::vector<std::string>& likelihoodTermNames, std::vector<std::string>& totSystTermNames);
     
-    string AddNormFactor(RooWorkspace *, string & , string & , EstimateSummary & , bool );
+    std::string AddNormFactor(RooWorkspace *, std::string & , std::string & , EstimateSummary & , bool );
     
-    void AddMultiVarGaussConstraint(RooWorkspace* proto, string prefix,int lowBin, int highBin, vector<string>& likelihoodTermNames);
+    void AddMultiVarGaussConstraint(RooWorkspace* proto, std::string prefix,int lowBin, int highBin, std::vector<std::string>& likelihoodTermNames);
     
-    void AddPoissonTerms(RooWorkspace* proto, string prefix, string obsPrefix, string expPrefix, int lowBin, int highBin,
-			 vector<string>& likelihoodTermNames);
+    void AddPoissonTerms(RooWorkspace* proto, std::string prefix, std::string obsPrefix, std::string expPrefix, int lowBin, int highBin,
+			 std::vector<std::string>& likelihoodTermNames);
     
     //void Combine_old();
     
-    RooWorkspace *  MakeCombinedModel(vector<string>, vector<RooWorkspace*>);
+    RooWorkspace *  MakeCombinedModel(std::vector<std::string>, std::vector<RooWorkspace*>);
     
-    //void Combine_ratio(vector<string> , vector<RooWorkspace*>);
+    //void Combine_ratio(std::vector<std::string> , std::vector<RooWorkspace*>);
     
-    void Customize(RooWorkspace* proto, const char* pdfNameChar, map<string,string> renameMap);
+    void Customize(RooWorkspace* proto, const char* pdfNameChar, std::map<std::string,std::string> renameMap);
     
     static void EditSyst(RooWorkspace* proto, const char* pdfNameChar, 
-			 map<string,double> gammaSyst, map<string,double> uniformSyst, map<string,double> logNormSyst, map<string,double> noSyst);
+			 std::map<std::string,double> gammaSyst, std::map<std::string,double> uniformSyst, std::map<std::string,double> logNormSyst, std::map<std::string,double> noSyst);
     
-    //void FormatFrameForLikelihood(RooPlot* frame, string XTitle=string("#sigma / #sigma_{SM}"), string YTitle=string("-log likelihood"));
+    //void FormatFrameForLikelihood(RooPlot* frame, std::string XTitle=std::string("#sigma / #sigma_{SM}"), std::string YTitle=std::string("-log likelihood"));
     
     
-    void LinInterpWithConstraint(RooWorkspace* proto, TH1* nominal, vector<TH1*> lowHist, vector<TH1*> highHist,
-				 vector<string> sourceName, string prefix, string productPrefix, string systTerm,
-				 int lowBin, int highBin, vector<string>& likelihoodTermNames);
+    void LinInterpWithConstraint(RooWorkspace* proto, TH1* nominal, std::vector<TH1*> lowHist, std::vector<TH1*> highHist,
+				 std::vector<std::string> sourceName, std::string prefix, std::string productPrefix, std::string systTerm,
+				 int lowBin, int highBin, std::vector<std::string>& likelihoodTermNames);
     
-    TDirectory* Makedirs( TDirectory* file, vector<string> names );
+    TDirectory* Makedirs( TDirectory* file, std::vector<std::string> names );
     
-    RooWorkspace* MakeSingleChannelModel(vector<RooStats::HistFactory::EstimateSummary> summary, vector<string> systToFix, bool doRatio=false);
+    RooWorkspace* MakeSingleChannelModel(std::vector<RooStats::HistFactory::EstimateSummary> summary, std::vector<std::string> systToFix, bool doRatio=false);
     
-    void  MakeTotalExpected(RooWorkspace* proto, string totName, string /**/, string /**/,
-			    int lowBin, int highBin, vector<string>& syst_x_expectedPrefixNames,
-			    vector<string>& normByNames);
+    void  MakeTotalExpected(RooWorkspace* proto, std::string totName, std::string /**/, std::string /**/,
+			    int lowBin, int highBin, std::vector<std::string>& syst_x_expectedPrefixNames,
+			    std::vector<std::string>& normByNames);
     
-    TDirectory* Mkdir( TDirectory * file, string name );
+    TDirectory* Mkdir( TDirectory * file, std::string name );
     
-    static void PrintCovarianceMatrix(RooFitResult* result, RooArgSet* params, string filename);
-    void ProcessExpectedHisto(TH1* hist,RooWorkspace* proto, string prefix, string productPrefix, string systTerm, double low, double high, int lowBin, int highBin);
-    void SetObsToExpected(RooWorkspace* proto, string obsPrefix, string expPrefix, int lowBin, int highBin);
-    //void FitModel(const std::string& FileNamePrefix, RooWorkspace *, string, string, TFile*, FILE*);
+    static void PrintCovarianceMatrix(RooFitResult* result, RooArgSet* params, std::string filename);
+    void ProcessExpectedHisto(TH1* hist,RooWorkspace* proto, std::string prefix, std::string productPrefix, std::string systTerm, double low, double high, int lowBin, int highBin);
+    void SetObsToExpected(RooWorkspace* proto, std::string obsPrefix, std::string expPrefix, int lowBin, int highBin);
+    //void FitModel(const std::string& FileNamePrefix, RooWorkspace *, std::string, std::string, TFile*, FILE*);
     //std::string FilePrefixStr(std::string);
     
     TH1* MakeScaledUncertaintyHist( const std::string& Name, std::vector< std::pair<TH1*,TH1*> > HistVec );
     TH1* MakeAbsolUncertaintyHist( const std::string& Name, const TH1* Hist );
-    RooArgList createStatConstraintTerms( RooWorkspace* proto, vector<string>& constraintTerms, ParamHistFunc& paramHist, TH1* uncertHist, 
+    RooArgList createStatConstraintTerms( RooWorkspace* proto, std::vector<std::string>& constraintTerms, ParamHistFunc& paramHist, TH1* uncertHist, 
 					  EstimateSummary::ConstraintType type, Double_t minSigma );
     
     inline void SetObsNameVec(const std::vector<std::string>& obsNameVec) { fObsNameVec = obsNameVec; }
@@ -108,7 +108,7 @@ namespace HistFactory{
     
     //string fFileNamePrefix;
     //string fRowTitle;
-    vector<string> fSystToFix;
+    std::vector<std::string> fSystToFix;
     double fNomLumi, fLumiError;
     int fLowBin, fHighBin;    
     //std::stringstream fResultsPrefixStr;
@@ -121,7 +121,7 @@ namespace HistFactory{
     
     std::vector<std::string> fObsNameVec;
     std::string fObsName;
-    vector<string> fPreprocessFunctions;
+    std::vector<std::string> fPreprocessFunctions;
     
     ClassDef(RooStats::HistFactory::HistoToWorkspaceFactoryFast,3)
   };
diff --git a/roofit/histfactory/inc/RooStats/HistFactory/LinInterpVar.h b/roofit/histfactory/inc/RooStats/HistFactory/LinInterpVar.h
index 4821f77..3225ad7 100644
--- a/roofit/histfactory/inc/RooStats/HistFactory/LinInterpVar.h
+++ b/roofit/histfactory/inc/RooStats/HistFactory/LinInterpVar.h
@@ -26,7 +26,7 @@ namespace HistFactory{
 
     LinInterpVar() ;
     LinInterpVar(const char *name, const char *title,
-           const RooArgList& _paramList, double nominal, vector<double> low, vector<double> high);
+                 const RooArgList& _paramList, double nominal, std::vector<double> low, std::vector<double> high);
 
     LinInterpVar(const char *name, const char *title);
     LinInterpVar(const LinInterpVar&, const char*);
@@ -39,8 +39,8 @@ namespace HistFactory{
 
     RooListProxy _paramList ;
     double _nominal;
-    vector<double> _low;
-    vector<double> _high;
+    std::vector<double> _low;
+    std::vector<double> _high;
     
     TIterator* _paramIter ;  //! do not persist
 
diff --git a/roofit/histfactory/inc/RooStats/HistFactory/MakeModelAndMeasurementsFast.h b/roofit/histfactory/inc/RooStats/HistFactory/MakeModelAndMeasurementsFast.h
index 9b4946a..9fc9dc3 100644
--- a/roofit/histfactory/inc/RooStats/HistFactory/MakeModelAndMeasurementsFast.h
+++ b/roofit/histfactory/inc/RooStats/HistFactory/MakeModelAndMeasurementsFast.h
@@ -1,7 +1,17 @@
 
-#ifndef MAKEMODELANDMEASUREMENTSFAST_H
-#define MAKEMODELANDMEASUREMENTSFAST_H
+#ifndef HISTFACTORY_MAKEMODELANDMEASUREMENTSFAST_H
+#define HISTFACTORY_MAKEMODELANDMEASUREMENTSFAST_H
 
+#include <string>
+#include <vector>
+
+#include "RooStats/HistFactory/Measurement.h"
+#include "RooStats/HistFactory/Channel.h"
+#include "RooStats/HistFactory/EstimateSummary.h"
+
+#include "RooWorkspace.h"
+#include "RooPlot.h"
+#include "TFile.h"
 
 namespace RooStats{
   namespace HistFactory{
@@ -10,12 +20,12 @@ namespace RooStats{
     RooWorkspace* MakeModelAndMeasurementFast( RooStats::HistFactory::Measurement& measurement );
     //RooWorkspace* MakeModelFast( RooStats::HistFactory::Measurement& measurement );
 
-    std::vector<EstimateSummary> GetChannelEstimateSummaries(RooStats::HistFactory::Measurement& measurement, RooStats::HistFactory::Channel& channel);
+    std::vector<RooStats::HistFactory::EstimateSummary> GetChannelEstimateSummaries(RooStats::HistFactory::Measurement& measurement, RooStats::HistFactory::Channel& channel);
     // void ConfigureWorkspaceForMeasurement( const std::string&, RooWorkspace*, RooStats::HistFactory::Measurement&);
 
-    void FormatFrameForLikelihood(RooPlot* frame, string XTitle=string("#sigma / #sigma_{SM}"), string YTitle=string("-log likelihood"));
-    void FitModel(RooWorkspace *, string data_name="obsData");
-    void FitModelAndPlot(const std::string& MeasurementName, const std::string& FileNamePrefix, RooWorkspace *, string, string, TFile*, FILE*);
+    void FormatFrameForLikelihood(RooPlot* frame, std::string xTitle=std::string("#sigma / #sigma_{SM}"), std::string yTitle=std::string("-log likelihood"));
+    void FitModel(RooWorkspace *, std::string data_name="obsData");
+    void FitModelAndPlot(const std::string& measurementName, const std::string& fileNamePrefix, RooWorkspace *, std::string, std::string, TFile*, FILE*);
   }
 }
 
diff --git a/roofit/histfactory/inc/RooStats/HistFactory/Measurement.h b/roofit/histfactory/inc/RooStats/HistFactory/Measurement.h
index 545c31a..4fbf844 100644
--- a/roofit/histfactory/inc/RooStats/HistFactory/Measurement.h
+++ b/roofit/histfactory/inc/RooStats/HistFactory/Measurement.h
@@ -107,7 +107,7 @@ private:
   int fBinHigh;
 
   bool fExportOnly;
-  bool fSaveExtra;
+  // bool fSaveExtra;
 
   std::string fInterpolationScheme;
   
diff --git a/roofit/histfactory/inc/RooStats/HistFactory/ParamHistFunc.h b/roofit/histfactory/inc/RooStats/HistFactory/ParamHistFunc.h
index 3fab435..cf9bb77 100755
--- a/roofit/histfactory/inc/RooStats/HistFactory/ParamHistFunc.h
+++ b/roofit/histfactory/inc/RooStats/HistFactory/ParamHistFunc.h
@@ -59,7 +59,7 @@ public:
   const RooArgSet* get(Int_t masterIdx) const { return _dataSet.get( masterIdx ) ; } 
   const RooArgSet* get(const RooArgSet& coord) const { return _dataSet.get( coord ) ; } 
 
-
+  double binVolume() const { return _dataSet.binVolume(); }
 
   virtual Bool_t forceAnalyticalInt(const RooAbsArg&) const { return kTRUE ; }
 
diff --git a/roofit/histfactory/inc/RooStats/HistFactory/RooBarlowBeestonLL.h b/roofit/histfactory/inc/RooStats/HistFactory/RooBarlowBeestonLL.h
new file mode 100644
index 0000000..5bfa514
--- /dev/null
+++ b/roofit/histfactory/inc/RooStats/HistFactory/RooBarlowBeestonLL.h
@@ -0,0 +1,137 @@
+/*****************************************************************************
+ * Project: RooFit                                                           *
+ *                                                                           *
+ * Copyright (c) 2000-2005, Regents of the University of California          *
+ *                          and Stanford University. All rights reserved.    *
+ *                                                                           *
+ * Redistribution and use in source and binary forms,                        *
+ * with or without modification, are permitted according to the terms        *
+ * listed in LICENSE (http://roofit.sourceforge.net/license.txt)             *
+ *****************************************************************************/
+
+#ifndef ROOBARLOWBEESTONLL
+#define ROOBARLOWBEESTONLL
+
+#include "RooAbsReal.h"
+#include "RooRealProxy.h"
+#include "RooSetProxy.h"
+#include <map>
+#include <set>
+#include <string>
+
+class RooMinuit ;
+
+namespace RooStats{
+  namespace HistFactory{
+
+class RooBarlowBeestonLL : public RooAbsReal {
+public:
+
+  RooBarlowBeestonLL() ;
+  RooBarlowBeestonLL(const char *name, const char *title, RooAbsReal& nll /*, const RooArgSet& observables*/);
+  RooBarlowBeestonLL(const RooBarlowBeestonLL& other, const char* name=0) ;
+  virtual TObject* clone(const char* newname) const { return new RooBarlowBeestonLL(*this,newname); }
+  virtual ~RooBarlowBeestonLL() ;
+
+  // A simple class to store the 
+  // necessary objects for a 
+  // single gamma in a single channel
+  class BarlowCache {
+  public:
+    BarlowCache() : hasStatUncert(false), gamma(NULL), 
+		    observables(NULL), bin_center(NULL), 
+		    tau(NULL), nom_pois_mean(NULL),
+		    sumPdf(NULL),  nData(-1) {}
+    bool hasStatUncert;
+    RooRealVar* gamma;
+    RooArgSet* observables;
+    RooArgSet* bin_center; // Snapshot
+    RooRealVar* tau;
+    RooAbsReal* nom_pois_mean;
+    RooAbsReal* sumPdf;
+    double nData;
+    double binVolume;
+    void SetBinCenter() const;
+    /*
+    // Restore original values and constant status of observables
+    TIterator* iter = obsSetOrig->createIterator() ;
+    RooRealVar* var ;
+    while((var=(RooRealVar*)iter->Next())) {
+    RooRealVar* target = (RooRealVar*) _obs.find(var->GetName()) ;
+    target->setVal(var->getVal()) ;
+    target->setConstant(var->isConstant()) ;
+    }
+     */
+
+  };
+  
+
+  void initializeBarlowCache();
+
+  RooArgSet* getParameters(const RooArgSet* depList, Bool_t stripDisconnected=kTRUE) const;
+
+  // void setAlwaysStartFromMin(Bool_t flag) { _startFromMin = flag ; }
+  // Bool_t alwaysStartFromMin() const { return _startFromMin ; }
+
+  //RooMinuit* minuit() { return _minuit ; }
+  RooAbsReal& nll() { return const_cast<RooAbsReal&>(_nll.arg()) ; }
+  // const RooArgSet& bestFitParams() const ;
+  // const RooArgSet& bestFitObs() const ;
+
+  //  virtual RooAbsReal* createProfile(const RooArgSet& paramsOfInterest) ;
+  
+  virtual Bool_t redirectServersHook(const RooAbsCollection& /*newServerList*/, Bool_t /*mustReplaceAll*/, Bool_t /*nameChange*/, Bool_t /*isRecursive*/) ;
+
+  // void clearAbsMin() { _absMinValid = kFALSE ; }
+
+  // Int_t numEval() const { return _neval ; }
+
+  void setPdf(RooAbsPdf* pdf) { _pdf = pdf; }
+  void setDataset(RooAbsData* data) { _data = data; }
+  
+  //void FactorizePdf(const RooArgSet &observables, RooAbsPdf &pdf, 
+  //	    RooArgList &obsTerms, RooArgList &constraints) const;
+
+
+protected:
+
+  // void validateAbsMin() const ;
+
+
+  RooRealProxy _nll ;    // Input -log(L) function
+  /*
+  RooSetProxy _obs ;     // Parameters of profile likelihood
+  RooSetProxy _par ;     // Marginialized parameters of likelihood
+  */
+  RooAbsPdf* _pdf;
+  RooAbsData* _data;
+  mutable std::map< std::string, std::vector< BarlowCache > > _barlowCache;
+  mutable std::set< std::string > _statUncertParams;
+  // Bool_t _startFromMin ; // Always start minimization for global minimum?
+
+  /*
+  TIterator* _piter ; //! Iterator over profile likelihood parameters to be minimized 
+  TIterator* _oiter ; //! Iterator of profile likelihood output parameter(s)
+  */
+
+  // mutable RooMinuit* _minuit ; //! Internal minuit instance
+
+  // mutable Bool_t _absMinValid ; // flag if absmin is up-to-date
+  // mutable Double_t _absMin ; // absolute minimum of -log(L)
+  // mutable RooArgSet _paramAbsMin ; // Parameter values at absolute minimum
+  // mutable RooArgSet _obsAbsMin ; // Observable values at absolute minimum
+  mutable std::map<std::string,bool> _paramFixed ; // Parameter constant status at last time of use
+  // mutable Int_t _neval ; // Number evaluations used in last minimization
+  Double_t evaluate() const ;
+  //Double_t evaluate_bad() const ;
+
+
+private:
+
+  ClassDef(RooStats::HistFactory::RooBarlowBeestonLL,0) // Real-valued function representing a Barlow-Beeston minimized profile likelihood of external (likelihood) function
+};
+
+  }
+}
+ 
+#endif
diff --git a/roofit/histfactory/src/Channel.cxx b/roofit/histfactory/src/Channel.cxx
index f422582..8b491c2 100644
--- a/roofit/histfactory/src/Channel.cxx
+++ b/roofit/histfactory/src/Channel.cxx
@@ -7,8 +7,6 @@
 #include "RooStats/HistFactory/HistFactoryException.h"
 #include "RooStats/HistFactory/Channel.h"
 
-
-
 RooStats::HistFactory::Channel::Channel() :
   fName( "" ) { ; }
 
@@ -276,7 +274,7 @@ bool RooStats::HistFactory::Channel::CheckHistograms() {
   
     if( fData.GetHisto() == NULL ) {
       std::cout << "Error: Data Histogram for channel " << GetName() << " is NULL." << std::endl;
-      throw bad_hf;
+      throw hf_exc();
     }
 
     // Get the histograms for the samples:
@@ -287,14 +285,14 @@ bool RooStats::HistFactory::Channel::CheckHistograms() {
       // Get the nominal histogram:
       if( sample.GetHisto() == NULL ) {
 	std::cout << "Error: Nominal Histogram for sample " << sample.GetName() << " is NULL." << std::endl;
-	throw bad_hf;
+	throw hf_exc();
       }
 
       // Get the StatError Histogram (if necessary)
       if( sample.GetStatError().GetUseHisto() ) {
 	if( sample.GetStatError().GetErrorHist() == NULL ) {
 	  std::cout << "Error: Statistical Error Histogram for sample " << sample.GetName() << " is NULL." << std::endl;
-	  throw bad_hf;
+	  throw hf_exc();
 	}
       }
 
@@ -307,12 +305,12 @@ bool RooStats::HistFactory::Channel::CheckHistograms() {
 	if( histoSys.GetHistoLow() == NULL ) {
 	  std::cout << "Error: HistoSyst Low for Systematic " << histoSys.GetName() 
 		    << " in sample " << sample.GetName() << " is NULL." << std::endl;
-	  throw bad_hf;
+	  throw hf_exc();
 	}
 	if( histoSys.GetHistoHigh() == NULL ) {
 	  std::cout << "Error: HistoSyst High for Systematic " << histoSys.GetName() 
 		    << " in sample " << sample.GetName() << " is NULL." << std::endl;
-	  throw bad_hf;
+	  throw hf_exc();
 	}
 	
       } // End Loop over HistoSys
@@ -326,12 +324,12 @@ bool RooStats::HistFactory::Channel::CheckHistograms() {
 	if( histoFactor.GetHistoLow() == NULL ) {
 	  std::cout << "Error: HistoSyst Low for Systematic " << histoFactor.GetName() 
 		    << " in sample " << sample.GetName() << " is NULL." << std::endl;
-	  throw bad_hf;
+	  throw hf_exc();
 	}
 	if( histoFactor.GetHistoHigh() == NULL ) {
 	  std::cout << "Error: HistoSyst High for Systematic " << histoFactor.GetName() 
 		    << " in sample " << sample.GetName() << " is NULL." << std::endl;
-	  throw bad_hf;
+	  throw hf_exc();
 	}
 
       } // End Loop over HistoFactor
@@ -345,7 +343,7 @@ bool RooStats::HistFactory::Channel::CheckHistograms() {
 	if( shapeSys.GetErrorHist() == NULL ) {
 	  std::cout << "Error: HistoSyst High for Systematic " << shapeSys.GetName() 
 		    << " in sample " << sample.GetName() << " is NULL." << std::endl;
-	  throw bad_hf;
+	  throw hf_exc();
 	}
 
       } // End Loop over ShapeSys
@@ -353,7 +351,7 @@ bool RooStats::HistFactory::Channel::CheckHistograms() {
     } // End Loop over Samples
 
   }
-  catch(exception& e)
+  catch(std::exception& e)
     {
       std::cout << e.what() << std::endl;
       return false;
@@ -382,7 +380,7 @@ TH1* RooStats::HistFactory::Channel::GetHistogram(std::string InputFile, std::st
   TFile* inFile = TFile::Open( InputFile.c_str() );
   if( !inFile ) {
     std::cout << "Error: Unable to open input file: " << InputFile << std::endl;
-    throw bad_hf;
+    throw hf_exc();
   }
 
   std::cout << "Opened input file: " << InputFile << ": " << inFile << std::endl;
@@ -401,16 +399,16 @@ TH1* RooStats::HistFactory::Channel::GetHistogram(std::string InputFile, std::st
   try{
     hist = dynamic_cast<TH1*>( inFile->Get( HistNameFull.c_str() ) );
   }
-  catch(exception& e)
+  catch(std::exception& e)
     {
       std::cout << "Failed to cast object to TH1*" << std::endl;
       std::cout << e.what() << std::endl;
-      throw bad_hf;
+      throw hf_exc();
     }
   if( !hist ) {
     std::cout << "Failed to get histogram: " << HistNameFull
 	      << " in file: " << InputFile << std::endl;
-    throw bad_hf;
+    throw hf_exc();
   }
 
 
@@ -421,7 +419,7 @@ TH1* RooStats::HistFactory::Channel::GetHistogram(std::string InputFile, std::st
     std::cerr << "filename: " << InputFile
 	      << "path: " << HistoPath
 	      << "obj: " << HistoName << std::endl;
-    throw bad_hf;
+    throw hf_exc();
   }
   else {
     ptr->SetDirectory(0); //         for the current histogram h
diff --git a/roofit/histfactory/src/ConfigParser.cxx b/roofit/histfactory/src/ConfigParser.cxx
index 73302fc..19a66b2 100644
--- a/roofit/histfactory/src/ConfigParser.cxx
+++ b/roofit/histfactory/src/ConfigParser.cxx
@@ -29,7 +29,7 @@
 using namespace RooStats;
 using namespace HistFactory;
 
-
+using namespace std;
 
 std::vector< RooStats::HistFactory::Measurement > ConfigParser::GetMeasurementsFromXML( string input ) {
  
@@ -63,7 +63,7 @@ std::vector< RooStats::HistFactory::Measurement > ConfigParser::GetMeasurementsF
     // Check that it is the proper DOCTYPE
     if( rootNode->GetNodeName() != TString( "Combination" ) ){
       std::cout << "Error: Driver DOCTYPE not equal to 'Combination'" << std::endl;
-      throw bad_hf;
+      throw hf_exc();
     }
 
     // Loop over the Combination's attributes
@@ -79,7 +79,7 @@ std::vector< RooStats::HistFactory::Measurement > ConfigParser::GetMeasurementsF
 
       if( attrName == TString( "" ) ) {
 	std::cout << " Error: Attribute for 'Combination' with no name found" << std::endl;
-	throw bad_hf;
+	throw hf_exc();
       }
 
       else if( attrName == TString( "OutputFilePrefix" ) ) {
@@ -96,7 +96,7 @@ std::vector< RooStats::HistFactory::Measurement > ConfigParser::GetMeasurementsF
       else {
 	std::cout << " Error: Unknown attribute for 'Combination' encountered: " 
 		  << attrName << std::endl;
-	throw bad_hf;
+	throw hf_exc();
       }
 
       // node = node->GetNextNode();
@@ -112,6 +112,11 @@ std::vector< RooStats::HistFactory::Measurement > ConfigParser::GetMeasurementsF
     node = rootNode->GetChildren();
     while( node != 0 ) {
       if( node->GetNodeName() == TString( "Input" ) ) {
+	if( node->GetText() == NULL ) {
+	  std::cout << "Error: node: " << node->GetName() 
+		    << " has no text." << std::endl;
+	  throw hf_exc();
+	}
 	xml_channel_files.push_back(node->GetText());
       }
       node = node->GetNextNode();
@@ -120,8 +125,8 @@ std::vector< RooStats::HistFactory::Measurement > ConfigParser::GetMeasurementsF
     // If no channel xml files are found, exit
     if(xml_channel_files.empty()){
       cerr << "no input channels found" << endl;
-      throw bad_hf;
-      return measurement_list;
+      throw hf_exc();
+      //return measurement_list;
     }
     else {
       std::cout << "Found Channels: ";
@@ -159,7 +164,7 @@ std::vector< RooStats::HistFactory::Measurement > ConfigParser::GetMeasurementsF
 
       if( node->GetNodeName() == TString( "" ) ) {
 	std::cout << "Error: Node found in Measurement Driver XML with no name" << std::endl;
-	throw bad_hf;
+	throw hf_exc();
       }
 
       else if( node->GetNodeName() == TString( "Measurement" ) ) {
@@ -184,7 +189,7 @@ std::vector< RooStats::HistFactory::Measurement > ConfigParser::GetMeasurementsF
       else {
 	std::cout << "Error: Unknown node found in Measurement Driver XML: "
 		  << node->GetNodeName() << std::endl;
-	throw bad_hf;
+	throw hf_exc();
       }
 
       node = node->GetNextNode();
@@ -195,7 +200,7 @@ std::vector< RooStats::HistFactory::Measurement > ConfigParser::GetMeasurementsF
 
     if( measurement_list.size() == 0 ) {
       std::cout << "Error: No Measurements found in XML Driver File" << std::endl;
-      throw bad_hf;
+      throw hf_exc();
     }
     else {
       std::cout << "Found Measurements: ";
@@ -248,10 +253,10 @@ std::vector< RooStats::HistFactory::Measurement > ConfigParser::GetMeasurementsF
 
 
   }
-  catch(exception& e)
+  catch(std::exception& e)
     {
       std::cout << e.what() << std::endl;
-      throw bad_hf;
+      throw hf_exc();
     }
 
 
@@ -293,7 +298,7 @@ void ConfigParser::FillMeasurementsAndChannelsFromXML(string input,
   // Check that it is the proper DOCTYPE
   if( rootNode->GetNodeName() != TString( "Combination" ) ){
     std::cout << "Error: Driver DOCTYPE not equal to 'Combination'" << std::endl;
-    throw bad_hf;
+    throw hf_exc();
   }
 
   // Loop over the Combination's attributes
@@ -309,7 +314,7 @@ void ConfigParser::FillMeasurementsAndChannelsFromXML(string input,
 
       if( attrName == TString( "" ) ) {
 	std::cout << " Error: Attribute for 'Combination' with no name found" << std::endl;
-	throw bad_hf;
+	throw hf_exc();
       }
 
       else if( attrName == TString( "OutputFilePrefix" ) ) {
@@ -326,7 +331,7 @@ void ConfigParser::FillMeasurementsAndChannelsFromXML(string input,
       else {
 	std::cout << " Error: Unknown attribute for 'Combination' encountered: " 
 		  << attrName << std::endl;
-	throw bad_hf;
+	throw hf_exc();
       }
 
       // node = node->GetNextNode();
@@ -378,7 +383,7 @@ void ConfigParser::FillMeasurementsAndChannelsFromXML(string input,
 
     if( node->GetNodeName() == TString( "" ) ) {
       std::cout << "Error: Node found in Measurement Driver XML with no name" << std::endl;
-      throw bad_hf;
+      throw hf_exc();
     }
 
     else if( node->GetNodeName() == TString( "Measurement" ) ) {
@@ -403,7 +408,7 @@ void ConfigParser::FillMeasurementsAndChannelsFromXML(string input,
     else {
       std::cout << "Error: Unknown node found in Measurement Driver XML: "
 		<< node->GetNodeName() << std::endl;
-      throw bad_hf;
+      throw hf_exc();
     }
 
     node = node->GetNextNode();
@@ -414,7 +419,7 @@ void ConfigParser::FillMeasurementsAndChannelsFromXML(string input,
 
   if( measurement_list.size() == 0 ) {
     std::cout << "Error: No Measurements found in XML Driver File" << std::endl;
-    throw bad_hf;
+    throw hf_exc();
   }
   else {
     std::cout << "Found Measurements: ";
@@ -623,7 +628,7 @@ HistFactory::Measurement ConfigParser::CreateMeasurementFromDriverNode( TXMLNode
     if( curAttr->GetName() == TString( "" ) ) {
       std::cout << "Found XML attribute in Measurement with no name"  << std::endl;
       // ADD Output Here
-      throw bad_hf;
+      throw hf_exc();
     }
     else if( curAttr->GetName() == TString( "Name" ) ) {
       //rowTitle=curAttr->GetValue();
@@ -652,7 +657,7 @@ HistFactory::Measurement ConfigParser::CreateMeasurementFromDriverNode( TXMLNode
     else {
       std::cout << "Found unknown XML attribute in Measurement: " << curAttr->GetName()
 		<< std::endl;
-      throw bad_hf;
+      throw hf_exc();
     }
 
   } // End Loop over attributes
@@ -665,10 +670,15 @@ HistFactory::Measurement ConfigParser::CreateMeasurementFromDriverNode( TXMLNode
   
     if( child->GetNodeName() == TString( "" ) ) {
       std::cout << "Found XML child node of Measurement with no name"  << std::endl;
-      throw bad_hf;
+      throw hf_exc();
     }
 
     else if( child->GetNodeName() == TString( "POI" ) ) {
+      if( child->GetText() == NULL ) {
+	std::cout << "Error: node: " << child->GetName() 
+		  << " has no text." << std::endl;
+	throw hf_exc();
+      }
       measurement.SetPOI( child->GetText() );
     }
 
@@ -679,6 +689,11 @@ HistFactory::Measurement ConfigParser::CreateMeasurementFromDriverNode( TXMLNode
 	if( curParam->GetName() == TString( "Const" ) ) {
 	  if(curParam->GetValue()==TString("True")){
 	    // Fix here...?
+	    if( child->GetText() == NULL ) {
+	      std::cout << "Error: node: " << child->GetName() 
+			<< " has no text." << std::endl;
+	      throw hf_exc();
+	    }
 	    AddSubStrings( measurement.GetConstantParams(), child->GetText() );
 	  }
 	}
@@ -695,6 +710,11 @@ HistFactory::Measurement ConfigParser::CreateMeasurementFromDriverNode( TXMLNode
       map<string,double> logNormSyst;
 
       // Get the list of parameters in this tag:
+      if( child->GetText() == NULL ) {
+	std::cout << "Error: node: " << child->GetName() 
+		  << " has no text." << std::endl;
+	throw hf_exc();
+      }
       AddSubStrings(syst, child->GetText());
 
       // Now, loop over this tag's attributes
@@ -704,7 +724,7 @@ HistFactory::Measurement ConfigParser::CreateMeasurementFromDriverNode( TXMLNode
 
 	if( curAttr->GetName() == TString( "" ) ) {
 	  std::cout << "Error: Found tag attribute with no name in ConstraintTerm" << std::endl;
-	  throw bad_hf;
+	  throw hf_exc();
 	}
 
 	else if( curAttr->GetName() == TString( "Type" ) ) {
@@ -718,7 +738,7 @@ HistFactory::Measurement ConfigParser::CreateMeasurementFromDriverNode( TXMLNode
 	else {
 	  std::cout << "Found tag attribute with unknown name in ConstraintTerm: "
 		    << curAttr->GetName() << std::endl;
-	  throw bad_hf;
+	  throw hf_exc();
 	}
 
       } // End Loop over tag attributes
@@ -730,7 +750,7 @@ HistFactory::Measurement ConfigParser::CreateMeasurementFromDriverNode( TXMLNode
       if( ! (type=="Gamma"     || type=="Uniform" || 
 	     type=="LogNormal" || type=="NoConstraint") ) {
 	std::cout << "Error: Encountered unknown type for ConstraintTerm: " << type << std::endl;
-	throw bad_hf;
+	throw hf_exc();
       }
 
 
@@ -770,7 +790,7 @@ HistFactory::Measurement ConfigParser::CreateMeasurementFromDriverNode( TXMLNode
     else {
     std::cout << "Found XML child of Measurement with unknown name: " << child->GetNodeName()
 		<< std::endl;
-      throw bad_hf;
+      throw hf_exc();
     }
 
     child = child->GetNextNode();
@@ -830,7 +850,7 @@ HistFactory::Channel ConfigParser::ReadXmlConfig( string filen, Double_t lumi )
   if( rootNode->GetNodeName() == TString( "" ) ){
 
     std::cout << "Error: Encounterd XML with no DOCTYPE" << std::endl;
-    throw bad_hf;
+    throw hf_exc();
 
   }
 
@@ -853,7 +873,7 @@ HistFactory::Channel ConfigParser::ReadXmlConfig( string filen, Double_t lumi )
   else {
     std::cout << "Found XML file with unknown DOCTYPE: " << rootNode->GetNodeName()
 	      << std::endl;
-    throw bad_hf;
+    throw hf_exc();
   }
 
 
@@ -892,7 +912,7 @@ HistFactory::Channel ConfigParser::ParseChannelXMLFile( string filen ) {
 	      << std::endl;
     std::cout << " DOCTYPE for channels must be 'Channel' "
 	      << " Check that your XML is properly written" << std::endl;
-    throw bad_hf;
+    throw hf_exc();
   }
 
   // Now, create the channel, 
@@ -915,7 +935,7 @@ HistFactory::Channel ConfigParser::ParseChannelXMLFile( string filen ) {
 
     if( attrName == TString( "" ) ) {
       std::cout << " Error: Attribute for 'Channel' with no name found" << std::endl;
-      throw bad_hf;
+      throw hf_exc();
     }
 
     else if( attrName == TString( "Name" ) ) {
@@ -946,7 +966,7 @@ HistFactory::Channel ConfigParser::ParseChannelXMLFile( string filen ) {
     else {
       std::cout << " Error: Unknown attribute for 'Channel' encountered: " 
 		<< attrName << std::endl;
-      throw bad_hf;
+      throw hf_exc();
     }
 
 
@@ -957,7 +977,7 @@ HistFactory::Channel ConfigParser::ParseChannelXMLFile( string filen ) {
   
   if( channel.GetName() == "" ) {
     std::cout << "Error: Channel created with no name" << std::endl;
-    throw bad_hf;
+    throw hf_exc();
   }
 
   m_currentChannel = channel.GetName();
@@ -971,7 +991,7 @@ HistFactory::Channel ConfigParser::ParseChannelXMLFile( string filen ) {
 
     if( node->GetNodeName() == TString( "" ) ) {
       std::cout << "Error: Encountered node in Channel with no name" << std::endl;
-      throw bad_hf;
+      throw hf_exc();
     }
 
     else if( node->GetNodeName() == TString( "Data" ) ) {
@@ -990,7 +1010,7 @@ HistFactory::Channel ConfigParser::ParseChannelXMLFile( string filen ) {
 
     else {
       std::cout << "Error: Encountered node in Channel with unknown name: " << node->GetNodeName() << std::endl;
-      throw bad_hf;
+      throw hf_exc();
     }
 
     node = node->GetNextNode();
@@ -1321,7 +1341,7 @@ HistFactory::Data ConfigParser::CreateDataElement( TXMLNode* node ) {
 
       if( attrName == TString( "" ) ) {
 	std::cout << " Error: Attribute for 'Data' with no name found" << std::endl;
-	throw bad_hf;
+	throw hf_exc();
       }
 
       else if( attrName == TString( "InputFile" ) ) {
@@ -1340,7 +1360,7 @@ HistFactory::Data ConfigParser::CreateDataElement( TXMLNode* node ) {
 
       else {
 	std::cout << " Error: Unknown attribute for 'Data' encountered: " << attrName << std::endl;
-	throw bad_hf;
+	throw hf_exc();
       }
 
     }
@@ -1348,11 +1368,11 @@ HistFactory::Data ConfigParser::CreateDataElement( TXMLNode* node ) {
     // Check the properties of the data node:
     if( data.GetInputFile() == "" ) {
       std::cout << "Error: Data Node has no InputFile" << std::endl;
-      throw bad_hf;
+      throw hf_exc();
     }
     if( data.GetHistoName() == "" ) {
       std::cout << "Error: Data Node has no HistoName" << std::endl;
-      throw bad_hf;
+      throw hf_exc();
     }
 
     std::cout << "Created Data Node with"
@@ -1398,7 +1418,7 @@ HistFactory::StatErrorConfig ConfigParser::CreateStatErrorConfigElement( TXMLNod
 
       if( attrVal == "" ) {
 	std::cout << "Error: Bad Value for StatErrorConfig Constraint Type Found" << std::endl;
-	throw bad_hf;
+	throw hf_exc();
       }
 
       else if( attrVal=="Gaussian" || attrVal=="Gauss"  ) {  
@@ -1413,7 +1433,7 @@ HistFactory::StatErrorConfig ConfigParser::CreateStatErrorConfigElement( TXMLNod
 
       else {
 	cout << "Invalid Stat Constraint Type: " << curAttr->GetValue() << endl;
-	throw bad_hf;
+	throw hf_exc();
       }
 
     }
@@ -1455,7 +1475,7 @@ HistFactory::Sample ConfigParser::CreateSampleElement( TXMLNode* node ) {
 
     if( attrName == TString( "" ) ) {
       std::cout << " Error: Attribute for 'Sample' with no name found" << std::endl;
-      throw bad_hf;
+      throw hf_exc();
     }
 
     else if( attrName == TString( "Name" ) ) {
@@ -1479,21 +1499,21 @@ HistFactory::Sample ConfigParser::CreateSampleElement( TXMLNode* node ) {
       /*
 	if( attrVal == "" ) {
 	std::cout << "Error: Attribute 'NormalizeByTheory' in Sample has no value" << std::endl;
-	throw bad_hf;
+	throw hf_exc();
 	}
 	else if ( attrVal == "True"  || attrVal == "true"  )   sample.NormalizeByTheory = true;
 	else if ( attrVal == "False" || attrVal == "false" )   sample.NormalizeByTheory = false;
 	else {
 	std::cout << "Error: Attribute 'NormalizeByTheory' in Sample has unknown value: " << attrVal <<  std::endl;
 	std::cout << "Value must be 'True' or 'False' " <<  std::endl;
-	throw bad_hf;
+	throw hf_exc();
 	}
       */
     }
 
     else {
       std::cout << " Error: Unknown attribute for 'Sample' encountered: " << attrName << std::endl;
-      throw bad_hf;
+      throw hf_exc();
     }
 
   }
@@ -1501,15 +1521,15 @@ HistFactory::Sample ConfigParser::CreateSampleElement( TXMLNode* node ) {
   // Quickly check the properties of the Sample Node
   if( sample.GetName() == "" ) {
     std::cout << "Error: Sample Node has no Name" << std::endl;
-    throw bad_hf;
+    throw hf_exc();
   }
   if( sample.GetInputFile() == "" ) {
     std::cout << "Error: Sample Node has no InputFile" << std::endl;
-    throw bad_hf;
+    throw hf_exc();
   }
   if( sample.GetHistoName() == "" ) {
     std::cout << "Error: Sample Node has no HistoName" << std::endl;
-    throw bad_hf;
+    throw hf_exc();
   }
 
 
@@ -1521,7 +1541,7 @@ HistFactory::Sample ConfigParser::CreateSampleElement( TXMLNode* node ) {
       
     if( child->GetNodeName() == TString( "" ) ) {
       std::cout << "Error: Encountered node in Sample with no name" << std::endl;
-      throw bad_hf;
+      throw hf_exc();
     }
 
     else if( child->GetNodeName() == TString( "NormFactor" ) ) {
@@ -1557,7 +1577,7 @@ HistFactory::Sample ConfigParser::CreateSampleElement( TXMLNode* node ) {
 
     else {
       std::cout << "Error: Encountered node in Sample with unknown name: " << child->GetNodeName() << std::endl;
-      throw bad_hf;
+      throw hf_exc();
     }
 
     child=child->GetNextNode();
@@ -1594,7 +1614,7 @@ HistFactory::NormFactor ConfigParser::MakeNormFactor( TXMLNode* node ) {
 
     if( attrName == TString( "" ) ){
       std::cout << "Error: Encountered Element in NormFactor with no name" << std::endl;
-      throw bad_hf;
+      throw hf_exc();
     }
 
     else if( curAttr->GetName() == TString( "Name" ) ) {
@@ -1616,14 +1636,14 @@ HistFactory::NormFactor ConfigParser::MakeNormFactor( TXMLNode* node ) {
     else {
       std::cout << "Error: Encountered Element in NormFactor with unknown name: " 
 		<< attrName << std::endl;
-      throw bad_hf;
+      throw hf_exc();
     }
 
   } // End loop over properties
 
   if( norm.GetName() == "" ) {
     std::cout << "Error: NormFactor Node has no Name" << std::endl;
-    throw bad_hf;
+    throw hf_exc();
   }
 
   norm.Print();
@@ -1684,7 +1704,7 @@ HistFactory::HistoSys ConfigParser::MakeHistoSys( TXMLNode* node ) {
 	
     if( attrName == TString( "" ) ){
       std::cout << "Error: Encountered Element in HistoSys with no name" << std::endl;
-      throw bad_hf;
+      throw hf_exc();
     }
 
     else if( curAttr->GetName() == TString( "Name" ) ) {
@@ -1714,7 +1734,7 @@ HistFactory::HistoSys ConfigParser::MakeHistoSys( TXMLNode* node ) {
     else {
       std::cout << "Error: Encountered Element in HistoSys with unknown name: " 
 		<< attrName << std::endl;
-      throw bad_hf;
+      throw hf_exc();
     }
 
   } // End loop over properties
@@ -1722,23 +1742,23 @@ HistFactory::HistoSys ConfigParser::MakeHistoSys( TXMLNode* node ) {
 
   if( histoSys.GetName() == "" ) {
     std::cout << "Error: HistoSys Node has no Name" << std::endl;
-    throw bad_hf;
+    throw hf_exc();
   }
   if( histoSys.GetInputFileHigh() == "" ) {
     std::cout << "Error: HistoSysSample Node has no InputFileHigh" << std::endl;
-    throw bad_hf;
+    throw hf_exc();
   }
   if( histoSys.GetInputFileLow() == "" ) {
     std::cout << "Error: HistoSysSample Node has no InputFileLow" << std::endl;
-    throw bad_hf;
+    throw hf_exc();
   }
   if( histoSys.GetHistoNameHigh() == "" ) {
     std::cout << "Error: HistoSysSample Node has no HistoNameHigh" << std::endl;
-    throw bad_hf;
+    throw hf_exc();
   }
   if( histoSys.GetHistoNameLow() == "" ) {
     std::cout << "Error: HistoSysSample Node has no HistoNameLow" << std::endl;
-    throw bad_hf;
+    throw hf_exc();
   }
 
 
@@ -1766,7 +1786,7 @@ HistFactory::OverallSys ConfigParser::MakeOverallSys( TXMLNode* node ) {
 
     if( attrName == TString( "" ) ){
       std::cout << "Error: Encountered Element in OverallSys with no name" << std::endl;
-      throw bad_hf;
+      throw hf_exc();
     }
 
     else if( attrName == TString( "Name" ) ) {
@@ -1782,14 +1802,14 @@ HistFactory::OverallSys ConfigParser::MakeOverallSys( TXMLNode* node ) {
     else {
       std::cout << "Error: Encountered Element in OverallSys with unknown name: " 
 		<< attrName << std::endl;
-      throw bad_hf;
+      throw hf_exc();
     }
 
   }
 
   if( overallSys.GetName() == "" ) {
     std::cout << "Error: Encountered OverallSys with no name" << std::endl;
-    throw bad_hf;
+    throw hf_exc();
   }
   
 
@@ -1817,7 +1837,7 @@ HistFactory::ShapeFactor ConfigParser::MakeShapeFactor( TXMLNode* node ) {
 
     if( attrName == TString( "" ) ){
       std::cout << "Error: Encountered Element in ShapeFactor with no name" << std::endl;
-      throw bad_hf;
+      throw hf_exc();
     }
 
     else if( attrName == TString( "Name" ) ) {
@@ -1827,14 +1847,14 @@ HistFactory::ShapeFactor ConfigParser::MakeShapeFactor( TXMLNode* node ) {
     else {
       std::cout << "Error: Encountered Element in ShapeFactor with unknown name: " 
 		<< attrName << std::endl;
-      throw bad_hf;
+      throw hf_exc();
     }
 
   }
 
   if( shapeFactor.GetName() == "" ) {
     std::cout << "Error: Encountered ShapeFactor with no name" << std::endl;
-    throw bad_hf;
+    throw hf_exc();
   }
 
   shapeFactor.Print();
@@ -1868,7 +1888,7 @@ HistFactory::ShapeSys ConfigParser::MakeShapeSys( TXMLNode* node ) {
 
     if( attrName == TString( "" ) ){
       std::cout << "Error: Encountered Element in ShapeSys with no name" << std::endl;
-      throw bad_hf;
+      throw hf_exc();
     }
 
     else if( attrName == TString( "Name" ) ) {
@@ -1890,7 +1910,7 @@ HistFactory::ShapeSys ConfigParser::MakeShapeSys( TXMLNode* node ) {
     else if( attrName == TString( "ConstraintType" ) ) {
       if( attrVal=="" ) {
 	std::cout << "Error: ShapeSys Constraint type is empty" << std::endl;
-	throw bad_hf;
+	throw hf_exc();
       }
       else if( attrVal=="Gaussian" || attrVal=="Gauss" ) {
 	shapeSys.SetConstraintType( Constraint::Gaussian );
@@ -1900,14 +1920,14 @@ HistFactory::ShapeSys ConfigParser::MakeShapeSys( TXMLNode* node ) {
       }
       else {
 	cout << "Error: Encountered unknown ShapeSys Constraint type: " << attrVal << endl;
-	throw bad_hf;
+	throw hf_exc();
       }
     }
 
     else {
       std::cout << "Error: Encountered Element in ShapeSys with unknown name: " 
 		<< attrName << std::endl;
-      throw bad_hf;
+      throw hf_exc();
     }
 
   } // End loop over attributes
@@ -1915,15 +1935,15 @@ HistFactory::ShapeSys ConfigParser::MakeShapeSys( TXMLNode* node ) {
 
   if( shapeSys.GetName() == "" ) {
     std::cout << "Error: Encountered ShapeSys with no Name" << std::endl;
-    throw bad_hf;
+    throw hf_exc();
   }
   if( shapeSys.GetInputFile() == "" ) {
     std::cout << "Error: Encountered ShapeSys with no InputFile" << std::endl;
-    throw bad_hf;
+    throw hf_exc();
   }
   if( shapeSys.GetHistoName() == "" ) {
     std::cout << "Error: Encountered ShapeSys with no HistoName" << std::endl;
-    throw bad_hf;
+    throw hf_exc();
   }
 
   shapeSys.Print();
@@ -1971,7 +1991,7 @@ HistFactory::StatError ConfigParser::ActivateStatError( TXMLNode* node ) {
 
     if( attrName == TString( "" ) ){
       std::cout << "Error: Encountered Element in ActivateStatError with no name" << std::endl;
-      throw bad_hf;
+      throw hf_exc();
     }
     
     else if( attrName == TString( "Activate" ) ) {
@@ -1993,7 +2013,7 @@ HistFactory::StatError ConfigParser::ActivateStatError( TXMLNode* node ) {
     else {
       std::cout << "Error: Encountered Element in ActivateStatError with unknown name: " 
 		<< attrName << std::endl;
-      throw bad_hf;
+      throw hf_exc();
     }
 
   } // End: Loop Over Attributes
@@ -2080,14 +2100,14 @@ bool ConfigParser::CheckTrueFalse( std::string attrVal, std::string NodeTitle )
   if( attrVal == "" ) {
     std::cout << "Error: In " << NodeTitle
 	      << " Expected either 'True' or 'False' but found empty" << std::endl;
-    throw bad_hf;
+    throw hf_exc();
   }
   else if ( attrVal == "True"  || attrVal == "true"  )   return true;
   else if ( attrVal == "False" || attrVal == "false" )   return false;
   else {
     std::cout << "Error: In " << NodeTitle
 	      << " Expected either 'True' or 'False' but found: " << attrVal <<  std::endl;
-    throw bad_hf;
+    throw hf_exc();
   }
 
   return false;
diff --git a/roofit/histfactory/src/FlexibleInterpVar.cxx b/roofit/histfactory/src/FlexibleInterpVar.cxx
index 54a9e18..0175175 100644
--- a/roofit/histfactory/src/FlexibleInterpVar.cxx
+++ b/roofit/histfactory/src/FlexibleInterpVar.cxx
@@ -21,7 +21,6 @@ END_HTML
 #include "RooFit.h"
 
 #include "Riostream.h"
-#include "Riostream.h"
 #include <math.h>
 #include "TMath.h"
 
diff --git a/roofit/histfactory/src/Helper.cxx b/roofit/histfactory/src/Helper.cxx
index 941565e..c96afe5 100644
--- a/roofit/histfactory/src/Helper.cxx
+++ b/roofit/histfactory/src/Helper.cxx
@@ -26,6 +26,8 @@ END_HTML
 #include "RooArgSet.h"
 #include "RooRealVar.h"
 
+using namespace std; 
+
 namespace RooStats{
 namespace HistFactory{
   vector<pair<string, string> > get_comb(vector<string> names){
@@ -302,7 +304,7 @@ std::vector<EstimateSummary> GetChannelEstimateSummaries(Measurement& measuremen
     }
     if( sample.GetShapeFactorList().size() > 1 ) {
       std::cout << "Error: Only One Shape Factor currently supported" << std::endl;
-      throw bad_hf;
+      throw hf_exc();
     }
 
 
diff --git a/roofit/histfactory/src/Helper.h b/roofit/histfactory/src/Helper.h
index 9eb17da..0e76177 100644
--- a/roofit/histfactory/src/Helper.h
+++ b/roofit/histfactory/src/Helper.h
@@ -23,17 +23,16 @@
 #include "RooWorkspace.h"
 
 
-using namespace std; 
 
 namespace RooStats{
 namespace HistFactory{
-  vector<EstimateSummary>*  loadSavedInputs(TFile* outFile, string channel );
-  void saveInputs(TFile* outFile, string channel, vector<EstimateSummary> summaries);
-  TH1 * GetHisto( TFile * inFile, const string name );
-  TH1 * GetHisto( const string file, const string path, const string obj );
-  bool AddSummaries( vector<EstimateSummary> & summary, vector<vector<EstimateSummary> > &master);
-  vector<pair<string, string> > get_comb(vector<string> names);
-  void AddSubStrings( vector<string> & vs, string s);
+  std::vector<EstimateSummary>*  loadSavedInputs(TFile* outFile, std::string channel );
+  void saveInputs(TFile* outFile, std::string channel, std::vector<EstimateSummary> summaries);
+  TH1 * GetHisto( TFile * inFile, const std::string name );
+  TH1 * GetHisto( const std::string file, const std::string path, const std::string obj );
+  bool AddSummaries( std::vector<EstimateSummary> & summary, std::vector<std::vector<EstimateSummary> > &master);
+  std::vector<std::pair<std::string, std::string> > get_comb(std::vector<std::string> names);
+  void AddSubStrings( std::vector<std::string> & vs, std::string s);
 
   std::vector<EstimateSummary> GetChannelEstimateSummaries(Measurement& measurement, Channel& channel);
 
diff --git a/roofit/histfactory/src/HistFactoryModelUtils.cxx b/roofit/histfactory/src/HistFactoryModelUtils.cxx
new file mode 100644
index 0000000..38e97ab
--- /dev/null
+++ b/roofit/histfactory/src/HistFactoryModelUtils.cxx
@@ -0,0 +1,424 @@
+
+// A set of utils for navegating HistFactory models
+#include <stdexcept>    
+#include <typeinfo>
+
+#include "RooStats/HistFactory/ParamHistFunc.h"
+#include "TIterator.h"
+#include "RooAbsArg.h"
+#include "RooAbsPdf.h"
+#include "RooArgSet.h"
+#include "RooArgList.h"
+#include "RooSimultaneous.h"
+#include "RooCategory.h"
+#include "RooRealVar.h"
+#include "RooProdPdf.h"
+#include "TH1.h"
+
+#include "RooStats/HistFactory/HistFactorySimultaneous.h"
+#include "RooStats/HistFactory/HistFactoryModelUtils.h"
+
+namespace RooStats{
+namespace HistFactory{
+
+
+  std::string channelNameFromPdf( RooAbsPdf* channelPdf ) {
+    std::string channelPdfName = channelPdf->GetName();
+    std::string ChannelName = channelPdfName.substr(6, channelPdfName.size() );
+    return ChannelName;
+  }
+
+  RooAbsPdf* getSumPdfFromChannel( RooAbsPdf* sim_channel ) {
+
+    bool verbose=false;
+
+    if(verbose) std::cout << "Getting the RooRealSumPdf for the channel: " 
+			  << sim_channel->GetName() << std::endl;
+
+    std::string channelPdfName = sim_channel->GetName();
+    std::string ChannelName = channelPdfName.substr(6, channelPdfName.size() );
+
+    // Now, get the RooRealSumPdf
+    // ie the channel WITHOUT constraints
+    std::string realSumPdfName = ChannelName + "_model";
+
+    RooAbsPdf* sum_pdf = NULL;        
+    TIterator* iter_sum_pdf = sim_channel->getComponents()->createIterator(); //serverIterator();
+    bool FoundSumPdf=false;
+    RooAbsArg* sum_pdf_arg=NULL;
+    while((sum_pdf_arg=(RooAbsArg*)iter_sum_pdf->Next())) {
+      std::string NodeClassName = sum_pdf_arg->ClassName();
+      if( NodeClassName == std::string("RooRealSumPdf") ) {
+	FoundSumPdf=true;
+	sum_pdf = (RooAbsPdf*) sum_pdf_arg;
+	break;
+      }
+    }
+    if( ! FoundSumPdf ) {
+      if(verbose) {
+	std::cout << "Failed to find RooRealSumPdf for channel: " << sim_channel->GetName() << std::endl;
+	sim_channel->getComponents()->Print("V");
+      }
+      sum_pdf=NULL;
+      //throw std::runtime_error("Failed to find RooRealSumPdf for channel");
+    } 
+    else {
+      if(verbose) std::cout << "Found RooRealSumPdf: " << sum_pdf->GetName() << std::endl;
+    }
+    delete iter_sum_pdf;
+    iter_sum_pdf = NULL;
+
+    return sum_pdf;
+
+  }
+
+
+ void FactorizeHistFactoryPdf(const RooArgSet &observables, RooAbsPdf &pdf, RooArgList &obsTerms, RooArgList &constraints) {
+   // utility function to factorize constraint terms from a pdf 
+   // (from G. Petrucciani)
+   const std::type_info & id = typeid(pdf);
+   if (id == typeid(RooProdPdf)) {
+      RooProdPdf *prod = dynamic_cast<RooProdPdf *>(&pdf);
+      RooArgList list(prod->pdfList());
+      for (int i = 0, n = list.getSize(); i < n; ++i) {
+         RooAbsPdf *pdfi = (RooAbsPdf *) list.at(i);
+            FactorizeHistFactoryPdf(observables, *pdfi, obsTerms, constraints);
+         }
+      } else if (id == typeid(RooSimultaneous) || id == typeid(HistFactorySimultaneous) ) {    //|| id == typeid(RooSimultaneousOpt)) {
+         RooSimultaneous *sim  = dynamic_cast<RooSimultaneous *>(&pdf);
+         RooAbsCategoryLValue *cat = (RooAbsCategoryLValue *) sim->indexCat().Clone();
+         for (int ic = 0, nc = cat->numBins((const char *)0); ic < nc; ++ic) {
+            cat->setBin(ic);
+            FactorizeHistFactoryPdf(observables, *sim->getPdf(cat->getLabel()), obsTerms, constraints);
+         }
+         delete cat;
+      } else if (pdf.dependsOn(observables)) {
+         if (!obsTerms.contains(pdf)) obsTerms.add(pdf);
+      } else {
+         if (!constraints.contains(pdf)) constraints.add(pdf);
+      }
+   }
+
+  /*
+  void getChannelsFromModel( RooAbsPdf* model, RooArgSet* channels, RooArgSet* channelsWithConstraints ) {
+
+    // Loop through the model
+    // Find all channels
+
+    std::string modelClassName = model->ClassName();
+    
+    if( modelClassName == std::string("RooSimultaneous") || model->InheritsFrom("RooSimultaneous") ) {
+
+      TIterator* simServerItr = model->serverIterator();
+
+      // Loop through the child nodes of the sim pdf
+      // and find the channel nodes
+      RooAbsArg* sim_channel_arg = NULL;
+      while(( sim_channel = (RooAbsArg*) simServerItr->Next() )) {
+
+	RooAbsPdf* sim_channel = (RooAbsPdf*) sim_channel_arg;
+
+	// Ignore the Channel Cat
+	std::string channelPdfName = sim_channel->GetName();
+	std::string channelClassName = sim_channel->ClassName();
+	if( channelClassName == std::string("RooCategory") ) continue;
+
+	// If we got here, we found a channel.
+	// Format is model_<ChannelName>
+
+	std::string ChannelName = channelPdfName.substr(6, channelPdfName.size() );
+
+	// Now, get the RooRealSumPdf
+	RooAbsPdf* sum_pdf = getSumPdfFromChannel( sim_channel );
+	
+	
+	/ *
+	// Now, get the RooRealSumPdf
+	// ie the channel WITHOUT constraints
+
+	std::string realSumPdfName = ChannelName + "_model";
+
+	RooAbsPdf* sum_pdf = NULL;        
+	TIterator* iter_sum_pdf = sim_channel->getComponents()->createIterator(); //serverIterator();
+	bool FoundSumPdf=false;
+	RooAbsArg* sum_pdf_arg=NULL;
+	while((sum_pdf_arg=(RooAbsArg*)iter_sum_pdf->Next())) {
+
+	  std::string NodeClassName = sum_pdf_arg->ClassName();
+	  if( NodeClassName == std::string("RooRealSumPdf") ) {
+	    FoundSumPdf=true;
+	    sum_pdf = (RooAbsPdf*) sum_pdf_arg;
+	    break;
+	  }
+	}
+	if( ! FoundSumPdf ) {
+	  std::cout << "Failed to find RooRealSumPdf for channel: " << sim_channel->GetName() << std::endl;
+	  sim_channel->getComponents()->Print("V");
+	  throw std::runtime_error("Failed to find RooRealSumPdf for channel");
+	}                                                  
+	delete iter_sum_pdf;
+	iter_sum_pdf = NULL;
+	* /
+
+	// Okay, now add to the arg sets
+	channels->add( *sum_pdf );
+	channelsWithConstraints->add( *sim_channel );
+
+      }
+
+      delete simServerItr;
+
+    }
+    else {
+      std::cout << "Model is not a RooSimultaneous or doesn't derive from one." << std::endl;
+      std::cout << "HistFactoryModelUtils isn't yet implemented for these pdf's" << std::endl;
+    }
+
+  }
+  */
+
+  bool getStatUncertaintyFromChannel( RooAbsPdf* channel, ParamHistFunc*& paramfunc, RooArgList* gammaList ) {
+
+    bool verbose=false;
+
+    // Find the servers of this channel
+    //TIterator* iter = channel->serverIterator();
+    TIterator* iter = channel->getComponents()->createIterator(); //serverIterator();
+    bool FoundParamHistFunc=false;
+    RooAbsArg* paramfunc_arg = NULL;        
+    while(( paramfunc_arg = (RooAbsArg*) iter->Next() )) {
+      std::string NodeName = paramfunc_arg->GetName();
+      std::string NodeClassName = paramfunc_arg->ClassName();
+      if( NodeClassName != std::string("ParamHistFunc") ) continue;
+      if( NodeName.find("mc_stat_") != std::string::npos ) {
+	FoundParamHistFunc=true;
+	paramfunc = (ParamHistFunc*) paramfunc_arg;
+	break;
+      }
+    }
+    if( ! FoundParamHistFunc || !paramfunc ) {
+      if(verbose) std::cout << "Failed to find ParamHistFunc for channel: " << channel->GetName() << std::endl;
+      return false;
+    }                                               
+    
+    delete iter;
+    iter = NULL;
+
+    // Now, get the set of gamma's
+    gammaList = (RooArgList*) &( paramfunc->paramList());
+    if(verbose) gammaList->Print("V");
+
+    return true;
+
+  }
+  
+
+  void getDataValuesForObservables( std::map< std::string, std::vector<double> >& ChannelBinDataMap,
+				    RooAbsData* data, RooAbsPdf* pdf ) {
+
+    bool verbose=false;
+
+    //std::map< std::string, std::vector<int>  ChannelBinDataMap;
+
+    RooSimultaneous* simPdf = (RooSimultaneous*) pdf;
+
+    // get category label
+    RooArgSet* allobs = (RooArgSet*) data->get();
+    TIterator* obsIter = allobs->createIterator();
+    RooCategory* cat = NULL;
+    RooAbsArg* temp = NULL;
+    while( (temp=(RooAbsArg*) obsIter->Next())) {
+      // use dynamic cast here instead
+      if( strcmp(temp->ClassName(),"RooCategory")==0){
+	cat = (RooCategory*) temp;
+	break;
+      }
+    }
+    if(verbose) {
+      if(!cat) std::cout <<"didn't find category"<< std::endl;
+      else std::cout <<"found category"<< std::endl;
+    }
+    delete obsIter;
+
+    // split dataset
+    TList* dataByCategory = data->split(*cat);
+    if(verbose) dataByCategory->Print();
+    // note :
+    // RooAbsData* dataForChan = (RooAbsData*) dataByCategory->FindObject("");
+
+    // loop over channels
+    RooCategory* channelCat = (RooCategory*) (&simPdf->indexCat());
+    TIterator* iter = channelCat->typeIterator() ;
+    RooCatType* tt = NULL;
+    while((tt=(RooCatType*) iter->Next())) {
+
+      // Get pdf associated with state from simpdf
+      RooAbsPdf* pdftmp = simPdf->getPdf(tt->GetName()) ;
+
+      std::string ChannelName = pdftmp->GetName(); //tt->GetName();
+      if(verbose) std::cout << "Getting data for channel: " << ChannelName << std::endl;
+      ChannelBinDataMap[ ChannelName ] = std::vector<double>();
+
+      RooAbsData* dataForChan = (RooAbsData*) dataByCategory->FindObject(tt->GetName());
+      if(verbose) dataForChan->Print();
+
+      // Generate observables defined by the pdf associated with this state
+      RooArgSet* obstmp = pdftmp->getObservables(*dataForChan->get()) ;   
+      RooRealVar* obs = ((RooRealVar*)obstmp->first());
+      if(verbose) obs->Print();
+
+      //double expected = pdftmp->expectedEvents(*obstmp);
+
+      // set value to desired value (this is just an example)
+      // double obsVal = obs->getVal();
+      // set obs to desired value of observable
+      // obs->setVal( obsVal );
+      //double fracAtObsValue = pdftmp->getVal(*obstmp);
+
+      // get num events expected in bin for obsVal
+      // double nu = expected * fracAtObsValue;
+      
+      // an easier way to get n
+      TH1* histForN = dataForChan->createHistogram("HhstForN",*obs);
+      for(int i=1; i<=histForN->GetNbinsX(); ++i){
+	double n = histForN->GetBinContent(i);
+	if(verbose) std::cout << "n" <<  i << " = " << n  << std::endl;
+	ChannelBinDataMap[ ChannelName ].push_back( n ); 
+      }
+      delete histForN;
+    
+    } // End Loop Over Categories
+    
+    delete iter;
+    return;
+
+  }
+
+
+  int getStatUncertaintyConstraintTerm( RooArgList* constraints, RooRealVar* gamma_stat, 
+					RooAbsReal*& pois_nom, RooRealVar*& tau ) {
+    // Given a set of constraint terms, 
+    // find the poisson constraint for the 
+    // given gamma and return the mean
+    // as well as the 'tau' parameter
+
+    bool verbose=false;
+
+    // To get the constraint term, loop over all constraint terms
+    // and look for the gamma_stat name as well as '_constraint'
+    // std::string constraintTermName = std::string(gamma_stat->GetName()) + "_constraint";
+    TIterator* iter_list = constraints->createIterator();
+    RooAbsArg* term_constr=NULL;
+    bool FoundConstraintTerm=false;
+    RooAbsPdf* constraintTerm=NULL;
+    while((term_constr=(RooAbsArg*)iter_list->Next())) {
+      std::string TermName = term_constr->GetName();
+      // std::cout << "Checking if is a constraint term: " << TermName << std::endl;
+      
+      //if( TermName.find(gamma_stat->GetName())!=string::npos ) {
+      if( term_constr->dependsOn( *gamma_stat) ) {
+	if( TermName.find("_constraint")!=std::string::npos ) {
+	  FoundConstraintTerm=true;
+	  constraintTerm = (RooAbsPdf*) term_constr;
+	  break;
+	}
+      }
+    }
+    if( FoundConstraintTerm==false ) {
+      std::cout << "Error: Couldn't find constraint term for parameter: " << gamma_stat->GetName()
+		<< " among constraints: " << constraints->GetName() <<  std::endl;
+      constraints->Print("V");
+      throw std::runtime_error("Failed to find Gamma ConstraintTerm");
+      return -1;
+    }
+    delete iter_list;
+
+    /*
+    RooAbsPdf* constraintTerm = (RooAbsPdf*) constraints->find( constraintTermName.c_str() );
+    if( constraintTerm == NULL ) {
+      std::cout << "Error: Couldn't find constraint term: " << constraintTermName
+		<< " for parameter: " << gamma_stat->GetName()
+		<< std::endl;
+      throw std::runtime_error("Failed to find Gamma ConstraintTerm");
+      return -1;
+    }
+    */
+
+    // Find the "data" of the poisson term
+    // This is the nominal value
+    bool FoundNomMean=false;
+    TIterator* iter_pois = constraintTerm->serverIterator(); //constraint_args
+    RooAbsArg* term_pois ;
+    while((term_pois=(RooAbsArg*)iter_pois->Next())) {
+      std::string serverName = term_pois->GetName();
+      //std::cout << "Checking Server: " << serverName << std::endl;
+      if( serverName.find("nom_")!=std::string::npos ) {
+	FoundNomMean = true;  
+	pois_nom = (RooRealVar*) term_pois;
+      }
+    }
+    if( !FoundNomMean || !pois_nom ) {
+      std::cout << "Error: Did not find Nominal Pois Mean parameter in gamma constraint term PoissonMean: "
+		<< constraintTerm->GetName() << std::endl;
+      throw std::runtime_error("Failed to find Nom Pois Mean");
+    }
+    else {
+      if(verbose) std::cout << "Found Poisson 'data' term: " << pois_nom->GetName() << std::endl;
+    }
+    delete iter_pois;
+
+    // Taking the constraint term (a Poisson), find
+    // the "mean" which is the product: gamma*tau
+    // Then, from that mean, find tau
+    TIterator* iter_constr = constraintTerm->serverIterator(); //constraint_args
+    RooAbsArg* pois_mean_arg=NULL;
+    bool FoundPoissonMean = false;
+    while(( pois_mean_arg = (RooAbsArg*) iter_constr->Next() )) {
+      std::string serverName = pois_mean_arg->GetName();
+      if( pois_mean_arg->dependsOn( *gamma_stat ) ) {
+	FoundPoissonMean=true;
+	// pois_mean = (RooAbsReal*) pois_mean_arg;
+	break;
+      }
+    }
+    if( !FoundPoissonMean || !pois_mean_arg ) {
+      std::cout << "Error: Did not find PoissonMean parameter in gamma constraint term: "
+		<< constraintTerm->GetName() << std::endl;
+      throw std::runtime_error("Failed to find PoissonMean");
+      return -1;
+    }
+    else {
+      if(verbose) std::cout << "Found Poisson 'mean' term: " << pois_mean_arg->GetName() << std::endl;
+    }
+    delete iter_constr;
+
+
+    TIterator* iter_product = pois_mean_arg->serverIterator(); //constraint_args
+    RooAbsArg* term_in_product ;
+    bool FoundTau=false;
+    while((term_in_product=(RooAbsArg*)iter_product->Next())) {
+      std::string serverName = term_in_product->GetName();
+      //std::cout << "Checking Server: " << serverName << std::endl;
+      if( serverName.find("_tau")!=std::string::npos ) {
+	FoundTau = true;  
+	tau = (RooRealVar*) term_in_product;
+      }
+    }
+    if( !FoundTau || !tau ) {
+      std::cout << "Error: Did not find Tau parameter in gamma constraint term PoissonMean: "
+		<< pois_mean_arg->GetName() << std::endl;
+      throw std::runtime_error("Failed to find Tau");
+    }
+    else {
+      if(verbose) std::cout << "Found Poisson 'tau' term: " << tau->GetName() << std::endl;
+    }
+    delete iter_product;
+
+    return 0;
+
+  }
+
+
+
+} // close RooStats namespace
+} // close HistFactory namespace
diff --git a/roofit/histfactory/src/HistFactorySimultaneous.cxx b/roofit/histfactory/src/HistFactorySimultaneous.cxx
new file mode 100644
index 0000000..2264b87
--- /dev/null
+++ b/roofit/histfactory/src/HistFactorySimultaneous.cxx
@@ -0,0 +1,128 @@
+/*****************************************************************************
+ * Project: RooFit                                                           *
+ * Package: RooFitCore                                                       *
+ * @(#)root/roofitcore:$Id: HistFactorySimultaneous.cxx 44543 2012-06-04 20:25:32Z moneta $
+ * Authors:                                                                  *
+ *   WV, Wouter Verkerke, UC Santa Barbara, verkerke at slac.stanford.edu       *
+ *   DK, David Kirkby,    UC Irvine,         dkirkby at uci.edu                 *
+ *                                                                           *
+ * Copyright (c) 2000-2005, Regents of the University of California          *
+ *                          and Stanford University. All rights reserved.    *
+ *                                                                           *
+ * Redistribution and use in source and binary forms,                        *
+ * with or without modification, are permitted according to the terms        *
+ * listed in LICENSE (http://roofit.sourceforge.net/license.txt)             *
+ *****************************************************************************/
+
+//////////////////////////////////////////////////////////////////////////////
+//
+// BEGIN_HTML
+// RooSimultaneous facilitates simultaneous fitting of multiple PDFs
+// to subsets of a given dataset.
+// <p>
+// The class takes an index category, which is interpreted as
+// the data subset indicator, and a list of PDFs, each associated
+// with a state of the index category. RooSimultaneous always returns
+// the value of the PDF that is associated with the current value
+// of the index category
+// <p>
+// Extended likelihood fitting is supported if all components support
+// extended likelihood mode. The expected number of events by a RooSimultaneous
+// is that of the component p.d.f. selected by the index category
+// END_HTML
+//
+
+
+#include "RooNLLVar.h"
+
+#include "RooStats/HistFactory/RooBarlowBeestonLL.h"
+#include "RooStats/HistFactory/HistFactorySimultaneous.h"
+
+using namespace std ;
+
+ClassImp(RooStats::HistFactory::HistFactorySimultaneous)
+;
+
+
+//_____________________________________________________________________________
+RooStats::HistFactory::HistFactorySimultaneous::HistFactorySimultaneous(const char *name, const char *title, 
+						 RooAbsCategoryLValue& inIndexCat) : 
+  RooSimultaneous(name, title, inIndexCat ) {}
+
+
+//_____________________________________________________________________________
+RooStats::HistFactory::HistFactorySimultaneous::HistFactorySimultaneous(const char *name, const char *title, 
+				 const RooArgList& inPdfList, RooAbsCategoryLValue& inIndexCat) :
+  RooSimultaneous(name, title, inPdfList, inIndexCat) {}
+
+
+//_____________________________________________________________________________
+RooStats::HistFactory::HistFactorySimultaneous::HistFactorySimultaneous(const char *name, const char *title, 
+				 map<string,RooAbsPdf*> pdfMap, RooAbsCategoryLValue& inIndexCat) :
+  RooSimultaneous(name, title, pdfMap, inIndexCat) {}
+
+
+//_____________________________________________________________________________
+RooStats::HistFactory::HistFactorySimultaneous::HistFactorySimultaneous(const HistFactorySimultaneous& other, const char* name) : 
+  RooSimultaneous(other, name) {}
+
+//_____________________________________________________________________________
+RooStats::HistFactory::HistFactorySimultaneous::HistFactorySimultaneous(const RooSimultaneous& other, const char* name) : 
+  RooSimultaneous(other, name) {}
+
+//_____________________________________________________________________________
+RooStats::HistFactory::HistFactorySimultaneous::~HistFactorySimultaneous() 
+{
+  // Destructor
+}
+
+
+//_____________________________________________________________________________
+RooAbsReal* RooStats::HistFactory::HistFactorySimultaneous::createNLL(RooAbsData& data, 
+					       const RooCmdArg& arg1, const RooCmdArg& arg2, 
+					       const RooCmdArg& arg3, const RooCmdArg& arg4, 
+					       const RooCmdArg& arg5, const RooCmdArg& arg6, 
+					       const RooCmdArg& arg7, const RooCmdArg& arg8) {
+  
+  // Probably not necessary because createNLL is virtual...
+
+  RooLinkedList l ;
+  l.Add((TObject*)&arg1) ;  l.Add((TObject*)&arg2) ;
+  l.Add((TObject*)&arg3) ;  l.Add((TObject*)&arg4) ;
+  l.Add((TObject*)&arg5) ;  l.Add((TObject*)&arg6) ;
+  l.Add((TObject*)&arg7) ;  l.Add((TObject*)&arg8) ;
+  return createNLL(data,l) ;
+  
+}
+
+
+//_____________________________________________________________________________
+
+RooAbsReal* RooStats::HistFactory::HistFactorySimultaneous::createNLL(RooAbsData& data, const RooLinkedList& cmdList) {
+  
+  // We want to overload the method createNLL so it return
+  // a RooBarlow-Beeston NLL function, which can be used
+  // in HistFactory to minimize statistical uncertainty analytically
+  //
+  // The only problem is one of ownership
+  // This HistFactorySimultaneous and the RooAbsData& data must
+  // exist for as long as the RooBarlowBeestonLL does
+  //
+  // This could be solved if we instead refer to the cloned
+  // pdf's and data set in the nll that we create here, but
+  // it's unclear how to do so
+  //
+  // Also, check for ownership/memory issue with the newly created nll
+  // and whether RooBarlowBeestonLL owns it, etc
+
+  // Create a standard nll
+  RooNLLVar* nll = (RooNLLVar*) RooSimultaneous::createNLL( data, cmdList );
+
+  RooBarlowBeestonLL* bbnll = new RooBarlowBeestonLL("bbnll", "bbnll", *nll); //, *observables);
+  bbnll->setPdf( this );
+  bbnll->setDataset( &data );
+  bbnll->initializeBarlowCache(); 
+  
+  return bbnll;
+
+}
diff --git a/roofit/histfactory/src/HistoToWorkspaceFactory.cxx b/roofit/histfactory/src/HistoToWorkspaceFactory.cxx
index 127e3c4..a181fa6 100644
--- a/roofit/histfactory/src/HistoToWorkspaceFactory.cxx
+++ b/roofit/histfactory/src/HistoToWorkspaceFactory.cxx
@@ -67,9 +67,9 @@ END_HTML
 
 // specific to this package
 //#include "RooStats/HistFactory/Helper.h"
-#include "Helper.h"
 #include "RooStats/HistFactory/LinInterpVar.h"
 #include "RooStats/HistFactory/HistoToWorkspaceFactory.h"
+#include "Helper.h"
 
 #define VERBOSE
 
diff --git a/roofit/histfactory/src/HistoToWorkspaceFactoryFast.cxx b/roofit/histfactory/src/HistoToWorkspaceFactoryFast.cxx
index 5af7659..47d6199 100644
--- a/roofit/histfactory/src/HistoToWorkspaceFactoryFast.cxx
+++ b/roofit/histfactory/src/HistoToWorkspaceFactoryFast.cxx
@@ -71,11 +71,11 @@ END_HTML
 #include "TMatrixDSym.h"
 
 // specific to this package
-//#include "RooStats/HistFactory/Helper.h"
-#include "Helper.h"
 #include "RooStats/HistFactory/LinInterpVar.h"
 #include "RooStats/HistFactory/FlexibleInterpVar.h"
 #include "RooStats/HistFactory/HistoToWorkspaceFactoryFast.h"
+#include "Helper.h"
+
 
 #include <algorithm>
 
@@ -160,6 +160,11 @@ namespace HistFactory{
 
     // Make a ModelConfig and configure it
     ModelConfig * proto_config = (ModelConfig *) ws_single->obj("ModelConfig");
+    if( proto_config == NULL ) {
+      std::cout << "Error: Did not find 'ModelConfig' object in file: " << ws_single->GetName() 
+		<< std::endl;
+      throw hf_exc();
+    }
     cout << "Setting Parameter of Interest as :" << measurement.GetPOI() << endl;
     RooRealVar* poi = (RooRealVar*) ws_single->var( (measurement.GetPOI()).c_str() );
     RooArgSet * params= new RooArgSet;
@@ -206,7 +211,12 @@ namespace HistFactory{
     
     // Then, use HistFactory on that vector to create the workspace
     RooWorkspace* ws_single = this->MakeSingleChannelModel(channel_estimateSummary, measurement.GetConstantParams());
-    
+    if( ws_single == NULL ) {
+      std::cout << "Error: Failed to make Single-Channel workspace for channel: " << ch_name
+		<< " and measurement: " << measurement.GetName() << std::endl;
+      throw hf_exc();
+    }
+
     // Finally, configure that workspace based on
     // properties of the measurement
     HistoToWorkspaceFactoryFast::ConfigureWorkspaceForMeasurement( "model_"+ch_name, ws_single, measurement );
@@ -245,8 +255,7 @@ namespace HistFactory{
       if( ! channel.CheckHistograms() ) {
 	std::cout << "MakeModelAndMeasurementsFast: Channel: " << channel.GetName()
 		  << " has uninitialized histogram pointers" << std::endl;
-	throw bad_hf;
-	return NULL;
+	throw hf_exc();
       }
 
       string ch_name = channel.GetName();
@@ -395,10 +404,16 @@ namespace HistFactory{
     std::vector<std::string>::iterator itr = fObsNameVec.begin();
     for (int idx=0; itr!=fObsNameVec.end(); ++itr, ++idx ) {
       if ( !proto->var(itr->c_str()) ) {
-	TAxis* axis(0);
+	TAxis* axis(NULL);
 	if (idx==0) { axis = nominal->GetXaxis(); }
-	if (idx==1) { axis = nominal->GetYaxis(); }
-	if (idx==2) { axis = nominal->GetZaxis(); }
+	else if (idx==1) { axis = nominal->GetYaxis(); }
+	else if (idx==2) { axis = nominal->GetZaxis(); }
+	else {
+	  std::cout << "Error: Too many observables.  "
+		    << "HistFactory only accepts up to 3 observables (3d) "
+		    << std::endl;
+	  throw hf_exc();
+	}
 	Int_t nbins = axis->GetNbins();	
 	Double_t xmin = axis->GetXmin();
 	Double_t xmax = axis->GetXmax(); 	
@@ -710,6 +725,9 @@ namespace HistFactory{
      tree->Fill();
      RooDataSet* data = new RooDataSet("expData","", tree, obsList); // one experiment
 
+     delete tree;
+     delete [] obsForTree;
+
      proto->import(*data);
 
   }
@@ -738,6 +756,11 @@ namespace HistFactory{
     //cout << "HistoToWorkspaceFactoryFast::EditSyst() : gamma = " << gammaSyst.size() << ", uniform = " << uniformSyst.size() << ", noconst = " << noSyst.size() << endl;
 
     ModelConfig * combined_config = (ModelConfig *) proto->obj("ModelConfig");
+    if( combined_config==NULL ) {
+      std::cout << "Error: Failed to find object 'ModelConfig' in workspace: " 
+		<< proto->GetName() << std::endl;
+      throw hf_exc();
+    }
     //    const RooArgSet * constrainedParams=combined_config->GetNuisanceParameters();
     //    RooArgSet temp(*constrainedParams);
     string edit="EDIT::newSimPdf("+pdfName+",";
@@ -1437,6 +1460,10 @@ namespace HistFactory{
       // Create the histogram of (binwise)
       // stat uncertainties:
       TH1* fracStatError = MakeScaledUncertaintyHist( statNodeName + "_RelErr", statHistPairs ); 
+      if( fracStatError == NULL ) {
+	std::cout << "Error: Failed to make ScaledUncertaintyHist for: " << statNodeName << std::endl;
+	throw hf_exc();
+      }
       
       // Using this TH1* of fractinal stat errors, 
       // create a set of constraint terms:
@@ -1492,10 +1519,23 @@ namespace HistFactory{
     //////////////////////////////////////
     // final proto model
     for(unsigned int i=0; i<constraintTermNames.size(); ++i){
-      constraintTerms.add(* (proto->arg(constraintTermNames[i].c_str())) );
+      RooAbsArg* proto_arg = (proto->arg(constraintTermNames[i].c_str()));
+      if( proto_arg==NULL ) {
+	std::cout << "Error: Cannot find arg set: " << constraintTermNames.at(i)
+		  << " in workspace: " << proto->GetName() << std::endl;
+	throw hf_exc();
+      }
+      constraintTerms.add( *proto_arg );
+      //  constraintTerms.add(* proto_arg(proto->arg(constraintTermNames[i].c_str())) );
     }
     for(unsigned int i=0; i<likelihoodTermNames.size(); ++i){
-      likelihoodTerms.add(* (proto->arg(likelihoodTermNames[i].c_str())) );
+      RooAbsArg* proto_arg = (proto->arg(likelihoodTermNames[i].c_str())); 
+      if( proto_arg==NULL ) {
+	std::cout << "Error: Cannot find arg set: " << constraintTermNames.at(i)
+		  << " in workspace: " << proto->GetName() << std::endl;
+	throw hf_exc();
+      }
+      likelihoodTerms.add( *proto_arg );
     }
     proto->defineSet("constraintTerms",constraintTerms);
     proto->defineSet("likelihoodTerms",likelihoodTerms);
@@ -1797,9 +1837,9 @@ namespace HistFactory{
 		  << " bin error for bin " << i_bin
 		  << " is NAN.  Not using Error!!!"
 		  << std::endl;
-	throw -1;
+	throw hf_exc();
 	//histError = sqrt( histContent );
-	histError = 0;
+	//histError = 0;
       }
     
       // Check that histError ! < 0
@@ -1895,8 +1935,8 @@ namespace HistFactory{
 		  << " bin error for bin " << binNumber
 		  << " is NAN.  Not using error!!"
 		  << std::endl;
-	throw -1;
-	histError = 0;
+	throw hf_exc();
+	//histError = 0;
       }
       
       TotalBinContent.at(i_bins) += histValue;
@@ -1941,8 +1981,7 @@ namespace HistFactory{
       std::cout << " HistErrorsSqr: " << ErrorsSqr
 		<< " TotalVal: " << TotalVal
 		<< std::endl;
-      throw -1;
-      return NULL;
+      throw hf_exc();
     }
 
     // 0th entry in vector is
diff --git a/roofit/histfactory/src/MakeModelAndMeasurements.cxx b/roofit/histfactory/src/MakeModelAndMeasurements.cxx
index 91883a4..cb0013e 100644
--- a/roofit/histfactory/src/MakeModelAndMeasurements.cxx
+++ b/roofit/histfactory/src/MakeModelAndMeasurements.cxx
@@ -86,12 +86,15 @@ END_HTML
 #include "RooStats/HistFactory/ConfigParser.h"
 #include "RooStats/HistFactory/EstimateSummary.h"
 #include "RooStats/HistFactory/HistoToWorkspaceFactory.h"
+#include "RooStats/HistFactory/HistFactoryException.h"
 
 
 using namespace RooFit;
 using namespace RooStats;
 using namespace HistFactory;
 
+using namespace std;
+
 void topDriver(string input);
 void fastDriver(string input); // in MakeModelAndMeasurementsFast
 
@@ -113,6 +116,9 @@ int main(int argc, char** argv) {
     catch (std::string str) {
       cerr << "caught exception: " << str << endl ;
     }
+    catch( const exception& e ) {
+      cerr << "Caught Exception: " << e.what() << endl;
+    }
   }
 
   if(argc==3){
@@ -125,6 +131,9 @@ int main(int argc, char** argv) {
       catch (std::string str) {
 	cerr << "caught exception: " << str << endl ;
       }
+      catch( const exception& e ) {
+	cerr << "Caught Exception: " << e.what() << endl;
+      }
     else if(flag=="-number_counting_form")
       try {
          topDriver(input);
@@ -132,6 +141,10 @@ int main(int argc, char** argv) {
       catch (std::string str) {
 	cerr << "caught exception: " << str << endl ;
       }
+      catch( const exception& e ) {
+	cerr << "Caught Exception: " << e.what() << endl;
+      }
+
     else
       cerr <<"unrecognized flag.  Options are -standard_form or -number_counting_form"<<endl;
 
@@ -210,6 +223,11 @@ void topDriver( string input ) {
 
       std::vector< EstimateSummary > dummy;
       RooWorkspace* ws = factory.MakeSingleChannelModel( dummy, measurement.GetConstantParams() );
+      if( ws==NULL ) {
+	std::cout << "Failed to create SingleChannelModel for channel: " << channel.GetName()
+		  << " and measurement: " << measurement.GetName() << std::endl;
+	throw hf_exc();
+      }
       //RooWorkspace* ws = factory.MakeSingleChannelModel( channel );
       channel_workspaces.push_back(ws);
 
@@ -263,6 +281,10 @@ void topDriver( string input ) {
 
     // Now, combine the channels
     RooWorkspace* ws=factory.MakeCombinedModel(channel_names, channel_workspaces);
+    if( ws == NULL ) {
+      std::cout << "Error: Failed to create workspace" << std::endl;
+      throw hf_exc();
+    }
     // Gamma/Uniform Constraints:
     // turn some Gaussian constraints into Gamma/Uniform/logNormal constraints, rename model newSimPdf
     if( measurement.GetGammaSyst().size()>0 || measurement.GetUniformSyst().size()>0 || measurement.GetLogNormSyst().size()>0) 
diff --git a/roofit/histfactory/src/MakeModelAndMeasurementsFast.cxx b/roofit/histfactory/src/MakeModelAndMeasurementsFast.cxx
index 050e565..5c71506 100644
--- a/roofit/histfactory/src/MakeModelAndMeasurementsFast.cxx
+++ b/roofit/histfactory/src/MakeModelAndMeasurementsFast.cxx
@@ -99,6 +99,7 @@ using namespace RooFit;
 using namespace RooStats;
 using namespace HistFactory;
 
+using namespace std;
 
 void fastDriver(string input){
   // TO DO:
@@ -235,7 +236,7 @@ RooWorkspace* RooStats::HistFactory::MakeModelAndMeasurementFast( RooStats::Hist
       if( ! channel.CheckHistograms() ) {
 	std::cout << "MakeModelAndMeasurementsFast: Channel: " << channel.GetName()
 		  << " has uninitialized histogram pointers" << std::endl;
-	throw bad_hf;
+	throw hf_exc();
 	return NULL;
       }
 
@@ -306,6 +307,10 @@ RooWorkspace* RooStats::HistFactory::MakeModelAndMeasurementFast( RooStats::Hist
     ws->writeToFile( CombinedFileName.c_str() );
     std::cout << "About to write combined measurement to file" << std::endl;
     TFile* combFile = TFile::Open( CombinedFileName.c_str(), "UPDATE" );
+    if( combFile == NULL ) {
+      std::cout << "Error: Failed to open file " << CombinedFileName << std::endl;
+      throw hf_exc();
+    }
     measurement.writeToFile( combFile );
     combFile->Close();
 
@@ -334,7 +339,7 @@ RooWorkspace* RooStats::HistFactory::MakeModelAndMeasurementFast( RooStats::Hist
   catch(exception& e)
     {
       std::cout << e.what() << std::endl;
-      throw bad_hf;
+      throw hf_exc();
       return NULL;
     }
 
@@ -399,7 +404,18 @@ void RooStats::HistFactory::FitModelAndPlot(const std::string& MeasurementName,
 
       RooAbsReal* nll = model->createNLL(*simData);
       RooAbsReal* profile = nll->createProfile(*poi);
+      if( profile==NULL ) {
+	std::cout << "Error: Failed to make ProfileLikelihood for: " << poi->GetName() 
+		  << " using model: " << model->GetName()
+		  << " and data: " << simData->GetName()
+		  << std::endl;
+	throw hf_exc();
+      }
       RooPlot* frame = poi->frame();
+      if( frame == NULL ) {
+	std::cout << "Error: Failed to create RooPlot frame for: " << poi->GetName() << std::endl;
+	throw hf_exc();
+      }
       FormatFrameForLikelihood(frame);
       TCanvas* c1 = new TCanvas( channel.c_str(), "",800,600);
       nll->plotOn(frame, ShiftToZero(), LineColor(kRed), LineStyle(kDashed));
@@ -411,7 +427,18 @@ void RooStats::HistFactory::FitModelAndPlot(const std::string& MeasurementName,
       c1->SaveAs( (FileNamePrefix+"_"+channel+"_"+MeasurementName+"_profileLR.eps").c_str() );
       delete c1;
 
-      outFile->mkdir(channel.c_str())->mkdir("Summary")->cd();
+      TDirectory* channel_dir = outFile->mkdir(channel.c_str());
+      if( channel_dir == NULL ) {
+	std::cout << "Error: Failed to make channel directory: " << channel << std::endl;
+	throw hf_exc();
+      }
+      TDirectory* summary_dir = channel_dir->mkdir("Summary");
+      if( summary_dir == NULL ) {
+	std::cout << "Error: Failed to make Summary directory for channel: " << channel << std::endl;
+	throw hf_exc();
+      }
+      summary_dir->cd();
+      //outFile->mkdir(channel.c_str())->mkdir("Summary")->cd();
     
       RooCurve* curve=frame->getCurve();
       Int_t curve_N=curve->GetN();
diff --git a/roofit/histfactory/src/Measurement.cxx b/roofit/histfactory/src/Measurement.cxx
index 2952c54..a30e0ba 100644
--- a/roofit/histfactory/src/Measurement.cxx
+++ b/roofit/histfactory/src/Measurement.cxx
@@ -62,9 +62,10 @@ RooStats::HistFactory::Channel& RooStats::HistFactory::Measurement::GetChannel(
 
   std::cout << "Error: Did not find channel: " << ChanName
 	    << " in measurement: " << GetName() << std::endl;
-  throw bad_hf;
+  throw hf_exc();
 
-  return RooStats::HistFactory::BadChannel;
+  // No Need to return after throwing exception
+  // return RooStats::HistFactory::BadChannel;
 
 
 }
@@ -126,10 +127,14 @@ void RooStats::HistFactory::Measurement::PrintXML( std::string Directory, std::s
 
   // First, check that the directory exists:
 
+
   // LM : fixes for Windows 
-  gSystem->MakeDirectory(Directory.c_str() );    
-  //mkdir( Directory.c_str(), 0777 );
-  
+  int success = gSystem->MakeDirectory(Directory.c_str() );    
+  if( success != 0 ) {
+    std::cout << "Error: Failed to make directory: " << Directory << std::endl;
+    throw hf_exc();
+  }
+
   // If supplied new Prefix, use that one:
 
   std::cout << "Printing XML Files for measurement: " << GetName() << std::endl;
@@ -141,7 +146,7 @@ void RooStats::HistFactory::Measurement::PrintXML( std::string Directory, std::s
 
   if( ! xml.is_open() ) {
     std::cout << "Error opening xml file: " << XMLName << std::endl;
-    throw bad_hf;
+    throw hf_exc();
   }
 
 
@@ -271,7 +276,7 @@ void RooStats::HistFactory::Measurement::writeToFile( TFile* file ) {
     if( ! channel.CheckHistograms() ) {
       std::cout << "Measurement.writeToFile(): Channel: " << chanName
 		<< " has uninitialized histogram pointers" << std::endl;
-      throw bad_hf;
+      throw hf_exc();
       return;
     }
     
@@ -284,11 +289,20 @@ void RooStats::HistFactory::Measurement::writeToFile( TFile* file ) {
     // for this channel
 
     TDirectory* chanDir = file->mkdir( (chanName + "_hists").c_str() );
+    if( chanDir == NULL ) {
+      std::cout << "Error: Cannot create channel " << (chanName + "_hists")
+		<< std::endl;
+      throw hf_exc();
+    }
     chanDir->cd();
 
     // Save the data:
     
     TDirectory* dataDir = chanDir->mkdir( "data" );
+    if( dataDir == NULL ) {
+      std::cout << "Error: Cannot make directory " << chanDir << std::endl;
+      throw hf_exc();
+    }
     dataDir->cd();
 
     channel.fData.writeToFile( OutputFileName, GetDirPath(dataDir) );
@@ -318,13 +332,17 @@ void RooStats::HistFactory::Measurement::writeToFile( TFile* file ) {
       file->cd();
       chanDir->cd();
       TDirectory* sampleDir = chanDir->mkdir( sampName.c_str() );
+      if( sampleDir == NULL ) {
+	std::cout << "Error: Directory " << sampName << " not created properly" << std::endl;
+	throw hf_exc();
+      }
       std::string sampleDirPath = GetDirPath( sampleDir );
 
       if( ! sampleDir ) {
 	std::cout << "Error making directory: " << sampName 
 		  << " in directory: " << chanName
 		  << std::endl;
-	throw bad_hf;
+	throw hf_exc();
       }
 
       // Write the data file to this directory
diff --git a/roofit/histfactory/src/ParamHistFunc.cxx b/roofit/histfactory/src/ParamHistFunc.cxx
index 3246da8..4a7221c 100755
--- a/roofit/histfactory/src/ParamHistFunc.cxx
+++ b/roofit/histfactory/src/ParamHistFunc.cxx
@@ -44,7 +44,7 @@ ClassImp(ParamHistFunc);
 
 
 //_____________________________________________________________________________
-ParamHistFunc::ParamHistFunc() 
+ParamHistFunc::ParamHistFunc() : _numBins(0)
 {
   ;
 }
@@ -810,17 +810,17 @@ Double_t ParamHistFunc::analyticalIntegralWN(Int_t /*code*/, const RooArgSet* /*
     
     // Get the bin volume
     _dataSet.get( nominalItr );
-    Double_t binVolume  = _dataSet.binVolume(); //_binning->binWidth( nominalItr );
+    Double_t binVolumeDS  = _dataSet.binVolume(); //_binning->binWidth( nominalItr );
     
     // Finally, get the subtotal
-    value += paramVal*binVolume;
+    value += paramVal*binVolumeDS;
 
     ++nominalItr;
 
     /*
     std::cout << "Integrating : "
 	      << " bin: "  << nomValue
-	      << " binVolume:  "  << binVolume
+	      << " binVolume:  "  << binVolumeDS
 	      << " paramValue:  "  << paramVal
 	      << " nomValue:  "  << nomValue
 	      << " subTotal:  "  << value
@@ -836,14 +836,14 @@ Double_t ParamHistFunc::analyticalIntegralWN(Int_t /*code*/, const RooArgSet* /*
 
 
 //_____________________________________________________________________________
-list<Double_t>* ParamHistFunc::plotSamplingHint(RooAbsRealLValue& obs, Double_t xlo, Double_t xhi) const
+list<Double_t>* ParamHistFunc::plotSamplingHint(RooAbsRealLValue& /*obs*/, Double_t /*xlo*/, Double_t /*xhi*/) const
 {
   // Return sampling hint for making curves of (projections) of this function
   // as the recursive division strategy of RooCurve cannot deal efficiently
   // with the vertical lines that occur in a non-interpolated histogram
 
   return 0;
-
+  /*
   // copied and edited from RooHistFunc
   RooAbsLValue* lvarg = &obs;
 
@@ -869,11 +869,12 @@ list<Double_t>* ParamHistFunc::plotSamplingHint(RooAbsRealLValue& obs, Double_t
   }
 
   return hint ;
+  */
 }
 
 
 //______________________________________________________________________________
-std::list<Double_t>* ParamHistFunc::binBoundaries(RooAbsRealLValue& obs, Double_t xlo, Double_t xhi) const 
+std::list<Double_t>* ParamHistFunc::binBoundaries(RooAbsRealLValue& /*obs*/, Double_t /*xlo*/, Double_t /*xhi*/) const 
 {
   // Return sampling hint for making curves of (projections) of this function
   // as the recursive division strategy of RooCurve cannot deal efficiently
@@ -881,6 +882,7 @@ std::list<Double_t>* ParamHistFunc::binBoundaries(RooAbsRealLValue& obs, Double_
 
   return 0;
 
+  /*
   // copied and edited from RooHistFunc
   RooAbsLValue* lvarg = &obs;
 
@@ -899,4 +901,5 @@ std::list<Double_t>* ParamHistFunc::binBoundaries(RooAbsRealLValue& obs, Double_
   }
 
   return hint ;
+  */
 }
diff --git a/roofit/histfactory/src/PiecewiseInterpolation.cxx b/roofit/histfactory/src/PiecewiseInterpolation.cxx
index 528dae7..d12b00d 100644
--- a/roofit/histfactory/src/PiecewiseInterpolation.cxx
+++ b/roofit/histfactory/src/PiecewiseInterpolation.cxx
@@ -9,7 +9,7 @@
 // END_HTML
 //
 
-
+#include <exception>
 #include "RooFit.h"
 
 #include "Riostream.h"
@@ -485,6 +485,10 @@ Double_t PiecewiseInterpolation::analyticalIntegralWN(Int_t code, const RooArgSe
 
   // old integral, only works for linear and not positive definite
   CacheElem* cache = (CacheElem*) _normIntMgr.getObjByIndex(code-1) ;
+  if( cache==NULL ) {
+    std::cout << "Error: Cache Element is NULL" << std::endl;
+    throw std::exception();
+  }
 
   // old integral, only works for linear and not positive definite
   RooFIter funcIntIter = cache->_funcIntList.fwdIterator() ;
@@ -653,6 +657,7 @@ void PiecewiseInterpolation::Streamer(TBuffer &R__b)
    if (R__b.IsReading()) {
       R__b.ReadClassBuffer(PiecewiseInterpolation::Class(),this);
       specialIntegratorConfig(kTRUE)->method1D().setLabel("RooBinIntegrator") ;      
+      if (_interpCode.empty()) _interpCode.resize(_paramSet.getSize());
    } else {
       R__b.WriteClassBuffer(PiecewiseInterpolation::Class(),this);
    }
diff --git a/roofit/histfactory/src/RooBarlowBeestonLL.cxx b/roofit/histfactory/src/RooBarlowBeestonLL.cxx
new file mode 100644
index 0000000..c1c2b1b
--- /dev/null
+++ b/roofit/histfactory/src/RooBarlowBeestonLL.cxx
@@ -0,0 +1,743 @@
+/***************************************************************************** 
+  * Project: RooFit                                                           * 
+  *                                                                           * 
+  * Copyright (c) 2000-2005, Regents of the University of California          * 
+  *                          and Stanford University. All rights reserved.    * 
+  *                                                                           * 
+  * Redistribution and use in source and binary forms,                        * 
+  * with or without modification, are permitted according to the terms        * 
+  * listed in LICENSE (http://roofit.sourceforge.net/license.txt)             * 
+  *****************************************************************************/ 
+
+//////////////////////////////////////////////////////////////////////////////
+//
+// BEGIN_HTML
+// Class RooBarlowBeestonLL implements the profile likelihood estimator for
+// a given likelihood and set of parameters of interest. The value return by 
+// RooBarlowBeestonLL is the input likelihood nll minimized w.r.t all nuisance parameters
+// (which are all parameters except for those listed in the constructor) minus
+// the -log(L) of the best fit. Note that this function is slow to evaluate
+// as a MIGRAD minimization step is executed for each function evaluation
+// END_HTML
+//
+
+#include <stdexcept>
+#include <math.h>
+
+#include "Riostream.h" 
+
+#include "RooFit.h"
+#include "RooStats/HistFactory/RooBarlowBeestonLL.h" 
+#include "RooAbsReal.h" 
+#include "RooAbsData.h" 
+//#include "RooMinuit.h"
+#include "RooMsgService.h"
+#include "RooRealVar.h"
+#include "RooMsgService.h"
+#include "RooNLLVar.h"
+
+#include "RooStats/RooStatsUtils.h"
+#include "RooProdPdf.h"
+#include "RooCategory.h"
+#include "RooSimultaneous.h"
+#include "RooArgList.h"
+#include "RooAbsCategoryLValue.h"
+
+#include "RooStats/HistFactory/ParamHistFunc.h"
+#include "RooStats/HistFactory/HistFactoryModelUtils.h"
+
+using namespace std ;
+
+ClassImp(RooStats::HistFactory::RooBarlowBeestonLL) 
+
+
+//_____________________________________________________________________________ 
+ RooStats::HistFactory::RooBarlowBeestonLL::RooBarlowBeestonLL() : 
+   RooAbsReal("RooBarlowBeestonLL","RooBarlowBeestonLL"), 
+   _nll(), 
+//   _obs("paramOfInterest","Parameters of interest",this), 
+//  _par("nuisanceParam","Nuisance parameters",this,kFALSE,kFALSE),
+  _pdf(NULL), _data(NULL)
+{ 
+  // Default constructor 
+  // Should only be used by proof. 
+  //  _piter = _par.createIterator() ; 
+  //  _oiter = _obs.createIterator() ; 
+} 
+
+
+//_____________________________________________________________________________
+RooStats::HistFactory::RooBarlowBeestonLL::RooBarlowBeestonLL(const char *name, const char *title, 
+				       RooAbsReal& nllIn /*, const RooArgSet& observables*/) :
+  RooAbsReal(name,title), 
+  _nll("input","-log(L) function",this,nllIn),
+  //  _obs("paramOfInterest","Parameters of interest",this),
+  //  _par("nuisanceParam","Nuisance parameters",this,kFALSE,kFALSE),
+  _pdf(NULL), _data(NULL)
+{ 
+  // Constructor of profile likelihood given input likelihood nll w.r.t
+  // the given set of variables. The input log likelihood is minimized w.r.t
+  // to all other variables of the likelihood at each evaluation and the
+  // value of the global log likelihood minimum is always subtracted.
+
+  // Determine actual parameters and observables
+  /*
+  RooArgSet* actualObs = nllIn.getObservables(observables) ;
+  RooArgSet* actualPars = nllIn.getParameters(observables) ;
+
+  _obs.add(*actualObs) ;
+  _par.add(*actualPars) ;
+
+  delete actualObs ;
+  delete actualPars ;
+
+  _piter = _par.createIterator() ;
+  _oiter = _obs.createIterator() ;
+  */
+} 
+
+
+
+//_____________________________________________________________________________
+RooStats::HistFactory::RooBarlowBeestonLL::RooBarlowBeestonLL(const RooBarlowBeestonLL& other, const char* name) :  
+  RooAbsReal(other,name), 
+  _nll("nll",this,other._nll),
+  //  _obs("obs",this,other._obs),
+  //  _par("par",this,other._par),
+  _pdf(NULL), _data(NULL),
+  _paramFixed(other._paramFixed)
+{ 
+  // Copy constructor
+
+  //  _piter = _par.createIterator() ;
+  //  _oiter = _obs.createIterator() ;
+
+  // _paramAbsMin.addClone(other._paramAbsMin) ;
+  // _obsAbsMin.addClone(other._obsAbsMin) ;
+    
+} 
+
+
+
+//_____________________________________________________________________________
+RooStats::HistFactory::RooBarlowBeestonLL::~RooBarlowBeestonLL()
+{
+  // Destructor
+
+  // Delete instance of minuit if it was ever instantiated
+  // if (_minuit) {
+  //   delete _minuit ;
+  // }
+
+  
+  //delete _piter ;
+  //delete _oiter ;
+}
+
+
+//_____________________________________________________________________________
+void RooStats::HistFactory::RooBarlowBeestonLL::BarlowCache::SetBinCenter() const {
+  TIterator* iter = bin_center->createIterator() ;
+  RooRealVar* var;
+  while((var=(RooRealVar*)iter->Next())) {
+    RooRealVar* target = (RooRealVar*) observables->find(var->GetName()) ;
+    target->setVal(var->getVal()) ;
+  }
+  delete iter;
+}
+
+
+//_____________________________________________________________________________
+void RooStats::HistFactory::RooBarlowBeestonLL::initializeBarlowCache() {
+
+  bool verbose=false;
+
+  if(!_data) {
+    std::cout << "Error: Must initialize data before initializing cache" << std::endl;
+    throw std::runtime_error("Uninitialized Data");    
+  }
+  if(!_pdf) {
+    std::cout << "Error: Must initialize model pdf before initializing cache" << std::endl;
+    throw std::runtime_error("Uninitialized model pdf");    
+  }
+
+  // Get the data bin values for all channels and bins
+  std::map< std::string, std::vector<double> > ChannelBinDataMap;
+  getDataValuesForObservables( ChannelBinDataMap, _data, _pdf );
+
+  // Get a list of constraint terms
+  RooArgList obsTerms;
+  RooArgList constraints;
+  RooArgSet* obsSet = _pdf->getObservables(*_data);
+  FactorizeHistFactoryPdf(*obsSet, *_pdf, obsTerms, constraints);
+
+  if( obsTerms.getSize() == 0 ) {
+    std::cout << "Error: Found no observable terms with pdf: " << _pdf->GetName()
+	      << " using dataset: " << _data->GetName() << std::endl;
+    return;
+  }
+  if( constraints.getSize() == 0 ) {
+    std::cout << "Error: Found no constraint terms with pdf: " << _pdf->GetName()
+	      << " using dataset: " << _data->GetName() << std::endl;
+    return;
+  }
+
+  /*
+  // Get the channels for this pdf
+  RooArgSet* channels = new RooArgSet();
+  RooArgSet* channelsWithConstraints = new RooArgSet();
+  getChannelsFromModel( _pdf, channels, channelsWithConstraints );
+  */
+  
+  // Loop over the channels
+  RooSimultaneous* simPdf = (RooSimultaneous*) _pdf;
+  RooCategory* channelCat = (RooCategory*) (&simPdf->indexCat());
+  TIterator* iter = channelCat->typeIterator() ;
+  RooCatType* tt = NULL;
+  while((tt=(RooCatType*) iter->Next())) {
+    /*
+      std::string ChannelName = tt->GetName();
+      
+      HHChannel_hh_edit
+      
+      TIterator* iter_channels = channelsWithConstraints->createIterator();
+      RooAbsPdf* channelPdf=NULL;
+      while(( channelPdf=(RooAbsPdf*)iter_channels->Next()  )) {
+      
+      std::string channel_name = RooStats::channelNameFromPdf( channelPdf );
+    */
+
+    // Warning: channel cat name is not necesarily the same name
+    // as the pdf's (for example, if someone does edits)
+    RooAbsPdf* channelPdf = simPdf->getPdf(tt->GetName());
+    std::string channel_name = channelPdf->GetName();
+
+    // First, we check if this channel uses Stat Uncertainties:
+    RooArgList* gammas = new RooArgList();
+    ParamHistFunc* param_func=NULL;
+    bool hasStatUncert = getStatUncertaintyFromChannel( channelPdf, param_func, gammas );
+    if( ! hasStatUncert ) {
+      if(verbose) {
+	std::cout << "Channel: " << channel_name
+		  << " doesn't have statistical uncertainties"
+		  << std::endl;
+      }
+      continue;
+    }
+    else {
+      if(verbose) std::cout << "Found ParamHistFunc: " << param_func->GetName() << std::endl;
+    }
+
+    // Now, loop over the bins in this channel
+    // To Do: Check that the index convention
+    // still works for 2-d (ie matches the
+    // convention in ParamHistFunc, etc)
+    int num_bins = param_func->numBins();
+  
+    // Initialize the vector to the number of bins, allowing
+    // us to skip gamma's if they are constant
+
+    std::vector<BarlowCache> temp_cache( num_bins );
+    bool channel_has_stat_uncertainty=false;
+
+    for( Int_t bin_index = 0; bin_index < num_bins; ++bin_index ) {
+
+      // Create a cache object
+      BarlowCache cache;
+
+      // Get the gamma for this bin, and skip if it's constant
+      RooRealVar* gamma_stat = &(param_func->getParameter(bin_index));
+      if( gamma_stat->isConstant() ) {
+	if(verbose) std::cout << "Ignoring constant gamma: " << gamma_stat->GetName() << std::endl;
+	continue;
+      }
+      else {
+	cache.hasStatUncert=true;
+	channel_has_stat_uncertainty=true;
+	cache.gamma = gamma_stat;
+	_statUncertParams.insert( gamma_stat->GetName() );
+      }
+
+      // Store a snapshot of the bin center
+      RooArgSet* bin_center = (RooArgSet*) param_func->get( bin_index )->snapshot();
+      cache.bin_center = bin_center;
+      cache.observables = obsSet;
+
+      cache.binVolume = param_func->binVolume();
+
+      // Delete this part, simply a comment
+      RooArgList obs_list( *(cache.bin_center) );
+
+      // Get the gamma's constraint term
+      RooAbsReal* pois_mean = NULL;
+      RooRealVar* tau = NULL;
+      getStatUncertaintyConstraintTerm( &constraints, gamma_stat, pois_mean, tau );
+      if( !tau || !pois_mean ) {
+	std::cout << "Failed to find pois mean or tau parameter for " << gamma_stat->GetName() << std::endl;
+      }
+      else {
+	if(verbose) std::cout << "Found pois mean and tau for parameter: " << gamma_stat->GetName()
+			      << " tau: " << tau->GetName() << " " << tau->getVal()
+			      << " pois_mean: " << pois_mean->GetName() << " " << pois_mean->getVal()
+			      << std::endl;
+      }
+
+      cache.tau = tau;
+      cache.nom_pois_mean = pois_mean;
+
+      // Get the RooRealSumPdf
+      RooAbsPdf* sum_pdf = getSumPdfFromChannel( channelPdf );
+      if( sum_pdf == NULL )  {
+	std::cout << "Failed to find RooRealSumPdf in channel " <<  channel_name
+		  << ", therefor skipping this channel for analytic uncertainty minimization"
+		  << std::endl;
+	channel_has_stat_uncertainty=false;
+	break;
+      }
+      cache.sumPdf = sum_pdf;
+
+      // And set the data value for this bin
+      if( ChannelBinDataMap.find(channel_name) == ChannelBinDataMap.end() ) {
+	std::cout << "Error: channel with name: " << channel_name
+		  << " not found in BinDataMap" << std::endl;
+	throw runtime_error("BinDataMap");
+      }
+      double nData = ChannelBinDataMap[channel_name].at(bin_index);
+      cache.nData = nData;
+      
+      temp_cache.at(bin_index) = cache;
+      //_barlowCache[channel_name].at(bin_index) = cache;
+
+    } // End: Loop over bins
+    
+    if( channel_has_stat_uncertainty ) {
+      std::cout << "Adding channel: " << channel_name
+		<< " to the barlow cache" << std::endl;
+      _barlowCache[channel_name] = temp_cache;
+    }
+    
+
+  } // End: Loop over channels
+
+
+
+  // Successfully initialized the cache
+  // Printing some info
+  /*
+  std::map< std::string, std::vector< BarlowCache > >::iterator iter_cache;
+  for( iter_cache = _barlowCache.begin(); iter_cache != _barlowCache.end(); ++iter_cache ) {
+    
+    std::string channel_name = (*iter_cache).first;
+    std::vector< BarlowCache >& channel_cache = (*iter_cache).second;
+
+
+    for( unsigned int i = 0; i < channel_cache.size(); ++i ) {
+      BarlowCache& bin_cache = channel_cache.at(i);
+
+
+      RooRealVar* gamma = bin_cache.gamma;
+      RooRealVar* tau = bin_cache.tau;
+      RooAbsReal* pois_mean = bin_cache.nom_pois_mean;
+      RooAbsPdf* sum_pdf = (RooAbsPdf*) bin_cache.sumPdf;
+      double binVolume = bin_cache.binVolume;
+
+
+      if( !bin_cache.hasStatUncert ) {
+	std::cout << "Barlow Cache for Channel: " << channel_name
+		  << " Bin: " << i
+		  << " NO STAT UNCERT" 
+		  << std::endl;
+      }
+      else {
+      std::cout << "Barlow Cache for Channel: " << channel_name
+		<< " Bin: " << i
+		<< " gamma: " << gamma->GetName()
+		<< " tau: " << tau->GetName()
+		<< " pois_mean: " << pois_mean->GetName()
+		<< " sum_pdf: " << sum_pdf->GetName()
+		<< " binVolume: " << binVolume
+		<< std::endl;
+      }
+
+    }
+  }
+  */
+
+}
+
+
+//_____________________________________________________________________________
+RooArgSet* RooStats::HistFactory::RooBarlowBeestonLL::getParameters(const RooArgSet* depList, Bool_t stripDisconnected) const {
+
+  RooArgSet* allArgs = RooAbsArg::getParameters( depList, stripDisconnected );
+
+  TIterator* iter_args = allArgs->createIterator();
+  RooRealVar* arg;
+  while((arg=(RooRealVar*)iter_args->Next())) {
+    std::string arg_name = arg->GetName();
+
+    // If there is a gamma in the name,
+    // strip it from the list of dependencies
+
+    if( _statUncertParams.find(arg_name.c_str()) != _statUncertParams.end() ) {
+      allArgs->remove( *arg, kTRUE );
+    }
+
+  }
+
+  return allArgs;
+
+}
+
+
+/*
+//_____________________________________________________________________________
+const RooArgSet& RooStats::HistFactory::RooBarlowBeestonLL::bestFitParams() const 
+{
+  validateAbsMin() ;
+  return _paramAbsMin ;
+}
+
+
+//_____________________________________________________________________________
+const RooArgSet& RooStats::HistFactory::RooBarlowBeestonLL::bestFitObs() const 
+{
+  validateAbsMin() ;
+  return _obsAbsMin ;
+}
+*/
+
+
+
+//_____________________________________________________________________________
+/*
+RooAbsReal* RooStats::HistFactory::RooBarlowBeestonLL::createProfile(const RooArgSet& paramsOfInterest) 
+{
+  // Optimized implementation of createProfile for profile likelihoods.
+  // Return profile of original function in terms of stated parameters 
+  // of interest rather than profiling recursively.
+
+  return nll().createProfile(paramsOfInterest) ;
+}
+*/
+
+
+/*
+void RooStats::HistFactory::RooBarlowBeestonLL::FactorizePdf(const RooArgSet &observables, RooAbsPdf &pdf, RooArgList &obsTerms, RooArgList &constraints) const {
+  // utility function to factorize constraint terms from a pdf
+  // (from G. Petrucciani)
+  const std::type_info & id = typeid(pdf);
+  if (id == typeid(RooProdPdf)) {
+    RooProdPdf *prod = dynamic_cast<RooProdPdf *>(&pdf);
+    RooArgList list(prod->pdfList());
+    for (int i = 0, n = list.getSize(); i < n; ++i) {
+      RooAbsPdf *pdfi = (RooAbsPdf *) list.at(i);
+      FactorizePdf(observables, *pdfi, obsTerms, constraints);
+    }
+  } else if (id == typeid(RooSimultaneous) ) {    //|| id == typeid(RooSimultaneousOpt)) {
+    RooSimultaneous *sim  = dynamic_cast<RooSimultaneous *>(&pdf);
+    RooAbsCategoryLValue *cat = (RooAbsCategoryLValue *) sim->indexCat().Clone();
+    for (int ic = 0, nc = cat->numBins((const char *)0); ic < nc; ++ic) {
+      cat->setBin(ic);
+      FactorizePdf(observables, *sim->getPdf(cat->getLabel()), obsTerms, constraints);
+    }
+    delete cat;
+  } else if (pdf.dependsOn(observables)) {
+    if (!obsTerms.contains(pdf)) obsTerms.add(pdf);
+  } else {
+    if (!constraints.contains(pdf)) constraints.add(pdf);
+  }
+}
+*/                                         
+
+
+
+//_____________________________________________________________________________
+Double_t RooStats::HistFactory::RooBarlowBeestonLL::evaluate() const 
+{ 
+
+  /*
+  // Loop over the cached bins and channels
+  RooArgSet* channels = new RooArgSet();
+  RooArgSet* channelsWithConstraints = new RooArgSet();
+  RooStats::getChannelsFromModel( _pdf, channels, channelsWithConstraints );
+
+  // Loop over channels
+  TIterator* iter_channels = channelsWithConstraints->createIterator();
+  RooAbsPdf* channelPdf=NULL;
+  while(( channelPdf=(RooAbsPdf*)iter_channels->Next()  )) {
+    std::string channel_name = channelPdf->GetName(); //RooStats::channelNameFromPdf( channelPdf );
+  */
+
+  // Loop over the channels (keys to the map)
+  //clock_t time_before_setVal, time_after_setVal;
+  //time_before_setVal=clock();  
+  std::map< std::string, std::vector< BarlowCache > >::iterator iter_cache;
+  for( iter_cache = _barlowCache.begin(); iter_cache != _barlowCache.end(); ++iter_cache ) {
+    
+    std::string channel_name = (*iter_cache).first;
+    std::vector< BarlowCache >& channel_cache = (*iter_cache).second;
+
+    /* Slower way to find the channel vector:
+    // Get the vector of bin uncertainty caches for this channel
+    if( _barlowCache.find( channel_name ) == _barlowCache.end() ) {
+      std::cout << "Error: channel: " << channel_name 
+		<< " not found in barlow Cache" << std::endl; 
+      throw runtime_error("Channel not in barlow cache");
+    }
+
+    std::vector< BarlowCache >& channel_cache = _barlowCache[ channel_name ];
+    */
+
+    // Loop over the bins in the cache
+    // Set all gamma's to 0
+    for( unsigned int i = 0; i < channel_cache.size(); ++i ) {
+      BarlowCache& bin_cache = channel_cache.at(i);
+      if( !bin_cache.hasStatUncert ) continue;
+      RooRealVar* gamma = bin_cache.gamma;
+      gamma->setVal(0.0);
+    }
+    std::vector< double > nu_b_vec( channel_cache.size() );
+    for( unsigned int i = 0; i < channel_cache.size(); ++i ) {
+      BarlowCache& bin_cache = channel_cache.at(i);
+      if( !bin_cache.hasStatUncert ) continue;
+
+      RooAbsPdf* sum_pdf = (RooAbsPdf*) bin_cache.sumPdf;
+      RooArgSet* obsSet = bin_cache.observables;
+      double binVolume = bin_cache.binVolume;
+
+      bin_cache.SetBinCenter();
+      double nu_b = sum_pdf->getVal(*obsSet)*sum_pdf->expectedEvents(*obsSet)*binVolume;
+      nu_b_vec.at(i) = nu_b;
+    }
+
+    // Loop over the bins in the cache
+    // Set all gamma's to 1
+    for( unsigned int i = 0; i < channel_cache.size(); ++i ) {
+      BarlowCache& bin_cache = channel_cache.at(i);
+      if( !bin_cache.hasStatUncert ) continue;
+      RooRealVar* gamma = bin_cache.gamma;
+      gamma->setVal(1.0);
+    }
+    std::vector< double > nu_b_stat_vec( channel_cache.size() );
+    for( unsigned int i = 0; i < channel_cache.size(); ++i ) {
+      BarlowCache& bin_cache = channel_cache.at(i);
+      if( !bin_cache.hasStatUncert ) continue;
+
+      RooAbsPdf* sum_pdf = (RooAbsPdf*) bin_cache.sumPdf;
+      RooArgSet* obsSet = bin_cache.observables;
+      double binVolume = bin_cache.binVolume;
+      
+      bin_cache.SetBinCenter();
+      double nu_b_stat = sum_pdf->getVal(*obsSet)*sum_pdf->expectedEvents(*obsSet)*binVolume - nu_b_vec.at(i);
+      nu_b_stat_vec.at(i) = nu_b_stat;
+    }
+    //time_after_setVal=clock();  
+    
+    // Done with the first loops.
+    // Now evaluating the function
+
+    //clock_t time_before_eval, time_after_eval;
+
+    // Loop over the bins in the cache
+    //time_before_eval=clock();
+    for( unsigned int i = 0; i < channel_cache.size(); ++i ) {
+      
+      BarlowCache& bin_cache = channel_cache.at(i);
+
+      if( !bin_cache.hasStatUncert ) {
+	//std::cout << "Bin: " << i << " of " << channel_cache.size() 
+	//	  << " in channel: " << channel_name
+	//	  << " doesn't have stat uncertainties" << std::endl;
+	continue;
+      }
+
+      // Set the observable to the bin center
+      bin_cache.SetBinCenter();
+
+      // Get the cached objects
+      RooRealVar* gamma = bin_cache.gamma;
+      RooRealVar* tau = bin_cache.tau;
+      RooAbsReal* pois_mean = bin_cache.nom_pois_mean;
+      //RooAbsPdf* sum_pdf = (RooAbsPdf*) bin_cache.sumPdf;
+      //RooArgSet* obsSet = bin_cache.observables;
+      //double binVolume = bin_cache.binVolume;
+
+      // Get the values necessary for
+      // the analytic minimization
+      double nu_b = nu_b_vec.at(i);
+      double nu_b_stat = nu_b_stat_vec.at(i);
+
+      double tau_val = tau->getVal();
+      double nData = bin_cache.nData;
+      double m_val = pois_mean->getVal();
+
+      double A = nu_b_stat*nu_b_stat + tau_val*nu_b_stat;
+      double B = nu_b*tau_val + nu_b*nu_b_stat - nData*nu_b_stat - m_val*nu_b_stat;
+      double C = -1*m_val*nu_b;
+
+      double discrim = B*B-4*A*C;
+
+      if( discrim < 0 ) {
+	std::cout << "Warning: Discriminant (B*B - 4AC) < 0" << std::endl;
+	std::cout << "Warning: Taking B*B - 4*A*C == 0Discriminant (B*B - 4AC) < 0" << std::endl;
+	discrim=0;
+	//throw runtime_error("BarlowBeestonLL::evaluate() : B*B - 4AC < 0");
+      }
+      if( A <= 0 ) {
+	std::cout << "Warning: A <= 0" << std::endl;
+	throw runtime_error("BarlowBeestonLL::evaluate() : A < 0");
+      }
+
+      double gamma_hat_hat = ( -1*B + TMath::Sqrt(discrim) ) / (2*A);
+
+      // Check for NAN
+      if( TMath::IsNaN(gamma_hat_hat) ) { 
+	std::cout << "ERROR: gamma hat hat is NAN" << std::endl;
+	throw runtime_error("BarlowBeestonLL::evaluate() : gamma hat hat is NAN");
+      }
+
+      if( gamma_hat_hat <= 0 ) {
+	std::cout << "WARNING: gamma hat hat <= 0.  Setting to 0" << std::endl;
+	gamma_hat_hat = 0;
+      }
+      
+      /*
+      std::cout << "n: " << bin_cache.nData << " "
+		<< "nu_stat: " << nu_b_stat << " "
+		<< "nu: " << nu_b << " "
+		<< "tau: " << tau->getVal() << " "
+		<< "m: " << pois_mean->getVal() << " "
+		<< "A: " << A << " "
+		<< "B: " << B << " "
+		<< "C: " << C << " "
+		<< "gamma hat hat: " << gamma_hat_hat 
+		<< std::endl;
+      */
+
+      gamma->setVal( gamma_hat_hat );
+
+    }
+
+    //time_after_eval=clock();
+
+    //float time_setVal = ((float) time_after_setVal - (float) time_before_setVal) / ((float) CLOCKS_PER_SEC);
+    //float time_eval   = ((float) time_after_eval - (float) time_before_eval) / ((float) CLOCKS_PER_SEC);
+
+    /*
+    std::cout << "Barlow timing for channel: " << channel_name
+	      << " SetVal: " << time_setVal
+	      << " Eval: " << time_eval
+	      << std::endl;
+    */
+  } 
+
+
+  return _nll;  
+
+}
+
+
+
+/*
+//_____________________________________________________________________________
+void RooStats::HistFactory::RooBarlowBeestonLL::validateAbsMin() const 
+{
+  // Check that parameters and likelihood value for 'best fit' are still valid. If not,
+  // because the best fit has never been calculated, or because constant parameters have
+  // changed value or parameters have changed const/float status, the minimum is recalculated
+
+  // Check if constant status of any of the parameters have changed
+  if (_absMinValid) {
+    _piter->Reset() ;
+    RooAbsArg* par ;
+    while((par=(RooAbsArg*)_piter->Next())) {
+      if (_paramFixed[par->GetName()] != par->isConstant()) {
+	cxcoutI(Minimization) << "RooStats::HistFactory::RooBarlowBeestonLL::evaluate(" << GetName() << ") constant status of parameter " << par->GetName() << " has changed from " 
+				<< (_paramFixed[par->GetName()]?"fixed":"floating") << " to " << (par->isConstant()?"fixed":"floating") 
+				<< ", recalculating absolute minimum" << endl ;
+	_absMinValid = kFALSE ;
+	break ;
+      }
+    }
+  }
+
+
+  // If we don't have the absolute minimum w.r.t all observables, calculate that first
+  if (!_absMinValid) {
+
+    cxcoutI(Minimization) << "RooStats::HistFactory::RooBarlowBeestonLL::evaluate(" << GetName() << ") determining minimum likelihood for current configurations w.r.t all observable" << endl ;
+
+
+    // Save current values of non-marginalized parameters
+    RooArgSet* obsStart = (RooArgSet*) _obs.snapshot(kFALSE) ;
+
+    // Start from previous global minimum 
+    if (_paramAbsMin.getSize()>0) {
+      const_cast<RooSetProxy&>(_par).assignValueOnly(_paramAbsMin) ;
+    }
+    if (_obsAbsMin.getSize()>0) {
+      const_cast<RooSetProxy&>(_obs).assignValueOnly(_obsAbsMin) ;
+    }
+
+    // Find minimum with all observables floating
+    const_cast<RooSetProxy&>(_obs).setAttribAll("Constant",kFALSE) ;  
+    _minuit->migrad() ;
+
+    // Save value and remember
+    _absMin = _nll ;
+    _absMinValid = kTRUE ;
+
+    // Save parameter values at abs minimum as well
+    _paramAbsMin.removeAll() ;
+
+    // Only store non-constant parameters here!
+    RooArgSet* tmp = (RooArgSet*) _par.selectByAttrib("Constant",kFALSE) ;
+    _paramAbsMin.addClone(*tmp) ;
+    delete tmp ;
+
+    _obsAbsMin.addClone(_obs) ;
+
+    // Save constant status of all parameters
+    _piter->Reset() ;
+    RooAbsArg* par ;
+    while((par=(RooAbsArg*)_piter->Next())) {
+      _paramFixed[par->GetName()] = par->isConstant() ;
+    }
+    
+    if (dologI(Minimization)) {
+      cxcoutI(Minimization) << "RooStats::HistFactory::RooBarlowBeestonLL::evaluate(" << GetName() << ") minimum found at (" ;
+
+      RooAbsReal* arg ;
+      Bool_t first=kTRUE ;
+      _oiter->Reset() ;
+      while ((arg=(RooAbsReal*)_oiter->Next())) {
+	ccxcoutI(Minimization) << (first?"":", ") << arg->GetName() << "=" << arg->getVal() ;	
+	first=kFALSE ;
+      }      
+      ccxcoutI(Minimization) << ")" << endl ;            
+    }
+
+    // Restore original parameter values
+    const_cast<RooSetProxy&>(_obs) = *obsStart ;
+    delete obsStart ;
+
+  }
+}
+*/
+
+
+//_____________________________________________________________________________
+Bool_t RooStats::HistFactory::RooBarlowBeestonLL::redirectServersHook(const RooAbsCollection& /*newServerList*/, Bool_t /*mustReplaceAll*/, 
+					 Bool_t /*nameChange*/, Bool_t /*isRecursive*/) 
+{ 
+  /*
+  if (_minuit) {
+    delete _minuit ;
+    _minuit = 0 ;
+  }
+  */
+  return kFALSE ;
+} 
+
+
diff --git a/roofit/histfactory/src/Sample.cxx b/roofit/histfactory/src/Sample.cxx
index 12fee53..fa06822 100644
--- a/roofit/histfactory/src/Sample.cxx
+++ b/roofit/histfactory/src/Sample.cxx
@@ -1,5 +1,6 @@
 
 #include "RooStats/HistFactory/Sample.h"
+#include "RooStats/HistFactory/HistFactoryException.h"
 
 //#include "TClass.h"
 
@@ -18,8 +19,9 @@ RooStats::HistFactory::Sample::Sample(std::string SampName) :
   fNormalizeByTheory(true), fStatErrorActivate(false)  { ; }
 
 
-TH1* RooStats::HistFactory::Sample::GetHisto() {
-  return (TH1*) fhNominal.GetObject();
+TH1* RooStats::HistFactory::Sample::GetHisto()  {
+  TH1* histo = (TH1*) fhNominal.GetObject();
+  return histo;
 }
 
 
diff --git a/roofit/histfactory/src/Systematics.cxx b/roofit/histfactory/src/Systematics.cxx
index dde21b6..b8c2466 100644
--- a/roofit/histfactory/src/Systematics.cxx
+++ b/roofit/histfactory/src/Systematics.cxx
@@ -17,7 +17,7 @@ RooStats::HistFactory::Constraint::Type RooStats::HistFactory::Constraint::GetTy
 
   if( Name == "" ) {
     std::cout << "Error: Given empty name for ConstraintType" << std::endl;
-    throw bad_hf;
+    throw hf_exc();
   }
   
   else if ( Name == "Gaussian" || Name == "Gauss" ) {
@@ -30,13 +30,15 @@ RooStats::HistFactory::Constraint::Type RooStats::HistFactory::Constraint::GetTy
 
   else {
     std::cout << "Error: Unknown name given for Constraint Type: " << Name << std::endl;
-    throw bad_hf;
+    throw hf_exc();
   }
 
 }
 
 // Norm Factor
-RooStats::HistFactory::NormFactor::NormFactor() {;}
+RooStats::HistFactory::NormFactor::NormFactor() : fName(""), fVal(1.0), 
+						  fLow(1.0), fHigh(1.0), 
+						  fConst(true) {;}
 
 void RooStats::HistFactory::NormFactor::Print( std::ostream& stream ) {
   stream << "\t \t Name: " << fName
@@ -58,11 +60,13 @@ void RooStats::HistFactory::OverallSys::Print( std::ostream& stream ) {
 // HistoSys
 
 TH1* RooStats::HistFactory::HistoSys::GetHistoLow() {
-  return (TH1*) fhLow.GetObject();
+  TH1* histo_low = (TH1*) fhLow.GetObject();
+  return histo_low;
 }
 
 TH1* RooStats::HistFactory::HistoSys::GetHistoHigh() {
-  return (TH1*) fhHigh.GetObject();
+  TH1* histo_high = (TH1*) fhHigh.GetObject();
+  return histo_high;
 }
 
 void RooStats::HistFactory::HistoSys::Print( std::ostream& stream ) {
@@ -83,12 +87,26 @@ void RooStats::HistFactory::HistoSys::writeToFile( std::string FileName, std::st
   // changes the name of the local file and histograms
   
   TH1* histLow = GetHistoLow();
+  if( histLow==NULL ) {
+    std::cout << "Error: Cannot write " << GetName()
+	      << " to file: " << FileName
+	      << " HistoLow is NULL" 
+	      << std::endl;
+    throw hf_exc();
+  }
   histLow->Write();
   fInputFileLow = FileName;
   fHistoPathLow = DirName;
   fHistoNameLow = histLow->GetName(); 
 
   TH1* histHigh = GetHistoHigh();
+  if( histHigh==NULL ) {
+    std::cout << "Error: Cannot write " << GetName()
+	      << " to file: " << FileName
+	      << " HistoHigh is NULL" 
+	      << std::endl;
+    throw hf_exc();
+  }
   histHigh->Write();
   fInputFileHigh = FileName;
   fHistoPathHigh = DirName;
@@ -104,7 +122,8 @@ void RooStats::HistFactory::HistoSys::writeToFile( std::string FileName, std::st
 // Shape Sys
 
 TH1* RooStats::HistFactory::ShapeSys::GetErrorHist() {
-  return (TH1*) fhError.GetObject();
+  TH1* error_hist = (TH1*) fhError.GetObject();
+  return error_hist;
 }
 
 
@@ -119,6 +138,13 @@ void RooStats::HistFactory::ShapeSys::Print( std::ostream& stream ) {
 void RooStats::HistFactory::ShapeSys::writeToFile( std::string FileName, std::string DirName ) {
 
   TH1* histError = GetErrorHist();
+  if( histError==NULL ) {
+    std::cout << "Error: Cannot write " << GetName()
+	      << " to file: " << FileName
+	      << " ErrorHist is NULL" 
+	      << std::endl;
+    throw hf_exc();
+  }
   histError->Write();
   fInputFile = FileName;
   fHistoPath = DirName;
@@ -144,11 +170,13 @@ void RooStats::HistFactory::HistoFactor::Print( std::ostream& stream ) {
 
 
 TH1* RooStats::HistFactory::HistoFactor::GetHistoLow() {
-  return (TH1*) fhLow.GetObject();
+  TH1* histo_low = (TH1*) fhLow.GetObject();
+  return histo_low;
 }
 
 TH1* RooStats::HistFactory::HistoFactor::GetHistoHigh() {
-  return (TH1*) fhHigh.GetObject();
+  TH1* histo_high = (TH1*) fhHigh.GetObject();
+  return histo_high;
 }
 
 
@@ -159,12 +187,26 @@ void RooStats::HistFactory::HistoFactor::writeToFile( std::string FileName, std:
   // changes the name of the local file and histograms
   
   TH1* histLow = GetHistoLow();
+  if( histLow==NULL ) {
+    std::cout << "Error: Cannot write " << GetName()
+	      << " to file: " << FileName
+	      << " HistoLow is NULL" 
+	      << std::endl;
+    throw hf_exc();
+  }
   histLow->Write();
   fInputFileLow = FileName;
   fHistoPathLow = DirName;
   fHistoNameLow = histLow->GetName(); 
 
   TH1* histHigh = GetHistoHigh();
+  if( histHigh==NULL ) {
+    std::cout << "Error: Cannot write " << GetName()
+	      << " to file: " << FileName
+	      << " HistoHigh is NULL" 
+	      << std::endl;
+    throw hf_exc();
+  }
   histHigh->Write();
   fInputFileHigh = FileName;
   fHistoPathHigh = DirName;
@@ -211,6 +253,10 @@ void RooStats::HistFactory::StatError::writeToFile( std::string OutputFileName,
     std::string statErrorHistName = "statisticalErrors";
     
     TH1* hStatError = GetErrorHist();
+    if( hStatError == NULL ) {
+      std::cout << "Error: Stat Error error hist is NULL" << std::endl;
+      throw hf_exc();
+    }
     hStatError->Write(statErrorHistName.c_str());
     
     fInputFile = OutputFileName;
diff --git a/roofit/roofit/inc/RooNDKeysPdf.h b/roofit/roofit/inc/RooNDKeysPdf.h
index b0e6e79..3b03751 100644
--- a/roofit/roofit/inc/RooNDKeysPdf.h
+++ b/roofit/roofit/inc/RooNDKeysPdf.h
@@ -1,7 +1,7 @@
 /*****************************************************************************
  * Project: RooFit                                                           *
  * Package: RooFitModels                                                     *
- *    File: $Id: RooNDKeysPdf.h 44077 2012-05-02 17:10:21Z moneta $
+ *    File: $Id: RooNDKeysPdf.h 44368 2012-05-30 15:38:44Z axel $
  * Authors:                                                                  *
  *   Max Baak, CERN, mbaak at cern.ch *
  *                                                                           *
@@ -143,7 +143,7 @@ protected:
   mutable std::vector<itVec> _sortTVIdcs;
 #endif
 
-  mutable std::vector<string> _varName;
+  mutable std::vector<std::string> _varName;
   mutable std::vector<Double_t> _rho;
   mutable RooArgSet _dataVars;
   mutable std::vector<Double_t> _x;
diff --git a/roofit/roofit/src/Roo2DKeysPdf.cxx b/roofit/roofit/src/Roo2DKeysPdf.cxx
index 88ef4f0..d4c7b5d 100644
--- a/roofit/roofit/src/Roo2DKeysPdf.cxx
+++ b/roofit/roofit/src/Roo2DKeysPdf.cxx
@@ -1,7 +1,7 @@
 /*****************************************************************************
  * Project: RooFit                                                           *
  * Package: RooFitModels                                                     *
- * @(#)root/roofit:$Id: Roo2DKeysPdf.cxx 24286 2008-06-16 15:47:04Z wouter $
+ * @(#)root/roofit:$Id: Roo2DKeysPdf.cxx 44368 2012-05-30 15:38:44Z axel $
  * Authors:                                                                  *
  *   AB, Adrian Bevan, Liverpool University, bevan at slac.stanford.edu         *
  *                                                                           *
@@ -37,6 +37,8 @@
 
 //#include <math.h>
 
+using namespace std;
+
 ClassImp(Roo2DKeysPdf)
 
 
diff --git a/roofit/roofit/src/RooBernstein.cxx b/roofit/roofit/src/RooBernstein.cxx
index 0a3f956..fa8bb89 100644
--- a/roofit/roofit/src/RooBernstein.cxx
+++ b/roofit/roofit/src/RooBernstein.cxx
@@ -1,7 +1,7 @@
 /*****************************************************************************
  * Project: RooFit                                                           *
  * Package: RooFitModels                                                     *
- * @(#)root/roofit:$Id: RooBernstein.cxx 41676 2011-11-01 15:44:30Z wouter $
+ * @(#)root/roofit:$Id: RooBernstein.cxx 44438 2012-06-01 08:19:35Z moneta $
  * Authors:                                                                  *
  *   Kyle Cranmer
  *                                                                           *
@@ -78,18 +78,45 @@ RooBernstein::RooBernstein(const RooBernstein& other, const char* name) :
 Double_t RooBernstein::evaluate() const 
 {
 
-  Double_t xmin = _x.min(); Double_t xmax = _x.max();
-  Int_t degree= _coefList.getSize()-1; // n+1 polys of degree n
+  Double_t xmin = _x.min();
+  Double_t x = (_x - xmin) / (_x.max() - xmin); // rescale to [0,1]
+  Int_t degree = _coefList.getSize() - 1; // n+1 polys of degree n
+  RooFIter iter = _coefList.fwdIterator();
 
-  Double_t temp=0, tempx=0;
-  RooFIter iter = _coefList.fwdIterator() ;
-  for (int i=0; i<=degree; ++i){
-    tempx = (_x-xmin)/(xmax-xmin); // rescale to [0,1]
-    temp += ((RooAbsReal*)iter.next())->getVal() *
-      TMath::Binomial(degree, i) * pow(tempx,i) * pow(1-tempx,degree-i);
+  if(degree == 0) {
+
+    return ((RooAbsReal *)iter.next())->getVal();
+
+  } else if(degree == 1) {
+
+    Double_t a0 = ((RooAbsReal *)iter.next())->getVal(); // c0
+    Double_t a1 = ((RooAbsReal *)iter.next())->getVal(); // c1 - c0
+    return a1 * x + a0;
+
+  } else if(degree == 2) {
+
+    Double_t a0 = ((RooAbsReal *)iter.next())->getVal(); // c0
+    Double_t a1 = 2 * (((RooAbsReal *)iter.next())->getVal() - a0); // 2 * (c1 - c0)
+    Double_t a2 = ((RooAbsReal *)iter.next())->getVal() - a1 - a0; // c0 - 2 * c1 + c2
+    return (a2 * x + a1) * x + a0;
+
+  } else if(degree > 2) {
+
+    Double_t t = x;
+    Double_t s = 1 - x;
+
+    Double_t result = ((RooAbsReal *)iter.next())->getVal() * s;    
+    for(Int_t i = 1; i < degree; i++) {
+      result = (result + t * TMath::Binomial(degree, i) * ((RooAbsReal *)iter.next())->getVal()) * s;
+      t *= x;
+    }
+    result += t * ((RooAbsReal *)iter.next())->getVal(); 
+
+    return result;
   }
-  return temp;
 
+  // in case list of arguments passed is empty
+  return TMath::SignalingNaN();
 }
 
 
diff --git a/roofit/roofitcore/inc/RooAbsData.h b/roofit/roofitcore/inc/RooAbsData.h
index 46047e9..7acb7bc 100644
--- a/roofit/roofitcore/inc/RooAbsData.h
+++ b/roofit/roofitcore/inc/RooAbsData.h
@@ -213,6 +213,7 @@ public:
 
   static void setDefaultStorageType(StorageType s) ;
 
+  static StorageType getDefaultStorageType();
 
 protected:
 
diff --git a/roofit/roofitcore/inc/RooCacheManager.h b/roofit/roofitcore/inc/RooCacheManager.h
index 172412c..7c83d45 100644
--- a/roofit/roofitcore/inc/RooCacheManager.h
+++ b/roofit/roofitcore/inc/RooCacheManager.h
@@ -1,7 +1,7 @@
 /*****************************************************************************
  * Project: RooFit                                                           *
  * Package: RooFitCore                                                       *
- *    File: $Id: RooCacheManager.h 42984 2012-02-13 15:30:31Z wouter $
+ *    File: $Id: RooCacheManager.h 44368 2012-05-30 15:38:44Z axel $
  * Authors:                                                                  *
  *   WV, Wouter Verkerke, UC Santa Barbara, verkerke at slac.stanford.edu       *
  *   DK, David Kirkby,    UC Irvine,         dkirkby at uci.edu                 *
@@ -18,7 +18,6 @@
 
 #include "Rtypes.h"
 
-#include "Riostream.h"
 #include "RooMsgService.h"
 #include "RooNormSetCache.h"
 #include "RooAbsReal.h"
@@ -94,12 +93,12 @@ public:
 
   void wireCache() {
     if (_size==0) {
-      oocoutI(_owner,Optimization) << "RooCacheManager::wireCache(" << _owner->GetName() << ") no cached elements!" << endl ;
+      oocoutI(_owner,Optimization) << "RooCacheManager::wireCache(" << _owner->GetName() << ") no cached elements!" << std::endl ;
     } else if (_size==1) {
-      oocoutI(_owner,Optimization) << "RooCacheManager::wireCache(" << _owner->GetName() << ") now wiring cache" << endl ;
+      oocoutI(_owner,Optimization) << "RooCacheManager::wireCache(" << _owner->GetName() << ") now wiring cache" << std::endl ;
       _wired=kTRUE ;
     } else if (_size>1) {
-      oocoutI(_owner,Optimization) << "RooCacheManager::wireCache(" << _owner->GetName() << ") cache cannot be wired because it contains more than one element" << endl ; 
+      oocoutI(_owner,Optimization) << "RooCacheManager::wireCache(" << _owner->GetName() << ") cache cannot be wired because it contains more than one element" << std::endl ; 
     }
   }
  
@@ -168,7 +167,7 @@ RooCacheManager<T>::RooCacheManager(const RooCacheManager& other, RooAbsArg* own
   _wired = kFALSE ;
   _lastIndex = -1 ;
 
-//   cout << "RooCacheManager:cctor(" << this << ")" << endl ;
+//   cout << "RooCacheManager:cctor(" << this << ")" << std::endl ;
 
   Int_t i ;
   for (i=0 ; i<other._size ; i++) {    
@@ -317,7 +316,7 @@ T* RooCacheManager<T>::getObjByIndex(Int_t index) const
 
   if (index<0||index>=_size) {
     oocoutE(_owner,ObjectHandling) << "RooCacheManager::getNormListByIndex: ERROR index (" 
-				   << index << ") out of range [0," << _size-1 << "]" << endl ;
+				   << index << ") out of range [0," << _size-1 << "]" << std::endl ;
     return 0 ;
   }
   return _object[index] ;
@@ -330,7 +329,7 @@ const RooNameSet* RooCacheManager<T>::nameSet1ByIndex(Int_t index) const
 
   if (index<0||index>=_size) {
     oocoutE(_owner,ObjectHandling) << "RooCacheManager::getNormListByIndex: ERROR index (" 
-				   << index << ") out of range [0," << _size-1 << "]" << endl ;
+				   << index << ") out of range [0," << _size-1 << "]" << std::endl ;
     return 0 ;
   }
   return &_nsetCache[index].nameSet1() ;
@@ -343,7 +342,7 @@ const RooNameSet* RooCacheManager<T>::nameSet2ByIndex(Int_t index) const
 
   if (index<0||index>=_size) {
     oocoutE(_owner,ObjectHandling) << "RooCacheManager::getNormListByIndex: ERROR index (" 
-				   << index << ") out of range [0," << _size-1 << "]" << endl ;
+				   << index << ") out of range [0," << _size-1 << "]" << std::endl ;
     return 0 ;
   }
   return &_nsetCache[index].nameSet2() ;
diff --git a/roofit/roofitcore/inc/RooFitResult.h b/roofit/roofitcore/inc/RooFitResult.h
index bdbf853..6e517f6 100644
--- a/roofit/roofitcore/inc/RooFitResult.h
+++ b/roofit/roofitcore/inc/RooFitResult.h
@@ -79,8 +79,8 @@ public:
   }
 
   inline UInt_t numStatusHistory() const { return _statusHistory.size() ; }
-  Int_t statusCodeHistory(UInt_t icycle) ;
-  const char* statusLabelHistory(UInt_t icycle) ;
+  Int_t statusCodeHistory(UInt_t icycle) const ;
+  const char* statusLabelHistory(UInt_t icycle) const ;
 
   inline Int_t covQual() const { 
     // Return MINUIT quality code of covariance matrix
diff --git a/roofit/roofitcore/inc/RooGlobalFunc.h b/roofit/roofitcore/inc/RooGlobalFunc.h
index 5ba1e45..fd813b5 100644
--- a/roofit/roofitcore/inc/RooGlobalFunc.h
+++ b/roofit/roofitcore/inc/RooGlobalFunc.h
@@ -183,6 +183,7 @@ RooCmdArg SplitRange(Bool_t flag=kTRUE) ;
 RooCmdArg SumCoefRange(const char* rangeName) ;
 RooCmdArg Constrain(const RooArgSet& params) ;
 RooCmdArg GlobalObservables(const RooArgSet& globs) ;
+RooCmdArg GlobalObservablesTag(const char* tagName) ;
 RooCmdArg Constrained() ;
 RooCmdArg ExternalConstraints(const RooArgSet& constraintPdfs) ;
 RooCmdArg PrintEvalErrors(Int_t numErrors) ;
diff --git a/roofit/roofitcore/inc/RooMinimizerFcn.h b/roofit/roofitcore/inc/RooMinimizerFcn.h
index 27a084f..ccbeeb3 100644
--- a/roofit/roofitcore/inc/RooMinimizerFcn.h
+++ b/roofit/roofitcore/inc/RooMinimizerFcn.h
@@ -1,7 +1,7 @@
 /*****************************************************************************
  * Project: RooFit                                                           *
  * Package: RooFitCore                                                       * 
- * @(#)root/roofitcore:$Id: RooMinimizerFcn.h 30408 2009-09-24 15:03:37Z wouter $
+ * @(#)root/roofitcore:$Id: RooMinimizerFcn.h 44381 2012-05-31 06:45:52Z moneta $
  * Authors:                                                                  *
  *   AL, Alfio Lazzaro,   INFN Milan,        alfio.lazzaro at mi.infn.it        *
  *                                                                           *
@@ -72,6 +72,7 @@ class RooMinimizerFcn : public ROOT::Math::IBaseFunctionMultiDim {
 
 
   virtual double DoEval(const double * x) const;  
+  void updateFloatVec() ;
 
 private:
   
@@ -88,6 +89,7 @@ private:
   bool _verbose;
 
   RooArgList* _floatParamList;
+  std::vector<RooAbsArg*> _floatParamVec ;
   RooArgList* _constParamList;
   RooArgList* _initFloatParamList;
   RooArgList* _initConstParamList;
diff --git a/roofit/roofitcore/inc/RooMultiVarGaussian.h b/roofit/roofitcore/inc/RooMultiVarGaussian.h
index a9e08d1..d9f555a 100644
--- a/roofit/roofitcore/inc/RooMultiVarGaussian.h
+++ b/roofit/roofitcore/inc/RooMultiVarGaussian.h
@@ -1,7 +1,7 @@
 /*****************************************************************************
  * Project: RooFit                                                           *
  * Package: RooFitModels                                                     *
- *    File: $Id: RooMultiVarGaussian.h 42242 2011-11-25 14:02:26Z wouter $
+ *    File: $Id: RooMultiVarGaussian.h 44368 2012-05-30 15:38:44Z axel $
  * Authors:                                                                  *
  *   WV, Wouter Verkerke, UC Santa Barbara, verkerke at slac.stanford.edu       *
  *   DK, David Kirkby,    UC Irvine,         dkirkby at uci.edu                 *
@@ -55,15 +55,15 @@ public:
   public:
     TMatrixD    S22bar ;
     Double_t    S22det ;
-    vector<int> pmap ;
+    std::vector<int> pmap ;
     Int_t       nint ;
   } ;
 
   class GenData {
   public:
     TMatrixD    UT ;
-    vector<int> omap ;
-    vector<int> pmap ;
+    std::vector<int> omap ;
+    std::vector<int> pmap ;
     TVectorD    mu1 ;
     TVectorD    mu2 ;
     TMatrixD    S12S22I ;
@@ -83,11 +83,11 @@ public:
     Int_t b3 ;
   } ;
 
-  static void blockDecompose(const TMatrixD& input, const vector<int>& map1, const vector<int>& map2, TMatrixDSym& S11, TMatrixD& S12, TMatrixD& S21, TMatrixDSym& S22) ;
+  static void blockDecompose(const TMatrixD& input, const std::vector<int>& map1, const std::vector<int>& map2, TMatrixDSym& S11, TMatrixD& S12, TMatrixD& S21, TMatrixDSym& S22) ;
 
 protected:
   
-  void decodeCode(Int_t code, vector<int>& map1, vector<int>& map2) const;
+  void decodeCode(Int_t code, std::vector<int>& map1, std::vector<int>& map2) const;
   AnaIntData& anaIntData(Int_t code) const ;
   GenData& genData(Int_t code) const ;
 
diff --git a/roofit/roofitcore/src/RooAbsData.cxx b/roofit/roofitcore/src/RooAbsData.cxx
index 4de69b4..2d69c8f 100644
--- a/roofit/roofitcore/src/RooAbsData.cxx
+++ b/roofit/roofitcore/src/RooAbsData.cxx
@@ -1,7 +1,7 @@
 /*****************************************************************************
  * Project: RooFit                                                           *
  * Package: RooFitCore                                                       *
- * @(#)root/roofitcore:$Id: RooAbsData.cxx 43071 2012-02-21 17:01:01Z axel $
+ * @(#)root/roofitcore:$Id: RooAbsData.cxx 44447 2012-06-01 09:58:22Z moneta $
  * Authors:                                                                  *
  *   WV, Wouter Verkerke, UC Santa Barbara, verkerke at slac.stanford.edu       *
  *   DK, David Kirkby,    UC Irvine,         dkirkby at uci.edu                 *
@@ -74,6 +74,13 @@ void RooAbsData::setDefaultStorageType(RooAbsData::StorageType s)
 
 
 //_____________________________________________________________________________
+RooAbsData::StorageType RooAbsData::getDefaultStorageType( ) 
+{
+  return defaultStorageType;
+}
+
+
+//_____________________________________________________________________________
 void RooAbsData::claimVars(RooAbsData* data) 
 {
   _dcc[data]++ ;
diff --git a/roofit/roofitcore/src/RooAbsPdf.cxx b/roofit/roofitcore/src/RooAbsPdf.cxx
index 8a3303f..ce37d8b 100644
--- a/roofit/roofitcore/src/RooAbsPdf.cxx
+++ b/roofit/roofitcore/src/RooAbsPdf.cxx
@@ -1,7 +1,7 @@
 /*****************************************************************************
  * Project: RooFit                                                           *
  * Package: RooFitCore                                                       *
- * @(#)root/roofitcore:$Id: RooAbsPdf.cxx 43683 2012-04-10 16:46:02Z pcanal $
+ * @(#)root/roofitcore:$Id: RooAbsPdf.cxx 44381 2012-05-31 06:45:52Z moneta $
  * Authors:                                                                  *
  *   WV, Wouter Verkerke, UC Santa Barbara, verkerke at slac.stanford.edu       *
  *   DK, David Kirkby,    UC Irvine,         dkirkby at uci.edu                 *
@@ -624,6 +624,13 @@ Double_t RooAbsPdf::getLogVal(const RooArgSet* nset) const
 
     return log((double)0);
   }
+
+  if (TMath::IsNaN(prob)) {
+    logEvalError("getLogVal() top-level p.d.f evaluates to NaN") ;
+
+    return log((double)0);
+    
+  }
   return log(prob);
 }
 
@@ -653,6 +660,18 @@ Double_t RooAbsPdf::extendedTerm(Double_t observed, const RooArgSet* nset) const
     return 0;
   }
 
+
+  // Explicitly handle case Nobs=Nexp=0
+  if (fabs(expected)<1e-10 && fabs(observed)<1e-10) {
+    return 0 ;
+  }
+
+  // Check for errors in Nexpected
+  if (expected<0 || TMath::IsNaN(expected)) {
+    logEvalError("extendedTerm #expected events is <0 or NaN") ;
+    return 0 ;
+  }
+
   // calculate and return the negative log-likelihood of the Poisson
   // factor for this dataset, dropping the constant log(observed!)
   Double_t extra= expected - observed*log(expected);
@@ -728,6 +747,7 @@ RooAbsReal* RooAbsPdf::createNLL(RooAbsData& data, const RooLinkedList& cmdList)
 
   pc.defineString("rangeName","RangeWithName",0,"",kTRUE) ;
   pc.defineString("addCoefRange","SumCoefRange",0,"") ;
+  pc.defineString("globstag","GlobalObservablesTag",0,"") ;
   pc.defineDouble("rangeLo","Range",0,-999.) ;
   pc.defineDouble("rangeHi","Range",1,-999.) ;
   pc.defineInt("splitRange","SplitRange",0,0) ;
@@ -743,8 +763,8 @@ RooAbsReal* RooAbsPdf::createNLL(RooAbsData& data, const RooLinkedList& cmdList)
   pc.defineSet("extCons","ExternalConstraints",0,0) ;
   pc.defineMutex("Range","RangeWithName") ;
   pc.defineMutex("Constrain","Constrained") ;
-  
-  
+  pc.defineMutex("GlobalObservables","GlobalObservablesTag") ;
+    
   // Process and check varargs 
   pc.process(cmdList) ;
   if (!pc.ok(kTRUE)) {
@@ -754,6 +774,7 @@ RooAbsReal* RooAbsPdf::createNLL(RooAbsData& data, const RooLinkedList& cmdList)
   // Decode command line arguments
   const char* rangeName = pc.getString("rangeName",0,kTRUE) ;
   const char* addCoefRangeName = pc.getString("addCoefRange",0,kTRUE) ;
+  const char* globsTag = pc.getString("globstag",0,kTRUE) ;
   Int_t ext      = pc.getInt("ext") ;
   Int_t numcpu   = pc.getInt("numcpu") ;
   Int_t splitr   = pc.getInt("splitRange") ;
@@ -767,6 +788,13 @@ RooAbsReal* RooAbsPdf::createNLL(RooAbsData& data, const RooLinkedList& cmdList)
   }
   RooArgSet* cPars = pc.getSet("cPars") ;
   RooArgSet* glObs = pc.getSet("glObs") ;
+  if (pc.hasProcessed("GlobalObservablesTag")) {
+    if (glObs) delete glObs ;
+    RooArgSet* allVars = getVariables() ;
+    glObs = (RooArgSet*) allVars->selectByAttrib(globsTag,kTRUE) ;
+    cout << "WVE debug globs from tag " << globsTag << " = " << *glObs << endl ;
+    delete allVars ;
+  }
   Bool_t doStripDisconnected=kFALSE ;
 
   // If no explicit list of parameters to be constrained is specified apply default algorithm
@@ -977,7 +1005,7 @@ RooFitResult* RooAbsPdf::fitTo(RooAbsData& data, const RooLinkedList& cmdList)
   RooCmdConfig pc(Form("RooAbsPdf::fitTo(%s)",GetName())) ;
 
   RooLinkedList fitCmdList(cmdList) ;
-  RooLinkedList nllCmdList = pc.filterCmdList(fitCmdList,"ProjectedObservables,Extended,Range,RangeWithName,SumCoefRange,NumCPU,SplitRange,Constrained,Constrain,ExternalConstraints,CloneData,GlobalObservables") ;
+  RooLinkedList nllCmdList = pc.filterCmdList(fitCmdList,"ProjectedObservables,Extended,Range,RangeWithName,SumCoefRange,NumCPU,SplitRange,Constrained,Constrain,ExternalConstraints,CloneData,GlobalObservables,GlobalObservablesTag") ;
 
   pc.defineString("fitOpt","FitOptions",0,"") ;
   pc.defineInt("optConst","Optimize",0,2) ;
diff --git a/roofit/roofitcore/src/RooBanner.cxx b/roofit/roofitcore/src/RooBanner.cxx
index af65a37..cb0c8af 100644
--- a/roofit/roofitcore/src/RooBanner.cxx
+++ b/roofit/roofitcore/src/RooBanner.cxx
@@ -11,7 +11,7 @@
 // END_HTML
 //
 
-const char* VTAG="3.53" ;
+const char* VTAG="3.54" ;
 
 Int_t doBanner()
 
diff --git a/roofit/roofitcore/src/RooEffGenContext.cxx b/roofit/roofitcore/src/RooEffGenContext.cxx
index bcf5766..e5a6b5c 100644
--- a/roofit/roofitcore/src/RooEffGenContext.cxx
+++ b/roofit/roofitcore/src/RooEffGenContext.cxx
@@ -1,7 +1,7 @@
 /*****************************************************************************
  * Project: RooFit                                                           *
  * Package: RooFitCore                                                       *
- * @(#)root/roofitcore:$Id: RooEffGenContext.cxx 42963 2012-02-10 16:20:26Z wouter $
+ * @(#)root/roofitcore:$Id: RooEffGenContext.cxx 44368 2012-05-30 15:38:44Z axel $
  * Authors:                                                                  *
  *   GR, Gerhard Raven, NIKHEF/VU, Gerhard.Raven at nikhf.nl                    *
  *                                                                           *
@@ -88,7 +88,7 @@ void RooEffGenContext::generateEvent(RooArgSet &theEvent, Int_t remaining)
       double val = _eff->getVal();
       if (val > _maxEff && !_eff->getMaxVal(*_vars)) {
          coutE(Generation) << ClassName() << "::" << GetName() 
-              << ":generateEvent: value of efficiency is larger than assumed maximum of 1."  << endl;
+              << ":generateEvent: value of efficiency is larger than assumed maximum of 1."  << std::endl;
          continue;
       }
       if (val > RooRandom::uniform() * _maxEff) {
diff --git a/roofit/roofitcore/src/RooFitResult.cxx b/roofit/roofitcore/src/RooFitResult.cxx
index b8a4c16..7f5e819 100644
--- a/roofit/roofitcore/src/RooFitResult.cxx
+++ b/roofit/roofitcore/src/RooFitResult.cxx
@@ -1,7 +1,7 @@
 /*****************************************************************************
  * Project: RooFit                                                           *
  * Package: RooFitCore                                                       *
- * @(#)root/roofitcore:$Id: RooFitResult.cxx 42242 2011-11-25 14:02:26Z wouter $
+ * @(#)root/roofitcore:$Id: RooFitResult.cxx 44381 2012-05-31 06:45:52Z moneta $
  * Authors:                                                                  *
  *   WV, Wouter Verkerke, UC Santa Barbara, verkerke at slac.stanford.edu       *
  *   DK, David Kirkby,    UC Irvine,         dkirkby at uci.edu                 *
@@ -186,7 +186,7 @@ void RooFitResult::setFinalParList(const RooArgList& list)
 
 
 //_____________________________________________________________________________
-Int_t RooFitResult::statusCodeHistory(UInt_t icycle) 
+Int_t RooFitResult::statusCodeHistory(UInt_t icycle) const
 { 
   if (icycle>=_statusHistory.size()) {
     coutE(InputArguments) << "RooFitResult::statusCodeHistory(" << GetName() 
@@ -199,7 +199,7 @@ Int_t RooFitResult::statusCodeHistory(UInt_t icycle)
 
 
 //_____________________________________________________________________________
-const char* RooFitResult::statusLabelHistory(UInt_t icycle) 
+const char* RooFitResult::statusLabelHistory(UInt_t icycle) const 
 { 
   if (icycle>=_statusHistory.size()) {
     coutE(InputArguments) << "RooFitResult::statusLabelHistory(" << GetName() 
diff --git a/roofit/roofitcore/src/RooGlobalFunc.cxx b/roofit/roofitcore/src/RooGlobalFunc.cxx
index ea9cfc2..a96e53b 100644
--- a/roofit/roofitcore/src/RooGlobalFunc.cxx
+++ b/roofit/roofitcore/src/RooGlobalFunc.cxx
@@ -1,7 +1,7 @@
 /*****************************************************************************
  * Project: RooFit                                                           *
  * Package: RooFitCore                                                       *
- * @(#)root/roofitcore:$Id: RooGlobalFunc.cxx 42515 2011-12-16 12:23:16Z wouter $
+ * @(#)root/roofitcore:$Id: RooGlobalFunc.cxx 44381 2012-05-31 06:45:52Z moneta $
  * Authors:                                                                  *
  *   WV, Wouter Verkerke, UC Santa Barbara, verkerke at slac.stanford.edu       *
  *   DK, David Kirkby,    UC Irvine,         dkirkby at uci.edu                 *
@@ -195,6 +195,7 @@ namespace RooFit {
   RooCmdArg SumCoefRange(const char* rangeName)          { return RooCmdArg("SumCoefRange",0,0,0,0,rangeName,0,0,0) ; }
   RooCmdArg Constrain(const RooArgSet& params)           { return RooCmdArg("Constrain",0,0,0,0,0,0,0,0,0,0,&params) ; }
   RooCmdArg GlobalObservables(const RooArgSet& globs)    { return RooCmdArg("GlobalObservables",0,0,0,0,0,0,0,0,0,0,&globs) ; }
+  RooCmdArg GlobalObservablesTag(const char* tagName)    { return RooCmdArg("GlobalObservablesTag",0,0,0,0,tagName,0,0,0) ; }
   RooCmdArg Constrained()                                { return RooCmdArg("Constrained",kTRUE,0,0,0,0,0,0,0) ; }
   RooCmdArg ExternalConstraints(const RooArgSet& cpdfs)  { return RooCmdArg("ExternalConstraints",0,0,0,0,0,0,&cpdfs,0,0,0,&cpdfs) ; }
   RooCmdArg PrintEvalErrors(Int_t numErrors)             { return RooCmdArg("PrintEvalErrors",numErrors,0,0,0,0,0,0,0) ; }
diff --git a/roofit/roofitcore/src/RooHistFunc.cxx b/roofit/roofitcore/src/RooHistFunc.cxx
index d8f45d3..a21aef1 100644
--- a/roofit/roofitcore/src/RooHistFunc.cxx
+++ b/roofit/roofitcore/src/RooHistFunc.cxx
@@ -1,7 +1,7 @@
 /*****************************************************************************
  * Project: RooFit                                                           *
  * Package: RooFitCore                                                       *
- * @(#)root/roofit:$Id: RooHistFunc.cxx 42963 2012-02-10 16:20:26Z wouter $
+ * @(#)root/roofit:$Id: RooHistFunc.cxx 44381 2012-05-31 06:45:52Z moneta $
  * Authors:                                                                  *
  *   WV, Wouter Verkerke, UC Santa Barbara, verkerke at slac.stanford.edu       *
  *   DK, David Kirkby,    UC Irvine,         dkirkby at uci.edu                 *
@@ -245,7 +245,6 @@ Double_t RooHistFunc::analyticalIntegral(Int_t code, const char* /*rangeName*/)
   }
 
   // Partial integration scenario, retrieve set of variables, calculate partial sum
-
   RooArgSet intSet ;
   TIterator* iter = _depList.createIterator() ;
   RooAbsArg* arg ;
@@ -272,7 +271,7 @@ list<Double_t>* RooHistFunc::plotSamplingHint(RooAbsRealLValue& obs, Double_t xl
   // with the vertical lines that occur in a non-interpolated histogram
 
   // No hints are required when interpolation is used
-  if (_intOrder>0) {
+  if (_intOrder>1) {
     return 0 ;
   }
 
@@ -315,7 +314,7 @@ std::list<Double_t>* RooHistFunc::binBoundaries(RooAbsRealLValue& obs, Double_t
   // with the vertical lines that occur in a non-interpolated histogram
 
   // No hints are required when interpolation is used
-  if (_intOrder>0) {
+  if (_intOrder>1) {
     return 0 ;
   }
 
diff --git a/roofit/roofitcore/src/RooMinimizerFcn.cxx b/roofit/roofitcore/src/RooMinimizerFcn.cxx
index 61b1f02..a5f546a 100644
--- a/roofit/roofitcore/src/RooMinimizerFcn.cxx
+++ b/roofit/roofitcore/src/RooMinimizerFcn.cxx
@@ -1,7 +1,7 @@
 /*****************************************************************************
  * Project: RooFit                                                           *
  * Package: RooFitCore                                                       *
- * @(#)root/roofitcore:$Id: RooMinimizerFcn.cxx 42242 2011-11-25 14:02:26Z wouter $
+ * @(#)root/roofitcore:$Id: RooMinimizerFcn.cxx 44381 2012-05-31 06:45:52Z moneta $
  * Authors:                                                                  *
  *   AL, Alfio Lazzaro,   INFN Milan,        alfio.lazzaro at mi.infn.it        *
  *                                                                           *
@@ -79,6 +79,8 @@ RooMinimizerFcn::RooMinimizerFcn(RooAbsReal *funct, RooMinimizer* context,
   delete pIter;
 
   _nDim = _floatParamList->getSize();
+
+  updateFloatVec() ;
   
   // Save snapshot of initial lists
   _initFloatParamList = (RooArgList*) _floatParamList->snapshot(kFALSE) ;
@@ -329,6 +331,8 @@ Bool_t RooMinimizerFcn::Synchronize(std::vector<ROOT::Fit::ParameterSettings>& p
 
   }
 
+  updateFloatVec() ;
+
   return 0 ;  
 
 }
@@ -442,7 +446,9 @@ void RooMinimizerFcn::ApplyCovarianceMatrix(TMatrixDSym& V)
 
 Bool_t RooMinimizerFcn::SetPdfParamVal(const Int_t &index, const Double_t &value) const
 {
-  RooRealVar* par = (RooRealVar*)_floatParamList->at(index);
+  //RooRealVar* par = (RooRealVar*)_floatParamList->at(index);
+  RooRealVar* par = (RooRealVar*)_floatParamVec[index] ;
+
   if (par->getVal()!=value) {
     if (_verbose) cout << par->GetName() << "=" << value << ", " ;
     
@@ -454,6 +460,22 @@ Bool_t RooMinimizerFcn::SetPdfParamVal(const Int_t &index, const Double_t &value
 }
 
 
+
+//_____________________________________________________________________________
+void RooMinimizerFcn::updateFloatVec() 
+{
+  _floatParamVec.clear() ;
+  RooFIter iter = _floatParamList->fwdIterator() ;
+  RooAbsArg* arg ;
+  _floatParamVec.reserve(_floatParamList->getSize()) ;
+  Int_t i(0) ;
+  while((arg=iter.next())) {
+    _floatParamVec[i++] = arg ;
+  }
+}
+
+
+
 double RooMinimizerFcn::DoEval(const double *x) const 
 {
 
diff --git a/roofit/roofitcore/src/RooPlot.cxx b/roofit/roofitcore/src/RooPlot.cxx
index 5a64ff9..f538ebe 100644
--- a/roofit/roofitcore/src/RooPlot.cxx
+++ b/roofit/roofitcore/src/RooPlot.cxx
@@ -1,7 +1,7 @@
 /*****************************************************************************
  * Project: RooFit                                                           *
  * Package: RooFitCore                                                       *
- * @(#)root/roofitcore:$Id: RooPlot.cxx 42546 2011-12-20 09:53:42Z wouter $
+ * @(#)root/roofitcore:$Id: RooPlot.cxx 44381 2012-05-31 06:45:52Z moneta $
  * Authors:                                                                  *
  *   WV, Wouter Verkerke, UC Santa Barbara, verkerke at slac.stanford.edu       *
  *   DK, David Kirkby,    UC Irvine,         dkirkby at uci.edu                 *
@@ -95,9 +95,11 @@ RooPlot::RooPlot(Double_t xmin, Double_t xmax) :
 {
   // Constructor of RooPlot with range [xmin,xmax]
 
+  Bool_t addDirectoryStatus = TH1::AddDirectoryStatus();
   TH1::AddDirectory(kFALSE) ;
   _hist = new TH1D(histName(),"A RooPlot",100,xmin,xmax) ;
-  TH1::AddDirectory(kTRUE) ;
+  TH1::AddDirectory(addDirectoryStatus) ;
+
 
   // Create an empty frame with the specified x-axis limits.
   initialize();
@@ -113,9 +115,10 @@ RooPlot::RooPlot(Double_t xmin, Double_t xmax, Double_t ymin, Double_t ymax) :
 {
   // Construct of a two-dimensioanl RooPlot with ranges [xmin,xmax] x [ymin,ymax]
 
+  Bool_t addDirectoryStatus = TH1::AddDirectoryStatus();
   TH1::AddDirectory(kFALSE) ;
   _hist = new TH1D(histName(),"A RooPlot",100,xmin,xmax) ;
-  TH1::AddDirectory(kFALSE) ;
+  TH1::AddDirectory(addDirectoryStatus) ;
 
   SetMinimum(ymin);
   SetMaximum(ymax);
@@ -131,9 +134,10 @@ RooPlot::RooPlot(const RooAbsRealLValue &var1, const RooAbsRealLValue &var2) :
   // Construct a two-dimensional RooPlot with ranges and properties taken
   // from variables var1 and var2
 
+  Bool_t addDirectoryStatus = TH1::AddDirectoryStatus();
   TH1::AddDirectory(kFALSE) ;
   _hist = new TH1D(histName(),"A RooPlot",100,var1.getMin(),var1.getMax()) ;
-  TH1::AddDirectory(kTRUE) ;
+  TH1::AddDirectory(addDirectoryStatus) ;
 
   if(!var1.hasMin() || !var1.hasMax()) {
     coutE(InputArguments) << "RooPlot::RooPlot: cannot create plot for variable without finite limits: "
@@ -163,9 +167,10 @@ RooPlot::RooPlot(const RooAbsRealLValue &var1, const RooAbsRealLValue &var2,
   // from variables var1 and var2 but with an overriding range definition
   // of [xmin,xmax] x [ymin,ymax]
 
+  Bool_t addDirectoryStatus = TH1::AddDirectoryStatus();
   TH1::AddDirectory(kFALSE) ;
   _hist = new TH1D(histName(),"A RooPlot",100,xmin,xmax) ;
-  TH1::AddDirectory(kTRUE) ;
+  TH1::AddDirectory(addDirectoryStatus) ;
 
   SetMinimum(ymin);
   SetMaximum(ymax);
@@ -183,9 +188,10 @@ RooPlot::RooPlot(const char* name, const char* title, const RooAbsRealLValue &va
   // Create an 1-dimensional with all properties taken from 'var', but
   // with an explicit range [xmin,xmax] and a default binning of 'nbins'
 
+  Bool_t addDirectoryStatus = TH1::AddDirectoryStatus();
   TH1::AddDirectory(kFALSE) ;
   _hist = new TH1D(name,title,nbins,xmin,xmax) ;
-  TH1::AddDirectory(kTRUE) ;
+  TH1::AddDirectory(addDirectoryStatus) ;
 
   // plotVar can be a composite in case of a RooDataSet::plot, need deepClone
   _plotVarSet = (RooArgSet*) RooArgSet(var).snapshot() ;
@@ -208,9 +214,10 @@ RooPlot::RooPlot(const RooAbsRealLValue &var, Double_t xmin, Double_t xmax, Int_
   // Create an 1-dimensional with all properties taken from 'var', but
   // with an explicit range [xmin,xmax] and a default binning of 'nbins'
 
+  Bool_t addDirectoryStatus = TH1::AddDirectoryStatus();
   TH1::AddDirectory(kFALSE) ;
   _hist = new TH1D(histName(),"RooPlot",nbins,xmin,xmax) ;
-  TH1::AddDirectory(kTRUE) ;
+  TH1::AddDirectory(addDirectoryStatus) ;
 
   // plotVar can be a composite in case of a RooDataSet::plot, need deepClone
   _plotVarSet = (RooArgSet*) RooArgSet(var).snapshot() ;
diff --git a/roofit/roofitcore/src/RooProofDriverSelector.cxx b/roofit/roofitcore/src/RooProofDriverSelector.cxx
index e2b9c9d..ff0ea3b 100644
--- a/roofit/roofitcore/src/RooProofDriverSelector.cxx
+++ b/roofit/roofitcore/src/RooProofDriverSelector.cxx
@@ -42,6 +42,7 @@
 #endif
  
 using namespace RooFit ;
+using namespace std ;
 
 void RooProofDriverSelector::SlaveBegin(TTree * /*tree*/) 
 {  
diff --git a/roofit/roofitcore/src/RooWorkspace.cxx b/roofit/roofitcore/src/RooWorkspace.cxx
index 4c33c6f..5e73e43 100644
--- a/roofit/roofitcore/src/RooWorkspace.cxx
+++ b/roofit/roofitcore/src/RooWorkspace.cxx
@@ -1,7 +1,7 @@
 /*****************************************************************************
  * Project: RooFit                                                           *
  * Package: RooFitCore                                                       *
- * @(#)root/roofitcore:$Id: RooWorkspace.cxx 43897 2012-04-23 08:07:00Z wouter $
+ * @(#)root/roofitcore:$Id: RooWorkspace.cxx 44381 2012-05-31 06:45:52Z moneta $
  * Authors:                                                                  *
  *   WV, Wouter Verkerke, UC Santa Barbara, verkerke at slac.stanford.edu       *
  *                                                                           *
@@ -782,8 +782,8 @@ Bool_t RooWorkspace::defineSet(const char* name, const RooArgSet& aset, Bool_t i
       if (importMissing) {
 	import(*sarg) ;
       } else {
-	coutE(InputArguments) << "RooWorkspace::defineSet(" << GetName() << ") ERROR set constituent " << sarg->GetName() 
-			      << " is not in workspace and importMissing option is disabled" << endl ;
+	coutE(InputArguments) << "RooWorkspace::defineSet(" << GetName() << ") ERROR set constituent \"" << sarg->GetName() 
+			      << "\" is not in workspace and importMissing option is disabled" << endl ;
 	return kTRUE ;
       }
     }
@@ -822,8 +822,8 @@ Bool_t RooWorkspace::defineSet(const char* name, const char* contentList)
   while(token) {
     // If missing, either import or report error
     if (!arg(token)) {
-      coutE(InputArguments) << "RooWorkspace::defineSet(" << GetName() << ") ERROR proposed set constituent " << token
-			    << " is not in workspace" << endl ;
+      coutE(InputArguments) << "RooWorkspace::defineSet(" << GetName() << ") ERROR proposed set constituent \"" << token
+			    << "\" is not in workspace" << endl ;
       return kTRUE ;
     }
     wsargs.add(*arg(token)) ;    
@@ -855,8 +855,8 @@ Bool_t RooWorkspace::extendSet(const char* name, const char* newContents)
   while(token) {
     // If missing, either import or report error
     if (!arg(token)) {
-      coutE(InputArguments) << "RooWorkspace::defineSet(" << GetName() << ") ERROR proposed set constituent " << token
-			    << " is not in workspace" << endl ;
+      coutE(InputArguments) << "RooWorkspace::defineSet(" << GetName() << ") ERROR proposed set constituent \"" << token
+			    << "\" is not in workspace" << endl ;
       return kTRUE ;
     }
     wsargs.add(*arg(token)) ;    
@@ -1221,7 +1221,7 @@ RooArgSet RooWorkspace::argSet(const char* nameList) const
     if (oneArg) {
       ret.add(*oneArg) ;
     } else {
-      coutE(InputArguments) << " RooWorkspace::argSet(" << GetName() << ") no RooAbsArg named " << token << " in workspace" << endl ;
+      coutE(InputArguments) << " RooWorkspace::argSet(" << GetName() << ") no RooAbsArg named \"" << token << "\" in workspace" << endl ;
     }
     token = strtok(0,",") ; 
   }
@@ -1770,14 +1770,21 @@ Bool_t RooWorkspace::import(TObject& object, Bool_t replaceExisting)
 			  << object.GetName() << " is already in workspace and replaceExisting flag is set to false" << endl ;
     return kTRUE ;
   }  
-  TH1::AddDirectory(kFALSE) ;
+
+  // Grab the current state of the directory Auto-Add
+  ROOT::DirAutoAdd_t func = object.IsA()->GetDirectoryAutoAdd();
+  object.IsA()->SetDirectoryAutoAdd(0);
+
   if (oldObj) {
     _genObjects.Replace(oldObj,object.Clone()) ;
     delete oldObj ;
   } else {
     _genObjects.Add(object.Clone()) ;
   }
-  TH1::AddDirectory(kTRUE) ;
+
+  // Reset the state of the directory Auto-Add
+  object.IsA()->SetDirectoryAutoAdd(func);
+
   return kFALSE ;
 }
 
diff --git a/roofit/roostats/inc/LinkDef.h b/roofit/roostats/inc/LinkDef.h
index 2142581..15f6133 100644
--- a/roofit/roostats/inc/LinkDef.h
+++ b/roofit/roostats/inc/LinkDef.h
@@ -66,7 +66,6 @@
 #pragma link C++ class RooStats::TestStatSampler+; // interface, not concrete
 #pragma link C++ class RooStats::DebuggingSampler+;
 #pragma link C++ class RooStats::ToyMCSampler+;
-#pragma link C++ class RooStats::ToyMCSamplerOld+;
 #pragma link C++ class RooStats::ToyMCStudy+;
 #pragma link C++ class RooStats::ProofConfig+;
 #pragma link C++ class RooStats::ToyMCImportanceSampler+;
diff --git a/roofit/roostats/inc/RooStats/AsymptoticCalculator.h b/roofit/roostats/inc/RooStats/AsymptoticCalculator.h
index 051c4d6..ce1145c 100644
--- a/roofit/roostats/inc/RooStats/AsymptoticCalculator.h
+++ b/roofit/roostats/inc/RooStats/AsymptoticCalculator.h
@@ -1,4 +1,4 @@
-// @(#)root/roostats:$Id: AsymptoticCalculator.h 44152 2012-05-07 10:30:54Z moneta $
+// @(#)root/roostats:$Id: AsymptoticCalculator.h 44269 2012-05-16 12:53:49Z moneta $
 // Author: Sven Kreiss, Kyle Cranmer   Nov 2010
 /*************************************************************************
  * Copyright (C) 1995-2008, Rene Brun and Fons Rademakers.               *
@@ -76,6 +76,10 @@ namespace RooStats {
       // set test statistic for one sided (upper limits)
       void SetOneSided(bool on) { fOneSided = on; }
 
+      // set the test statistics for two sided (in case of upper limits
+      // for discovery does not make really sense)
+      void SetTwoSided() { fOneSided = false; fOneSidedDiscovery = false;}
+
       // set the test statistics for one-sided discovery
       void SetOneSidedDiscovery(bool on) { fOneSidedDiscovery = on; }
 
diff --git a/roofit/roostats/inc/RooStats/DebuggingSampler.h b/roofit/roostats/inc/RooStats/DebuggingSampler.h
index eaee4a7..bd5828f 100644
--- a/roofit/roostats/inc/RooStats/DebuggingSampler.h
+++ b/roofit/roostats/inc/RooStats/DebuggingSampler.h
@@ -1,4 +1,4 @@
-// @(#)root/roostats:$Id: DebuggingSampler.h 39391 2011-05-26 09:51:59Z moneta $
+// @(#)root/roostats:$Id: DebuggingSampler.h 44376 2012-05-30 21:47:29Z moneta $
 // Author: Kyle Cranmer, Lorenzo Moneta, Gregory Schott, Wouter Verkerke
 /*************************************************************************
  * Copyright (C) 1995-2008, Rene Brun and Fons Rademakers.               *
@@ -70,7 +70,7 @@ namespace RooStats {
       // Get the TestStatistic
       virtual TestStatistic* GetTestStatistic()  const {
          // TODO change to Roo... notifications
-         cout << "GetTestStatistic() IS NOT IMPLEMENTED FOR THIS SAMPLER. Returning NULL." << endl;
+         std::cout << "GetTestStatistic() IS NOT IMPLEMENTED FOR THIS SAMPLER. Returning NULL." << std::endl;
          return NULL; /*fTestStatistic;*/
       }
     
@@ -102,7 +102,7 @@ namespace RooStats {
       // Set the TestStatistic (want the argument to be a function of the data & parameter points
       virtual void SetTestStatistic(TestStatistic* /*testStatistic*/) {
          // TODO change to Roo... notifications
-         cout << "SetTestStatistic(...) IS NOT IMPLEMENTED FOR THIS SAMPLER" << endl;
+         std::cout << "SetTestStatistic(...) IS NOT IMPLEMENTED FOR THIS SAMPLER" << std::endl;
       }
       
    private:
diff --git a/roofit/roostats/inc/RooStats/DetailedOutputAggregator.h b/roofit/roostats/inc/RooStats/DetailedOutputAggregator.h
index ab06791..14e96b4 100755
--- a/roofit/roostats/inc/RooStats/DetailedOutputAggregator.h
+++ b/roofit/roostats/inc/RooStats/DetailedOutputAggregator.h
@@ -32,141 +32,51 @@
    */
 //
 
-#include "RooFitResult.h"
-#include "RooPullVar.h"
-#include "RooDataSet.h"
+
+class RooAbsCollection; 
+class RooFitResult;
+class RooDataSet;
+class RooArgList;
 
 namespace RooStats {
 
-	class DetailedOutputAggregator {
-
-		public:
-			// Translate the given fit result to a RooArgSet in a generic way.
-			// Prefix is prepended to all variable names.
-			static RooArgSet *GetAsArgSet(RooFitResult *result, TString prefix="", bool withErrorsAndPulls=false) {
-				RooArgSet *detailedOutput = new RooArgSet;
-				const RooArgSet &detOut = result->floatParsFinal();
-				const RooArgSet &truthSet = result->floatParsInit();
-				RooRealVar* var(0);
-				TIterator *it = detOut.createIterator();
-				for(;(var = dynamic_cast<RooRealVar*>(it->Next()));) {
-					RooAbsArg* clone = var->cloneTree(TString().Append(prefix).Append(var->GetName()));
-					clone->SetTitle( TString().Append(prefix).Append(var->GetTitle()) );
-					detailedOutput->addOwned(*clone);
-
-               if( withErrorsAndPulls ) {
-                  TString pullname = TString().Append(prefix).Append(TString::Format("%s_pull", var->GetName()));
-                  //					TString pulldesc = TString::Format("%s pull for fit %u", var->GetTitle(), fitNumber);
-                  RooRealVar* truth = dynamic_cast<RooRealVar*>(truthSet.find(var->GetName()));
-                  RooPullVar pulltemp("temppull", "temppull", *var, *truth);
-                  RooRealVar* pull = new RooRealVar(pullname, pullname, pulltemp.getVal());
-                  detailedOutput->addOwned(*pull);
-   
-                  TString errloname = TString().Append(prefix).Append(TString::Format("%s_errlo", var->GetName()));
-                  //					TString errlodesc = TString::Format("%s low error for fit %u", var->GetTitle(), fitNumber);
-                  RooRealVar* errlo = new RooRealVar(errloname, errloname, var->getErrorLo());
-                  detailedOutput->addOwned(*errlo);
-   
-                  TString errhiname = TString().Append(prefix).Append(TString::Format("%s_errhi", var->GetName()));
-                  //					TString errhidesc = TString::Format("%s high error for fit %u", var->GetTitle(), fitNumber);
-                  RooRealVar* errhi = new RooRealVar(errhiname, errhiname, var->getErrorHi());
-                  detailedOutput->addOwned(*errhi);
-               }
-				}
-				delete it;
-
-				// monitor a few more variables
-				detailedOutput->addOwned( *new RooRealVar(TString().Append(prefix).Append("minNLL"), TString().Append(prefix).Append("minNLL"), result->minNll() ) );
-				detailedOutput->addOwned( *new RooRealVar(TString().Append(prefix).Append("fitStatus"), TString().Append(prefix).Append("fitStatus"), result->status() ) );
-				detailedOutput->addOwned( *new RooRealVar(TString().Append(prefix).Append("covQual"), TString().Append(prefix).Append("covQual"), result->covQual() ) );
-				detailedOutput->addOwned( *new RooRealVar(TString().Append(prefix).Append("numInvalidNLLEval"), TString().Append(prefix).Append("numInvalidNLLEval"), result->numInvalidNLL() ) );
-				return detailedOutput;
-			}
-
-			DetailedOutputAggregator() {
-				result = NULL;
-				builtSet = NULL;
-			}
-
-			// For each variable in aset, prepend prefix to its name and add
-			// to the internal store. Note this will not appear in the produced
-			// dataset unless CommitSet is called.
-			void AppendArgSet(const RooArgSet *aset, TString prefix="") {
-				if (aset == NULL) {
-				   // silently ignore
-					//std::cout << "Attempted to append NULL" << endl;
-					return;
-				}
-				if (builtSet == NULL) {
-					builtSet = new RooArgSet();
-				}
-				TIterator* iter = aset->createIterator();
-				while(RooRealVar* v = dynamic_cast<RooRealVar*>( iter->Next() ) ) {
-					TString renamed(TString::Format("%s%s", prefix.Data(), v->GetName()));
-					if (result != NULL) {
-						// we already commited an argset once, so we expect all columns to already be in the set
-						builtSet->setRealValue(renamed, v->getVal());
-					}
-					else {
-						// we never commited, so by default all columns are expected to not exist
-						RooRealVar *var = new RooRealVar(renamed, v->GetTitle(), v->getVal());
-						if (!builtSet->addOwned(*var)) {
-							delete var;
-							builtSet->setRealValue(renamed, v->getVal());
-						}
-					}
-				}
-				delete iter;
-			}
-
-			// Commit to the result RooDataSet.
-			void CommitSet(double weight=1.0) {
-				if (result == NULL) {
-					result = new RooDataSet("", "",
-							RooArgSet( *(new RooRealVar("weight","weight",1.0)), "tmpSet" ), "weight");
-					InitializeColumns(result, builtSet);
-				}
-				result->add(*builtSet, weight);
-				TIterator* iter = builtSet->createIterator();
-				while(RooAbsArg* v = dynamic_cast<RooAbsArg*>( iter->Next() ) ) {
-					builtSet->setRealValue(v->GetName(), -999.0);
-				}
-				delete iter;
-			}
-
-			RooDataSet *GetAsDataSet(TString name, TString title) {
-			   RooDataSet* temp = NULL;
-				if( result ) {
-				   temp = new RooDataSet( *result );
-				   temp->SetNameTitle( name.Data(), title.Data() );
-				}else{
-					temp = new RooDataSet(name.Data(), title.Data(),
-							RooArgSet( *(new RooRealVar("weight","weight",1.0)), "tmpSet" ), "weight");
-				}
-
-				return temp;
-			}
-
-			virtual ~DetailedOutputAggregator() {
-				if (result != NULL) delete result;
-				if (builtSet != NULL) delete builtSet;
-			}
-
-		private:
-			RooDataSet *result;
-			RooArgSet *builtSet;
-
-			void InitializeColumns(RooDataSet *dset, RooArgSet *aset) {
-				TIterator* iter = aset->createIterator();
-				while(RooAbsArg* v = dynamic_cast<RooAbsArg*>( iter->Next() ) ) {
-					dset->addColumn( *(new RooRealVar(v->GetName(), v->GetTitle(), -1.0)));
-				}
-				delete iter;
-			}
-
-		protected:
-			ClassDef(DetailedOutputAggregator,1)
-	};
+   class DetailedOutputAggregator {
+
+   public:
+      // Translate the given fit result to a RooArgSet in a generic way.
+      // Prefix is prepended to all variable names.
+      static RooArgSet *GetAsArgSet(RooFitResult *result, TString prefix="", bool withErrorsAndPulls=false);
+      
+      DetailedOutputAggregator() {
+         fResult = NULL;
+         fBuiltSet = NULL;
+      }
+
+      // For each variable in aset, prepend prefix to its name and add
+      // to the internal store. Note this will not appear in the produced
+      // dataset unless CommitSet is called.
+      void AppendArgSet(const RooAbsCollection *aset, TString prefix="");
+
+      const RooArgList* GetAsArgList() const {
+         // Returns this set of detailed output.
+         return fBuiltSet;
+      }
+      
+      // Commit to the result RooDataSet.
+      void CommitSet(double weight=1.0);
+
+      RooDataSet *GetAsDataSet(TString name, TString title);
+
+      virtual ~DetailedOutputAggregator();
+
+   private:
+
+      RooDataSet *fResult;
+      RooArgList *fBuiltSet;
+      
+   protected:
+      ClassDef(DetailedOutputAggregator,1)
+   };
 }
 
 #endif
diff --git a/roofit/roostats/inc/RooStats/FeldmanCousins.h b/roofit/roostats/inc/RooStats/FeldmanCousins.h
index 81ac9bd..1359e67 100644
--- a/roofit/roostats/inc/RooStats/FeldmanCousins.h
+++ b/roofit/roostats/inc/RooStats/FeldmanCousins.h
@@ -1,4 +1,4 @@
-// @(#)root/roostats:$Id: FeldmanCousins.h 39391 2011-05-26 09:51:59Z moneta $
+// @(#)root/roostats:$Id: FeldmanCousins.h 44368 2012-05-30 15:38:44Z axel $
 // Author: Kyle Cranmer, Lorenzo Moneta, Gregory Schott, Wouter Verkerke
 /*************************************************************************
  * Copyright (C) 1995-2008, Rene Brun and Fons Rademakers.               *
@@ -55,21 +55,21 @@ namespace RooStats {
       virtual Double_t ConfidenceLevel()  const {return 1.-fSize;}  
       // Set the DataSet
       virtual void SetData(RooAbsData& /*data*/) {  
-	cout << "DEPRECATED, set data in constructor" << endl;
+	std::cout << "DEPRECATED, set data in constructor" << std::endl;
       }    
       // Set the Pdf
       virtual void SetPdf(RooAbsPdf& /*pdf*/) { 
-	cout << "DEPRECATED, use ModelConfig" << endl;
+	std::cout << "DEPRECATED, use ModelConfig" << std::endl;
       }	
 
       // specify the parameters of interest in the interval
       virtual void SetParameters(const RooArgSet& /*set*/) { 
-	cout << "DEPRECATED, use ModelConfig" << endl;
+	std::cout << "DEPRECATED, use ModelConfig" << std::endl;
       }
 
       // specify the nuisance parameters (eg. the rest of the parameters)
       virtual void SetNuisanceParameters(const RooArgSet& /*set*/) {
-	cout << "DEPRECATED, use ModelConfig" << endl;
+	std::cout << "DEPRECATED, use ModelConfig" << std::endl;
       }
 
       // User-defined set of points to test
diff --git a/roofit/roostats/inc/RooStats/HybridCalculatorOriginal.h b/roofit/roostats/inc/RooStats/HybridCalculatorOriginal.h
index 2a1daca..bc13807 100644
--- a/roofit/roostats/inc/RooStats/HybridCalculatorOriginal.h
+++ b/roofit/roostats/inc/RooStats/HybridCalculatorOriginal.h
@@ -1,4 +1,4 @@
-// @(#)root/roostats:$Id: HybridCalculatorOriginal.h 39391 2011-05-26 09:51:59Z moneta $
+// @(#)root/roostats:$Id: HybridCalculatorOriginal.h 44368 2012-05-30 15:38:44Z axel $
 
 /*************************************************************************
  * Project: RooStats                                                     *
@@ -135,7 +135,7 @@ namespace RooStats {
       HybridResult* Calculate(unsigned int nToys, bool usePriors) const;
       void PrintMore(const char* options) const;
 
-      void PatchSetExtended(bool on = true) { fTmpDoExtended = on; std::cout << "extended patch set to " << on << endl; } // patch to test with RooPoisson (or other non-extended models)
+      void PatchSetExtended(bool on = true) { fTmpDoExtended = on; std::cout << "extended patch set to " << on << std::endl; } // patch to test with RooPoisson (or other non-extended models)
 
    private:
 
diff --git a/roofit/roostats/inc/RooStats/HypoTestInverter.h b/roofit/roostats/inc/RooStats/HypoTestInverter.h
index 269ebff..eb55946 100644
--- a/roofit/roostats/inc/RooStats/HypoTestInverter.h
+++ b/roofit/roostats/inc/RooStats/HypoTestInverter.h
@@ -1,4 +1,4 @@
-// @(#)root/roostats:$Id: HypoTestInverter.h 44038 2012-04-30 15:21:37Z moneta $
+// @(#)root/roostats:$Id: HypoTestInverter.h 44368 2012-05-30 15:38:44Z axel $
 // Author: Kyle Cranmer, Lorenzo Moneta, Gregory Schott, Wouter Verkerke
 /*************************************************************************
  * Copyright (C) 1995-2008, Rene Brun and Fons Rademakers.               *
@@ -179,7 +179,7 @@ private:
    int fMaxToys;  // maximum number of toys to run 
     
    HypoTestCalculatorGeneric* fCalculator0;   // pointer to the calculator passed in the constructor
-   auto_ptr<HypoTestCalculatorGeneric> fHC;
+   std::auto_ptr<HypoTestCalculatorGeneric> fHC;
    RooRealVar* fScannedVariable;     // pointer to the constrained variable
    mutable HypoTestInverterResult* fResults; // pointer to the result 
      
diff --git a/roofit/roostats/inc/RooStats/HypoTestResult.h b/roofit/roostats/inc/RooStats/HypoTestResult.h
index 1228f08..fc7adcb 100644
--- a/roofit/roostats/inc/RooStats/HypoTestResult.h
+++ b/roofit/roostats/inc/RooStats/HypoTestResult.h
@@ -1,4 +1,4 @@
-// @(#)root/roostats:$Id: HypoTestResult.h 44157 2012-05-07 16:41:44Z moneta $
+// @(#)root/roostats:$Id: HypoTestResult.h 44473 2012-06-01 16:12:31Z moneta $
 // Author: Kyle Cranmer, Lorenzo Moneta, Gregory Schott, Wouter Verkerke, Sven Kreiss
 /*************************************************************************
  * Copyright (C) 1995-2008, Rene Brun and Fons Rademakers.               *
@@ -67,7 +67,7 @@ namespace RooStats {
       // default constructor
       explicit HypoTestResult(const char* name = 0);
       
-      // copy constructor
+      // copy constructo
       HypoTestResult(const HypoTestResult& other);
 
       // constructor from name, null and alternate p values 
@@ -76,6 +76,9 @@ namespace RooStats {
       // destructor 
       virtual ~HypoTestResult();
 
+      // assignment operator
+      HypoTestResult & operator=(const HypoTestResult& other);
+
       // add values from another HypoTestResult
       virtual void Append(const HypoTestResult *other);
 
@@ -137,8 +140,12 @@ namespace RooStats {
       /// The error on the ratio CLs+b/CLb
       Double_t CLsError() const;
 
+      /// The error on the Null p-value
       Double_t NullPValueError() const;
 
+      /// The error on the significance, computed from NullPValueError via error propagation
+      Double_t SignificanceError() const;
+
 
       void Print(const Option_t* = "") const;
 
diff --git a/roofit/roostats/inc/RooStats/MCMCCalculator.h b/roofit/roostats/inc/RooStats/MCMCCalculator.h
index 1542d00..181b131 100644
--- a/roofit/roostats/inc/RooStats/MCMCCalculator.h
+++ b/roofit/roostats/inc/RooStats/MCMCCalculator.h
@@ -1,4 +1,4 @@
-// @(#)root/roostats:$Id: MCMCCalculator.h 40959 2011-09-20 16:33:21Z moneta $
+// @(#)root/roostats:$Id: MCMCCalculator.h 44368 2012-05-30 15:38:44Z axel $
 // Authors: Kevin Belasco        17/06/2009
 // Authors: Kyle Cranmer         17/06/2009
 /*************************************************************************
@@ -143,7 +143,7 @@ namespace RooStats {
       {
          if (epsilon < 0)
             coutE(InputArguments) << "MCMCInterval::SetEpsilon will not allow "
-                                  << "negative epsilon value" << endl;
+                                  << "negative epsilon value" << std::endl;
          else
             fEpsilon = epsilon;
       }
@@ -166,7 +166,7 @@ namespace RooStats {
       {
          if (delta < 0.)
             coutE(InputArguments) << "MCMCInterval::SetDelta will not allow "
-                                  << "negative delta value" << endl;
+                                  << "negative delta value" << std::endl;
          else
             fDelta = delta;
       }
diff --git a/roofit/roostats/inc/RooStats/MCMCInterval.h b/roofit/roostats/inc/RooStats/MCMCInterval.h
index a504089..ddc052c 100644
--- a/roofit/roostats/inc/RooStats/MCMCInterval.h
+++ b/roofit/roostats/inc/RooStats/MCMCInterval.h
@@ -1,4 +1,4 @@
-// @(#)root/roostats:$Id: MCMCInterval.h 39391 2011-05-26 09:51:59Z moneta $
+// @(#)root/roostats:$Id: MCMCInterval.h 44368 2012-05-30 15:38:44Z axel $
 // Authors: Kevin Belasco        17/06/2009
 // Authors: Kyle Cranmer         17/06/2009
 /*************************************************************************
@@ -238,7 +238,7 @@ namespace RooStats {
       {
          if (epsilon < 0)
             coutE(InputArguments) << "MCMCInterval::SetEpsilon will not allow "
-                                  << "negative epsilon value" << endl;
+                                  << "negative epsilon value" << std::endl;
          else
             fEpsilon = epsilon;
       }
@@ -268,7 +268,7 @@ namespace RooStats {
       {
          if (delta < 0.)
             coutE(InputArguments) << "MCMCInterval::SetDelta will not allow "
-                                  << "negative delta value" << endl;
+                                  << "negative delta value" << std::endl;
          else
             fDelta = delta;
       }
@@ -299,7 +299,7 @@ namespace RooStats {
 
       Double_t fLeftSideTF; // left side tail-fraction for interval
       Double_t fTFConfLevel; // the actual conf level of tail-fraction interval
-      vector<Int_t> fVector; // vector containing the Markov chain data
+      std::vector<Int_t> fVector; // vector containing the Markov chain data
       Double_t fVecWeight; // sum of weights of all entries in fVector
       Double_t fTFLower;   // lower limit of the tail-fraction interval
       Double_t fTFUpper;   // upper limit of the tail-fraction interval
diff --git a/roofit/roostats/inc/RooStats/MinNLLTestStat.h b/roofit/roostats/inc/RooStats/MinNLLTestStat.h
index 8ce6b8d..828d86c 100755
--- a/roofit/roostats/inc/RooStats/MinNLLTestStat.h
+++ b/roofit/roostats/inc/RooStats/MinNLLTestStat.h
@@ -56,30 +56,44 @@ namespace RooStats {
    public:
      MinNLLTestStat() {
         // Proof constructor. Do not use.
-	proflts = 0;
+	fProflts = 0;
      }
      MinNLLTestStat(RooAbsPdf& pdf) {
-	proflts = new ProfileLikelihoodTestStat(pdf);
+	fProflts = new ProfileLikelihoodTestStat(pdf);
+     }
+
+     MinNLLTestStat(const MinNLLTestStat& rhs) : fProflts(0) {
+        RooAbsPdf * pdf = rhs.fProflts->GetPdf();
+        if (pdf)  fProflts = new ProfileLikelihoodTestStat(*pdf);
+     }
+
+     MinNLLTestStat & operator=(const MinNLLTestStat& rhs)  {
+        if (this == &rhs) return *this;
+        RooAbsPdf * pdf = rhs.fProflts->GetPdf();
+        if (fProflts) delete fProflts;
+        fProflts = NULL;
+        if (pdf)  fProflts = new ProfileLikelihoodTestStat(*pdf);
+        return *this;
      }
 
      virtual ~MinNLLTestStat() {
-	delete proflts;
+	delete fProflts;
      }
 
-     void SetOneSided(Bool_t flag=true) {proflts->SetOneSided(flag);}
-     void SetOneSidedDiscovery(Bool_t flag=true) {proflts->SetOneSidedDiscovery(flag);}
-     void SetReuseNLL(Bool_t flag) { proflts->SetReuseNLL(flag); }
-     void SetMinimizer(const char* minimizer){ proflts->SetMinimizer(minimizer); }
-     void SetStrategy(Int_t strategy){ proflts->SetStrategy(strategy); }
-     void SetTolerance(double tol){ proflts->SetTolerance(tol); }
-     void SetPrintLevel(Int_t printlevel){ proflts->SetPrintLevel(printlevel); }
+     void SetOneSided(Bool_t flag=true) {fProflts->SetOneSided(flag);}
+     void SetOneSidedDiscovery(Bool_t flag=true) {fProflts->SetOneSidedDiscovery(flag);}
+     void SetReuseNLL(Bool_t flag) { fProflts->SetReuseNLL(flag); }
+     void SetMinimizer(const char* minimizer){ fProflts->SetMinimizer(minimizer); }
+     void SetStrategy(Int_t strategy){ fProflts->SetStrategy(strategy); }
+     void SetTolerance(double tol){ fProflts->SetTolerance(tol); }
+     void SetPrintLevel(Int_t printlevel){ fProflts->SetPrintLevel(printlevel); }
     
      // Main interface to evaluate the test statistic on a dataset
      virtual Double_t Evaluate(RooAbsData& data, RooArgSet& paramsOfInterest) {
-        return proflts->EvaluateProfileLikelihood(1, data, paramsOfInterest); //find unconditional NLL minimum
+        return fProflts->EvaluateProfileLikelihood(1, data, paramsOfInterest); //find unconditional NLL minimum
      }
 
-     virtual void EnableDetailedOutput( bool e=true ) { proflts->EnableDetailedOutput(e); }
+     virtual void EnableDetailedOutput( bool e=true ) { fProflts->EnableDetailedOutput(e); }
 
      virtual const RooArgSet* GetDetailedOutput(void) const {
 	     // Returns detailed output. The value returned by this function is updated after each call to Evaluate().
@@ -88,15 +102,15 @@ namespace RooStats {
 	     // <li> the minimum nll, fitstatus and convergence quality for each fit </li> 
 	     // <li> for all non-constant parameters their value, error and pull </li>
 	     // </ul>
-	     return proflts->GetDetailedOutput();
+	     return fProflts->GetDetailedOutput();
      }
     
-     virtual void SetVarName(const char* name) { proflts->SetVarName(name); }
+     virtual void SetVarName(const char* name) { fProflts->SetVarName(name); }
 
-     virtual const TString GetVarName() const { return proflts->GetVarName(); }
+     virtual const TString GetVarName() const { return fProflts->GetVarName(); }
 
    private:
-     ProfileLikelihoodTestStat* proflts;
+     ProfileLikelihoodTestStat* fProflts;
 
    protected:
       ClassDef(MinNLLTestStat,1)   // implements the minimum NLL as a test statistic to be used with several tools
diff --git a/roofit/roostats/inc/RooStats/ModelConfig.h b/roofit/roostats/inc/RooStats/ModelConfig.h
index b4c74b3..026a88e 100644
--- a/roofit/roostats/inc/RooStats/ModelConfig.h
+++ b/roofit/roostats/inc/RooStats/ModelConfig.h
@@ -1,4 +1,4 @@
-// @(#)root/roostats:$Id: ModelConfig.h 39391 2011-05-26 09:51:59Z moneta $
+// @(#)root/roostats:$Id: ModelConfig.h 44368 2012-05-30 15:38:44Z axel $
 // Author: Kyle Cranmer, Lorenzo Moneta, Gregory Schott, Wouter Verkerke, Sven Kreiss
 /*************************************************************************
  * Copyright (C) 1995-2008, Rene Brun and Fons Rademakers.               *
@@ -114,36 +114,75 @@ public:
    virtual void SetParametersOfInterest(const RooArgSet& set) {
       SetParameters(set); 
    }
+   // specify the parameters of interest 
+   // through a list of comma-separated arguments already in the workspace
+   virtual void SetParameters(const char *argList) {
+      if(!GetWS()) return;
+      SetParameters(GetWS()->argSet(argList));
+   }
+   virtual void SetParametersOfInterest(const char *argList) {
+      SetParameters(argList);
+   }
     
-   // specify the nuisance parameters (eg. the rest of the parameters)
+   // specify the nuisance parameters (e.g. the rest of the parameters)
    virtual void SetNuisanceParameters(const RooArgSet& set) {
       fNuisParamsName=std::string(GetName()) + "_NuisParams";
       DefineSetInWS(fNuisParamsName.c_str(), set);
    }
+   // specify the nuisance parameters 
+   // through a list of comma-separated arguments already in the workspace
+   virtual void SetNuisanceParameters(const char *argList) {
+      if(!GetWS()) return;
+      SetNuisanceParameters(GetWS()->argSet(argList));
+   }
 
    // specify the constraint parameters 
    virtual void SetConstraintParameters(const RooArgSet& set) {
       fConstrParamsName=std::string(GetName()) + "_ConstrainedParams";
       DefineSetInWS(fConstrParamsName.c_str(), set);
    }
+   // specify the constraint parameters 
+   // through a list of comma-separated arguments already in the workspace
+   virtual void SetConstraintParameters(const char *argList) {
+      if(!GetWS()) return;
+      SetConstraintParameters(GetWS()->argSet(argList));
+   }
 
    // specify the observables
    virtual void SetObservables(const RooArgSet& set) {
       fObservablesName=std::string(GetName()) + "_Observables";
       DefineSetInWS(fObservablesName.c_str(), set);
    }
+   // specify the observables 
+   // through a list of comma-separated arguments already in the workspace
+   virtual void SetObservables(const char *argList) {
+      if(!GetWS()) return;
+      SetObservables(GetWS()->argSet(argList));
+   }
 
    // specify the conditional observables
    virtual void SetConditionalObservables(const RooArgSet& set) {
       fConditionalObsName=std::string(GetName()) + "_ConditionalObservables";
       DefineSetInWS(fConditionalObsName.c_str(), set);
    }
-
    // specify the conditional observables
+   // through a list of comma-separated arguments already in the workspace
+   virtual void SetConditionalObservables(const char *argList) {
+      if(!GetWS()) return;
+      SetConditionalObservables(GetWS()->argSet(argList));
+   }
+
+   // specify the global observables
    virtual void SetGlobalObservables(const RooArgSet& set) {
       fGlobalObsName=std::string(GetName()) + "_GlobalObservables";
       DefineSetInWS(fGlobalObsName.c_str(), set);
    }
+   // specify the global observables 
+   // through a list of comma-separated arguments already in the workspace
+   virtual void SetGlobalObservables(const char *argList) {
+      if(!GetWS()) return;
+      SetGlobalObservables(GetWS()->argSet(argList));
+   }
 
    // set parameter values for a particular hypothesis if using a common PDF
    // by saving a snapshot in the workspace
@@ -156,7 +195,7 @@ public:
       if(GetWS()->pdf(name))
          fPdfName = name;
       else
-         coutE(ObjectHandling) << "pdf "<<name<< " does not exist in workspace"<<endl;
+         coutE(ObjectHandling) << "pdf "<<name<< " does not exist in workspace"<<std::endl;
    }
 
    // specify the name of the PDF in the workspace to be used
@@ -166,7 +205,7 @@ public:
       if(GetWS()->pdf(name))
          fPriorPdfName = name;
       else
-         coutE(ObjectHandling) << "pdf "<<name<< " does not exist in workspace"<<endl;
+         coutE(ObjectHandling) << "pdf "<<name<< " does not exist in workspace"<<std::endl;
    }
 
 
@@ -177,7 +216,7 @@ public:
       if(GetWS()->data(name))
          fProtoDataName = name;
       else
-         coutE(ObjectHandling) << "dataset "<<name<< " does not exist in workspace"<<endl;
+         coutE(ObjectHandling) << "dataset "<<name<< " does not exist in workspace"<<std::endl;
    }
 
 
diff --git a/roofit/roostats/inc/RooStats/NeymanConstruction.h b/roofit/roostats/inc/RooStats/NeymanConstruction.h
index a88c55d..b16270b 100644
--- a/roofit/roostats/inc/RooStats/NeymanConstruction.h
+++ b/roofit/roostats/inc/RooStats/NeymanConstruction.h
@@ -1,4 +1,4 @@
-// @(#)root/roostats:$Id: NeymanConstruction.h 39391 2011-05-26 09:51:59Z moneta $
+// @(#)root/roostats:$Id: NeymanConstruction.h 44368 2012-05-30 15:38:44Z axel $
 // Author: Kyle Cranmer, Lorenzo Moneta, Gregory Schott, Wouter Verkerke
 /*************************************************************************
  * Copyright (C) 1995-2008, Rene Brun and Fons Rademakers.               *
@@ -82,17 +82,17 @@ namespace RooStats {
 
       // Set the Pdf, add to the the workspace if not already there
       virtual void SetPdf(RooAbsPdf& /*pdf*/) { 
-	cout << "DEPRECATED, use ModelConfig"<<endl;
+        std::cout << "DEPRECATED, use ModelConfig"<<std::endl;
       }  
 
       // specify the parameters of interest in the interval
       virtual void SetParameters(const RooArgSet& /*set*/) {
-	cout << "DEPRECATED, use ModelConfig"<<endl;
+        std::cout << "DEPRECATED, use ModelConfig"<<std::endl;
       }
 
       // specify the nuisance parameters (eg. the rest of the parameters)
       virtual void SetNuisanceParameters(const RooArgSet& /*set*/) {
-	cout << "DEPRECATED, use ModelConfig"<<endl;
+        std::cout << "DEPRECATED, use ModelConfig"<<std::endl;
       }
 
       // set the size of the test (rate of Type I error) ( Eg. 0.05 for a 95% Confidence Interval)
diff --git a/roofit/roostats/inc/RooStats/NumEventsTestStat.h b/roofit/roostats/inc/RooStats/NumEventsTestStat.h
index 9038391..c273a1b 100644
--- a/roofit/roostats/inc/RooStats/NumEventsTestStat.h
+++ b/roofit/roostats/inc/RooStats/NumEventsTestStat.h
@@ -1,4 +1,4 @@
-// @(#)root/roostats:$Id: NumEventsTestStat.h 43881 2012-04-20 16:01:26Z moneta $
+// @(#)root/roostats:$Id: NumEventsTestStat.h 44376 2012-05-30 21:47:29Z moneta $
 // Author: Kyle Cranmer, Lorenzo Moneta, Gregory Schott, Wouter Verkerke
 /*************************************************************************
  * Copyright (C) 1995-2008, Rene Brun and Fons Rademakers.               *
@@ -65,7 +65,7 @@ namespace RooStats {
      virtual Double_t Evaluate(RooAbsData& data, RooArgSet& /*paramsOfInterest*/)  {       
       
          if(!&data) {
-            cout << "Data set reference is NULL" << endl;
+            std::cout << "Data set reference is NULL" << std::endl;
             return 0;
          }
 
@@ -91,7 +91,7 @@ namespace RooStats {
             return numEvents;
          }
 
-         cout << "Data set is invalid" << endl;
+         std::cout << "Data set is invalid" << std::endl;
          return 0;
      }
 
diff --git a/roofit/roostats/inc/RooStats/PdfProposal.h b/roofit/roostats/inc/RooStats/PdfProposal.h
index 073ac4a..a01d571 100644
--- a/roofit/roostats/inc/RooStats/PdfProposal.h
+++ b/roofit/roostats/inc/RooStats/PdfProposal.h
@@ -1,4 +1,4 @@
-// @(#)root/roostats:$Id: PdfProposal.h 44077 2012-05-02 17:10:21Z moneta $
+// @(#)root/roostats:$Id: PdfProposal.h 44368 2012-05-30 15:38:44Z axel $
 // Authors: Kevin Belasco        17/06/2009
 // Authors: Kyle Cranmer         17/06/2009
 /*************************************************************************
@@ -116,8 +116,8 @@ namespace RooStats {
 
    protected:
       RooAbsPdf* fPdf; // the proposal density function
-      map<RooRealVar*, RooAbsReal*> fMap; // map of values in pdf to update
-      map<RooRealVar*, RooAbsReal*>::iterator fIt; // pdf iterator
+      std::map<RooRealVar*, RooAbsReal*> fMap; // map of values in pdf to update
+      std::map<RooRealVar*, RooAbsReal*>::iterator fIt; // pdf iterator
       RooArgSet fLastX; // the last point we were at
       Int_t fCacheSize; // how many points to generate each time
       Int_t fCachePosition; // our position in the cached proposal data set
diff --git a/roofit/roostats/inc/RooStats/ProfileLikelihoodTestStat.h b/roofit/roostats/inc/RooStats/ProfileLikelihoodTestStat.h
index 3f87807..ecfd584 100644
--- a/roofit/roostats/inc/RooStats/ProfileLikelihoodTestStat.h
+++ b/roofit/roostats/inc/RooStats/ProfileLikelihoodTestStat.h
@@ -1,4 +1,4 @@
-// @(#)root/roostats:$Id: ProfileLikelihoodTestStat.h 44157 2012-05-07 16:41:44Z moneta $
+// @(#)root/roostats:$Id: ProfileLikelihoodTestStat.h 44473 2012-06-01 16:12:31Z moneta $
 // Author: Kyle Cranmer, Lorenzo Moneta, Gregory Schott, Wouter Verkerke
 // Additional Contributions: Giovanni Petrucciani 
 /*************************************************************************
@@ -66,6 +66,7 @@ namespace RooStats {
         fLastData = 0;
 	fLimitType = twoSided;
 	fSigned = false;
+        fDetailedOutputWithErrorsAndPulls = false;
         fDetailedOutputEnabled = false;
         fDetailedOutput = NULL;
       
@@ -84,6 +85,7 @@ namespace RooStats {
        fLastData = 0;
        fLimitType = twoSided;
        fSigned = false;
+       fDetailedOutputWithErrorsAndPulls = false;
        fDetailedOutputEnabled = false;
        fDetailedOutput = NULL;
       
@@ -101,6 +103,8 @@ namespace RooStats {
        if(fDetailedOutput) delete fDetailedOutput;
      }
 
+     //LM use default copy constructor and assignment copying the pointers. Is this what we want ?
+
      void SetOneSided(Bool_t flag=true) {fLimitType = (flag ? oneSided : twoSided);}
      void SetOneSidedDiscovery(Bool_t flag=true) {fLimitType = (flag ? oneSidedDiscovery : twoSided);}
      void SetSigned(Bool_t flag=true) {fSigned = flag;}  // +/- t_mu instead of t_mu>0 with one-sided settings
@@ -128,6 +132,7 @@ namespace RooStats {
      virtual void EnableDetailedOutput( bool e=true, bool withErrorsAndPulls=false ) {
         fDetailedOutputEnabled = e;
         fDetailedOutputWithErrorsAndPulls = withErrorsAndPulls;
+        delete fDetailedOutput;
         fDetailedOutput = NULL;
      }
      virtual const RooArgSet* GetDetailedOutput(void) const {
@@ -139,9 +144,12 @@ namespace RooStats {
 	     // </ul>
 	     return fDetailedOutput;
      }
-    
+         
      virtual void SetVarName(const char* name) { fVarName = name; }
      virtual const TString GetVarName() const {return fVarName;}
+
+     virtual RooAbsPdf * GetPdf() const { return fPdf; }
+
       
       //      const bool PValueIsRightTail(void) { return false; } // overwrites default
 
diff --git a/roofit/roostats/inc/RooStats/ProposalHelper.h b/roofit/roostats/inc/RooStats/ProposalHelper.h
index b0dd010..c4b1860 100644
--- a/roofit/roostats/inc/RooStats/ProposalHelper.h
+++ b/roofit/roostats/inc/RooStats/ProposalHelper.h
@@ -1,4 +1,4 @@
-// @(#)root/roostats:$Id: ProposalHelper.h 44077 2012-05-02 17:10:21Z moneta $
+// @(#)root/roostats:$Id: ProposalHelper.h 44368 2012-05-30 15:38:44Z axel $
 // Authors: Kevin Belasco        7/22/2009
 // Authors: Kyle Cranmer         7/22/2009
 /*************************************************************************
@@ -60,7 +60,7 @@ namespace RooStats {
             fCacheSize = size;
          else
             coutE(Eval) << "Warning: Requested non-positive cache size: " <<
-                           size << ". Cache size unchanged." << endl;
+                           size << ". Cache size unchanged." << std::endl;
       }
 
       virtual void SetUpdateProposalParameters(Bool_t updateParams)
diff --git a/roofit/roostats/inc/RooStats/SimpleLikelihoodRatioTestStat.h b/roofit/roostats/inc/RooStats/SimpleLikelihoodRatioTestStat.h
index d04c650..cfa6a61 100644
--- a/roofit/roostats/inc/RooStats/SimpleLikelihoodRatioTestStat.h
+++ b/roofit/roostats/inc/RooStats/SimpleLikelihoodRatioTestStat.h
@@ -1,4 +1,4 @@
-// @(#)root/roostats:$Id: SimpleLikelihoodRatioTestStat.h 43847 2012-04-19 14:23:18Z moneta $
+// @(#)root/roostats:$Id: SimpleLikelihoodRatioTestStat.h 44368 2012-05-30 15:38:44Z axel $
 // Author: Kyle Cranmer and Sven Kreiss    June 2010
 /*************************************************************************
  * Copyright (C) 1995-2008, Rene Brun and Fons Rademakers.               *
@@ -165,7 +165,7 @@ class SimpleLikelihoodRatioTestStat : public TestStatistic {
          if (fFirstEval && ParamsAreEqual()) {
             oocoutW(fNullParameters,InputArguments)
                << "Same RooArgSet used for null and alternate, so you must explicitly SetNullParameters and SetAlternateParameters or the likelihood ratio will always be 1."
-               << endl;
+               << std::endl;
          }
          fFirstEval = false;
 
@@ -191,7 +191,7 @@ class SimpleLikelihoodRatioTestStat : public TestStatistic {
          *attachedSet = nullPOI;
          double nullNLL = fNllNull->getVal();
          
-         //cout << endl << "SLRTS: null params:" << endl;
+         //cout << std::endl << "SLRTS: null params:" << std::endl;
          //attachedSet->Print("v");
          
 
@@ -215,11 +215,11 @@ class SimpleLikelihoodRatioTestStat : public TestStatistic {
          *attachedSet = *fAltParameters;
          double altNLL = fNllAlt->getVal();
 
-         //cout << endl << "SLRTS: alt params:" << endl;
+         //cout << std::endl << "SLRTS: alt params:" << std::endl;
          //attachedSet->Print("v");
 
 
-         //cout << endl << "SLRTS null NLL: " << nullNLL << "    alt NLL: " << altNLL << endl << endl;
+         //cout << std::endl << "SLRTS null NLL: " << nullNLL << "    alt NLL: " << altNLL << std::endl << std::endl;
 
 
          if (!reuse) { 
@@ -238,9 +238,9 @@ class SimpleLikelihoodRatioTestStat : public TestStatistic {
             fDetailedOutput->setRealValue( "nullNLL", nullNLL );
             fDetailedOutput->setRealValue( "altNLL", altNLL );
 
-//             cout << endl << "STORING THIS AS DETAILED OUTPUT:" << endl;
+//             cout << std::endl << "STORING THIS AS DETAILED OUTPUT:" << std::endl;
 //             fDetailedOutput->Print("v");
-//             cout << endl;
+//             cout << std::endl;
          }
 
 
diff --git a/roofit/roostats/inc/RooStats/ToyMCImportanceSampler.h b/roofit/roostats/inc/RooStats/ToyMCImportanceSampler.h
index 64339c5..01724c2 100644
--- a/roofit/roostats/inc/RooStats/ToyMCImportanceSampler.h
+++ b/roofit/roostats/inc/RooStats/ToyMCImportanceSampler.h
@@ -75,9 +75,9 @@ class ToyMCImportanceSampler: public ToyMCSampler {
 
       using ToyMCSampler::GenerateToyData;
       virtual RooAbsData* GenerateToyData(RooArgSet& paramPoint, double& weight) const;
-      virtual RooAbsData* GenerateToyData(RooArgSet& paramPoint, double& weight, vector<double>& impNLLs, double& nullNLL) const;
-      virtual RooAbsData* GenerateToyData(vector<double>& weights) const;
-      virtual RooAbsData* GenerateToyData(vector<double>& weights, vector<double>& nullNLLs, vector<double>& impNLLs) const;
+      virtual RooAbsData* GenerateToyData(RooArgSet& paramPoint, double& weight, std::vector<double>& impNLLs, double& nullNLL) const;
+      virtual RooAbsData* GenerateToyData(std::vector<double>& weights) const;
+      virtual RooAbsData* GenerateToyData(std::vector<double>& weights, std::vector<double>& nullNLLs, std::vector<double>& impNLLs) const;
 
 
       /// specifies the pdf to sample from
@@ -87,7 +87,7 @@ class ToyMCImportanceSampler: public ToyMCSampler {
          ) {
             oocoutE((TObject*)0,InputArguments) << "Index out of range. Requested index: "<<i<<
                " , but null densities: "<<fNullDensities.size()<<
-               " and importance densities: "<<fImportanceDensities.size() << endl;
+               " and importance densities: "<<fImportanceDensities.size() << std::endl;
          }
          
          fIndexGenDensity = i;
@@ -103,11 +103,11 @@ class ToyMCImportanceSampler: public ToyMCSampler {
       // is used. The snapshot is also optional.
       void AddImportanceDensity(RooAbsPdf* p, const RooArgSet* s) {
          if( p == NULL && s == NULL ) {
-            oocoutI((TObject*)0,InputArguments) << "Neither density nor snapshot given. Doing nothing." << endl;
+            oocoutI((TObject*)0,InputArguments) << "Neither density nor snapshot given. Doing nothing." << std::endl;
             return;
          }
          if( p == NULL && fPdf == NULL ) {
-            oocoutE((TObject*)0,InputArguments) << "No density given, but snapshot is there. Aborting." << endl;
+            oocoutE((TObject*)0,InputArguments) << "No density given, but snapshot is there. Aborting." << std::endl;
             return;
          }
          
@@ -124,7 +124,7 @@ class ToyMCImportanceSampler: public ToyMCSampler {
       // is used. The snapshot and TestStatistic is also optional.
       void AddNullDensity(RooAbsPdf* p, const RooArgSet* s = NULL) {
          if( p == NULL && s == NULL ) {
-            oocoutI((TObject*)0,InputArguments) << "Neither density nor snapshot nor test statistic given. Doing nothing." << endl;
+            oocoutI((TObject*)0,InputArguments) << "Neither density nor snapshot nor test statistic given. Doing nothing." << std::endl;
             return;
          }
          
@@ -144,7 +144,7 @@ class ToyMCImportanceSampler: public ToyMCSampler {
          if( fNullDensities.size() == 1 ) { fNullDensities[0] = &pdf; }
          else if( fNullDensities.size() == 0) AddNullDensity( &pdf );
          else{
-            oocoutE((TObject*)0,InputArguments) << "Cannot use SetPdf() when already multiple null densities are specified. Please use AddNullDensity()." << endl;
+            oocoutE((TObject*)0,InputArguments) << "Cannot use SetPdf() when already multiple null densities are specified. Please use AddNullDensity()." << std::endl;
          }
       }
       // overwrite from ToyMCSampler
@@ -152,11 +152,11 @@ class ToyMCImportanceSampler: public ToyMCSampler {
          ToyMCSampler::SetParametersForTestStat(nullpoi);
          if( fNullSnapshots.size() == 0 ) AddNullDensity( NULL, &nullpoi );
          else if( fNullSnapshots.size() == 1 ) {
-            oocoutI((TObject*)0,InputArguments) << "Overwriting snapshot for the only defined null density." << endl;
+            oocoutI((TObject*)0,InputArguments) << "Overwriting snapshot for the only defined null density." << std::endl;
             if( fNullSnapshots[0] ) delete fNullSnapshots[0];
             fNullSnapshots[0] = (const RooArgSet*)nullpoi.snapshot();
          }else{
-            oocoutE((TObject*)0,InputArguments) << "Cannot use SetParametersForTestStat() when already multiple null densities are specified. Please use AddNullDensity()." << endl;
+            oocoutE((TObject*)0,InputArguments) << "Cannot use SetParametersForTestStat() when already multiple null densities are specified. Please use AddNullDensity()." << std::endl;
          }
       }
 
@@ -197,19 +197,19 @@ class ToyMCImportanceSampler: public ToyMCSampler {
       bool fApplyVeto;
 
       // support multiple null densities
-      vector<RooAbsPdf*> fNullDensities;
-      mutable vector<const RooArgSet*> fNullSnapshots;
+      std::vector<RooAbsPdf*> fNullDensities;
+      mutable std::vector<const RooArgSet*> fNullSnapshots;
 
       // densities and snapshots to generate from      
-      vector<RooAbsPdf*> fImportanceDensities;
-      vector<const RooArgSet*> fImportanceSnapshots;
+      std::vector<RooAbsPdf*> fImportanceDensities;
+      std::vector<const RooArgSet*> fImportanceSnapshots;
       
       bool fReuseNLL;
       
       toysStrategies fToysStrategy;
 
-      mutable vector<RooAbsReal*> fNullNLLs;    //!
-      mutable vector<RooAbsReal*> fImpNLLs;     //!
+      mutable std::vector<RooAbsReal*> fNullNLLs;    //!
+      mutable std::vector<RooAbsReal*> fImpNLLs;     //!
 
 
    protected:
diff --git a/roofit/roostats/inc/RooStats/ToyMCSampler.h b/roofit/roostats/inc/RooStats/ToyMCSampler.h
index 10763c8..4056b17 100644
--- a/roofit/roostats/inc/RooStats/ToyMCSampler.h
+++ b/roofit/roostats/inc/RooStats/ToyMCSampler.h
@@ -1,4 +1,4 @@
-// @(#)root/roostats:$Id: ToyMCSampler.h 44157 2012-05-07 16:41:44Z moneta $
+// @(#)root/roostats:$Id: ToyMCSampler.h 44473 2012-06-01 16:12:31Z moneta $
 // Author: Sven Kreiss and Kyle Cranmer    June 2010
 // Author: Kyle Cranmer, Lorenzo Moneta, Gregory Schott, Wouter Verkerke
 // Additions and modifications by Mario Pelliccioni
@@ -53,6 +53,8 @@ END_HTML
 
 namespace RooStats {
 
+  class DetailedOutputAggregator;
+
 // only used inside ToyMCSampler, ie "private" in the cxx file
 class NuisanceParametersSampler {
    // Helper for ToyMCSampler. Handles all of the nuisance parameter related
@@ -116,11 +118,12 @@ class ToyMCSampler: public TestStatSampler {
       // is used. The snapshot and TestStatistic is also optional.
       virtual void AddTestStatistic(TestStatistic* t = NULL) {
          if( t == NULL ) {
-            oocoutI((TObject*)0,InputArguments) << "No test statistic given. Doing nothing." << endl;
+            oocoutI((TObject*)0,InputArguments) << "No test statistic given. Doing nothing." << std::endl;
             return;
          }
+
+         //if( t == NULL && fTestStatistics.size() >= 1 ) t = fTestStatistics[0];
          
-         if( t == NULL && fTestStatistics.size() >= 1 ) t = fTestStatistics[0];
          fTestStatistics.push_back( t );
       }      
 
@@ -129,7 +132,7 @@ class ToyMCSampler: public TestStatSampler {
       // generates toy data
       //   without weight
       virtual RooAbsData* GenerateToyData(RooArgSet& paramPoint, RooAbsPdf& pdf) const {
-         if(fExpectedNuisancePar) oocoutE((TObject*)NULL,InputArguments) << "ToyMCSampler: using expected nuisance parameters but ignoring weight. Use GetSamplingDistribution(paramPoint, weight) instead." << endl;
+         if(fExpectedNuisancePar) oocoutE((TObject*)NULL,InputArguments) << "ToyMCSampler: using expected nuisance parameters but ignoring weight. Use GetSamplingDistribution(paramPoint, weight) instead." << std::endl;
          double weight;
          return GenerateToyData(paramPoint, weight, pdf);
       }
@@ -147,18 +150,7 @@ class ToyMCSampler: public TestStatSampler {
          return fTestStatistics[i]->Evaluate(data, nullPOI);
       }
       virtual Double_t EvaluateTestStatistic(RooAbsData& data, RooArgSet& nullPOI) { return EvaluateTestStatistic( data,nullPOI, 0 ); }
-      virtual RooArgList* EvaluateAllTestStatistics(RooAbsData& data, RooArgSet& nullPOI) {
-         RooArgList* allTS = new RooArgList( "allTS" );
-         for( unsigned int i = 0; i < fTestStatistics.size(); i++ ) {
-            if( fTestStatistics[i] == NULL ) continue;
-            allTS->add( *(new RooRealVar(
-               TString::Format( "%s_TS%d", fSamplingDistName.c_str(),i ),
-               fTestStatistics[i]->GetVarName(),
-               fTestStatistics[i]->Evaluate( data, nullPOI )
-            ) ) );
-         }
-         return allTS;
-      }
+      virtual RooArgList* EvaluateAllTestStatistics(RooAbsData& data, const RooArgSet& poi);
 
 
       virtual TestStatistic* GetTestStatistic(unsigned int i) const {
@@ -209,7 +201,7 @@ class ToyMCSampler: public TestStatSampler {
       // Set the TestStatistic (want the argument to be a function of the data & parameter points
       virtual void SetTestStatistic(TestStatistic *testStatistic, unsigned int i) {
          if( fTestStatistics.size() < i ) {
-            oocoutE((TObject*)NULL,InputArguments) << "Cannot set test statistic for this index." << endl;
+            oocoutE((TObject*)NULL,InputArguments) << "Cannot set test statistic for this index." << std::endl;
             return;
          }
 	 if( fTestStatistics.size() == i)
@@ -234,7 +226,7 @@ class ToyMCSampler: public TestStatSampler {
 
       // Set the name of the sampling distribution used for plotting
       void SetSamplingDistName(const char* name) { if(name) fSamplingDistName = name; }
-      string GetSamplingDistName(void) { return fSamplingDistName; }
+      std::string GetSamplingDistName(void) { return fSamplingDistName; }
 
       // This option forces a maximum number of total toys.
       void SetMaxToys(Double_t t) { fMaxToys = t; }
@@ -262,6 +254,8 @@ class ToyMCSampler: public TestStatSampler {
       
    protected:
 
+      const RooArgList* EvaluateAllTestStatistics(RooAbsData& data, const RooArgSet& poi, DetailedOutputAggregator& detOutAgg);
+
       // helper for GenerateToyData
       RooAbsData* Generate(RooAbsPdf &pdf, RooArgSet &observables, const RooDataSet *protoData=NULL, int forceEvents=0) const;
 
@@ -272,9 +266,9 @@ class ToyMCSampler: public TestStatSampler {
       // densities, snapshots, and test statistics to reweight to
       RooAbsPdf *fPdf; // model (can be alt or null)
       const RooArgSet* fParametersForTestStat;
-      vector<TestStatistic*> fTestStatistics;
+      std::vector<TestStatistic*> fTestStatistics;
 
-      string fSamplingDistName; // name of the model
+      std::string fSamplingDistName; // name of the model
       RooAbsPdf *fPriorNuisance; // prior pdf for nuisance parameters
       const RooArgSet *fNuisancePars;
       const RooArgSet *fObservables;
@@ -306,9 +300,9 @@ class ToyMCSampler: public TestStatSampler {
 
       // objects below cache information and are mutable and non-persistent
       mutable RooArgSet* _allVars ; //! 
-      mutable list<RooAbsPdf*> _pdfList ; //!
-      mutable list<RooArgSet*> _obsList ; //!
-      mutable list<RooAbsPdf::GenSpec*> _gsList ; //!      
+      mutable std::list<RooAbsPdf*> _pdfList ; //!
+      mutable std::list<RooArgSet*> _obsList ; //!
+      mutable std::list<RooAbsPdf::GenSpec*> _gsList ; //!      
       mutable RooAbsPdf::GenSpec* _gs1 ; //! GenSpec #1 
       mutable RooAbsPdf::GenSpec* _gs2 ; //! GenSpec #2
       mutable RooAbsPdf::GenSpec* _gs3 ; //! GenSpec #3
diff --git a/roofit/roostats/inc/RooStats/ToyMCSamplerOld.h b/roofit/roostats/inc/RooStats/ToyMCSamplerOld.h
deleted file mode 100644
index 8c6053b..0000000
--- a/roofit/roostats/inc/RooStats/ToyMCSamplerOld.h
+++ /dev/null
@@ -1,322 +0,0 @@
-// @(#)root/roostats:$Id: ToyMCSamplerOld.h 44157 2012-05-07 16:41:44Z moneta $
-// Author: Kyle Cranmer, Lorenzo Moneta, Gregory Schott, Wouter Verkerke
-// Additions and modifications by Mario Pelliccioni
-/*************************************************************************
- * Copyright (C) 1995-2008, Rene Brun and Fons Rademakers.               *
- * All rights reserved.                                                  *
- *                                                                       *
- * For the licensing terms see $ROOTSYS/LICENSE.                         *
- * For the list of contributors see $ROOTSYS/README/CREDITS.             *
- *************************************************************************/
-
-#ifndef ROOSTATS_ToyMCSamplerOld
-#define ROOSTATS_ToyMCSamplerOld
-
-//_________________________________________________
-/*
-BEGIN_HTML
-<p>
-ToyMCSamplerOld is a simple implementation of the TestStatSampler interface.
-It generates Toy Monte Carlo for a given parameter point, and evaluates a 
-test statistic that the user specifies (passed via the RooStats::TestStatistic interface).
-
-Development notes: We need to provide a nice way for the user to:
-<ul>
-  <li>specify the number of toy experiments (needed to probe a given confidence level)</li>
-  <li>specify if the number of events per toy experiment should be fixed (conditioning) or floating (unconditional)</li>
-  <li>specify if any auxiliary observations should be fixed (conditioning) or floating (unconditional)</li>
-  <li>specify if nuisance paramters should be part of the toy MC: eg: integrated out (Bayesian marginalization)</li>
-</ul>
-
-All of these should be made fairly explicit in the interface.
-</p>
-END_HTML
-*/
-//
-
-#ifndef ROOT_Rtypes
-#include "Rtypes.h"
-#endif
-
-#include <vector>
-#include <string>
-#include <sstream>
-
-#include "RooStats/TestStatSampler.h"
-#include "RooStats/SamplingDistribution.h"
-#include "RooStats/TestStatistic.h"
-#include "RooStats/RooStatsUtils.h"
-
-#include "RooWorkspace.h"
-#include "RooMsgService.h"
-#include "RooAbsPdf.h"
-#include "TRandom.h"
-
-#include "RooDataSet.h"
-
-namespace RooStats {
-
-    class ToyMCSamplerOld : public TestStatSampler {
-
-
-  public:
-    ToyMCSamplerOld(TestStatistic &ts) {
-      fTestStat = &ts;
-      fWS = new RooWorkspace();
-      fOwnsWorkspace = true;
-      fDataName = "";
-      fPdfName = "";
-      fNullPOI = 0;
-      fNuisParams=0;
-      fObservables=0;
-      fExtended = kTRUE;
-      fRand = new TRandom();
-      fCounter=0;
-      fVarName = fTestStat->GetVarName();
-      fLastDataSet = 0;
-      fNevents = 0; 
-      fNtoys = 0; 
-      fSize = 0.05; 
-    }
-
-    virtual ~ToyMCSamplerOld() {
-      if(fOwnsWorkspace) delete fWS;
-      if(fRand) delete fRand;
-      if(fLastDataSet) delete fLastDataSet;
-    }
-    
-    // Extended interface to append to sampling distribution more samples
-    virtual SamplingDistribution* AppendSamplingDistribution(RooArgSet& allParameters, 
-							     SamplingDistribution* last, 
-							     Int_t additionalMC) {
-
-      Int_t tmp = fNtoys;
-      fNtoys = additionalMC;
-      SamplingDistribution* newSamples = GetSamplingDistribution(allParameters);
-      fNtoys = tmp;
-
-      if(last){
-	last->Add(newSamples);
-	delete newSamples;
-	return last;
-      }
-
-      return newSamples;
-    }
-
-    // Main interface to get a SamplingDistribution
-    virtual SamplingDistribution* GetSamplingDistribution(RooArgSet& allParameters) {
-      std::vector<Double_t> testStatVec;
-      //       cout << " about to generate sampling dist " << endl;
-
-      RooFit::MsgLevel msglevel = RooMsgService::instance().globalKillBelow();
-      RooMsgService::instance().setGlobalKillBelow(RooFit::ERROR) ;
-
-      for(Int_t i=0; i<fNtoys; ++i){
-	//cout << " on toy number " << i << endl;
-	//	RooAbsData* toydata = (RooAbsData*)GenerateToyData(allParameters);
-	//	testStatVec.push_back( fTestStat->Evaluate(*toydata, allParameters) );
-	//	delete toydata;
-
-	RooDataSet* toydata = (RooDataSet*)GenerateToyData(allParameters);
-
-	// note, evaluation always done at fNullPOI
-	testStatVec.push_back( fTestStat->Evaluate(*toydata, *fNullPOI) );
-
-	// want to clean up memory, but delete toydata causes problem with 
-	// nll->setData(data, noclone) because pointer to last data set is no longer valid
-	//	delete toydata; 
-
-	// instead, delete previous data set
-	if(fLastDataSet) delete fLastDataSet;
-	fLastDataSet = toydata;
-      }
-     
-       RooMsgService::instance().setGlobalKillBelow(msglevel);
-
-      //      cout << " generated sampling dist " << endl;
-      return new SamplingDistribution( "temp",//MakeName(allParameters).c_str(),
-				       "Sampling Distribution of Test Statistic", testStatVec, fVarName );
-    } 
-
-     virtual RooAbsData* GenerateToyData(RooArgSet& allParameters) const {
-       // This method generates a toy dataset for the given parameter point.
-
-
-       //       cout << "fNevents = " << fNevents << endl;
-       RooAbsPdf* pdf = fWS->pdf(fPdfName);
-       if(!fObservables){
-	 cout << "Observables not specified in ToyMCSamplerOld, will try to determine.  "
-	      << "Will ignore all constant parameters, parameters of interest, and nuisance parameters." << endl;
-	 RooArgSet* observables = pdf->getVariables();
-	 RemoveConstantParameters(observables); // observables might be set constant, this is just a guess
-
-
-	 if(fNullPOI) observables->remove(*fNullPOI, kFALSE, kTRUE);
-	 if(fNuisParams) observables->remove(*fNuisParams, kFALSE, kTRUE);
-	 cout << "will use the following as observables when generating data" << endl;
-	 observables->Print();
-	 fObservables=observables;
-       } /*else {
-	   cout << "obs set: will use the following as observables when generating data" << endl;
-	   fObservables->Print();
-	   }*/
-
-       //fluctuate the number of events if fExtended is on.  
-       // This is a bit slippery for number counting expts. where entry in data and
-
-       /*
-       // model is number of events, and so number of entries in data always =1.
-       Int_t nEvents = fNevents;
-       if(fExtended) {
-	 if( pdf->expectedEvents(*fObservables) > 0){
-	   // if PDF knows expected events use it instead
-	   nEvents = fRand->Poisson(pdf->expectedEvents(*fObservables));
-	 } else{
-	   nEvents = fRand->Poisson(fNevents);
-	 }
-       }
-       */
-
-       // Set the parameters to desired values for generating toys
-       RooArgSet* parameters = pdf->getParameters(fObservables);
-       RooStats::SetParameters(&allParameters, parameters);
-
-       /*       
-	 cout << "expected events = " <<  pdf->expectedEvents(*observables) 
-	    << "fExtended = " << fExtended
-	    << "fNevents = " << fNevents << " fNevents " 
-	    << "generating" << nEvents << " events " << endl;
-       */
-       
-       RooFit::MsgLevel level = RooMsgService::instance().globalKillBelow();
-       RooMsgService::instance().setGlobalKillBelow(RooFit::ERROR) ;
-
-       //       cout << "nEvents = " << nEvents << endl;
-       RooAbsData* data = NULL;
-       if(fExtended) {
-	 data = (RooAbsData*)pdf->generate(*fObservables, RooFit::Extended());
-       } else {
-	 data = (RooAbsData*)pdf->generate(*fObservables, fNevents);
-     }
-
-       RooMsgService::instance().setGlobalKillBelow(level) ;
-       delete parameters;
-       return data;
-     }
-
-     // helper method to create meaningful names for sampling dist
-     string MakeName(RooArgSet& /*params*/){
-       std::ostringstream str;
-       str<<"SamplingDist_"<< fCounter;
-       fCounter++;
-       std::string buf = str.str(); 
-       return buf ;       
-     }
-
-      // Main interface to evaluate the test statistic on a dataset
-     virtual Double_t EvaluateTestStatistic(RooAbsData& data, RooArgSet& allParameters) {
-       return fTestStat->Evaluate(data, allParameters);
-     }
-
-      // Get the TestStatistic
-      virtual TestStatistic* GetTestStatistic()  const {
-	 return fTestStat;
-      }  
-    
-      // Get the Confidence level for the test
-      virtual Double_t ConfidenceLevel()  const {return 1.-fSize;}  
-
-      // Common Initialization
-      virtual void Initialize(RooAbsArg& /*testStatistic*/, 
-			      RooArgSet& /*paramsOfInterest*/, 
-			      RooArgSet& /*nuisanceParameters*/) {}
-
-      //set the parameters for the toyMC generation
-      virtual void SetNToys(const Int_t ntoy) {
-        fNtoys = ntoy;
-      }
-
-      virtual void SetNEventsPerToy(const Int_t nevents) {
-        fNevents = nevents;
-      }
-
-
-      virtual void SetExtended(const Bool_t isExtended) {
-        fExtended = isExtended;
-      }
-
-      // Set the DataSet, add to the the workspace if not already there
-      virtual void SetData(RooAbsData& data) {
-	if(&data){
-	  fWS->import(data);
-	  fDataName = data.GetName();
-	  fWS->Print();
-	}
-      }
-      // Set the Pdf, add to the the workspace if not already there
-      virtual void SetPdf(RooAbsPdf& pdf) { 
-	if(&pdf){
-	  fWS->import(pdf);
-	  fPdfName = pdf.GetName();
-	}
-      }
-
-      // specify the name of the dataset in the workspace to be used
-      virtual void SetData(const char* name) {fDataName = name;}
-      // specify the name of the PDF in the workspace to be used
-      virtual void SetPdf(const char* name) {fPdfName = name;}
-      // How to randomize the prior. Set to NULL to deactivate randomization.
-      virtual void SetPriorNuisance(RooAbsPdf* /*not supported*/) {}
-
-      // specify the values of parameters used when evaluating test statistic
-      virtual void SetParametersForTestStat(const RooArgSet& nullpoi) {fNullPOI = (RooArgSet*)nullpoi.snapshot();}
-      // specify the nuisance parameters (eg. the rest of the parameters)
-      virtual void SetNuisanceParameters(const RooArgSet& set) {fNuisParams = &set;}
-      // specify the observables in the dataset (needed to evaluate the test statistic)
-      virtual void SetObservables(const RooArgSet& set) {fObservables = &set;}
-      // specify the conditional observables
-      virtual void SetGlobalObservables(const RooArgSet& ) {}
-
-      // set the size of the test (rate of Type I error) ( Eg. 0.05 for a 95% Confidence Interval)
-      virtual void SetTestSize(Double_t size) {fSize = size;}
-      // set the confidence level for the interval (eg. 0.95 for a 95% Confidence Interval)
-      virtual void SetConfidenceLevel(Double_t cl) {fSize = 1.-cl;}
-
-      // Set the TestStatistic (want the argument to be a function of the data & parameter points
-      virtual void SetTestStatistic(TestStatistic* testStat)   {
-	fTestStat = testStat;
-      }  
-
-      // Set the name of the sampling distribution used for plotting
-      void SetSamplingDistName(const char* name) { if(name) fSamplingDistName = name; }
-
-      
-   private:
-      Double_t fSize;
-      RooWorkspace* fWS; // a workspace that owns all the components to be used by the calculator
-      Bool_t fOwnsWorkspace; // flag if this object owns its workspace
-      string fSamplingDistName; // name of the model
-      const char* fPdfName; // name of  common PDF in workspace
-      const char* fDataName; // name of data set in workspace
-      RooArgSet* fNullPOI; // the values of parameters used when evaluating test statistic
-      const RooArgSet* fNuisParams;// RooArgSet specifying  nuisance parameters for interval
-      mutable const RooArgSet* fObservables; // RooArgSet specifying the observables in the dataset (needed to evaluate the test statistic)
-      TestStatistic* fTestStat; // pointer to the test statistic that is being sampled
-      Int_t fNtoys; // number of toys to generate
-      Int_t fNevents; // number of events per toy (may be ignored depending on settings)
-      Bool_t fExtended; // if nEvents should fluctuate
-      TRandom* fRand; // random generator
-      TString fVarName; // name of test statistic
-
-      Int_t fCounter; // counter for naming sampling dist objects
-
-      RooDataSet* fLastDataSet; // work around for memory issues in nllvar->setData(data, noclone)
-
-   protected:
-      ClassDef(ToyMCSamplerOld,1)   // A simple implementation of the TestStatSampler interface
-	};
-}
-
-
-#endif
diff --git a/roofit/roostats/src/AsymptoticCalculator.cxx b/roofit/roostats/src/AsymptoticCalculator.cxx
index 47dd41f..e854a5a 100644
--- a/roofit/roostats/src/AsymptoticCalculator.cxx
+++ b/roofit/roostats/src/AsymptoticCalculator.cxx
@@ -1,4 +1,4 @@
-// @(#)root/roostats:$Id: AsymptoticCalculator.cxx 44156 2012-05-07 16:37:38Z moneta $
+// @(#)root/roostats:$Id: AsymptoticCalculator.cxx 44368 2012-05-30 15:38:44Z axel $
 // Author: Kyle Cranmer, Sven Kreiss   23/05/10
 /*************************************************************************
  * Copyright (C) 1995-2008, Rene Brun and Fons Rademakers.               *
@@ -46,6 +46,7 @@
 #include "TStopwatch.h"
 
 using namespace RooStats;
+using namespace std;
 
 namespace Utils { 
 
@@ -135,16 +136,16 @@ AsymptoticCalculator::AsymptoticCalculator(
       allParams->snapshot(nominalParams);
    }
 
-   // evaluate the unconditional nll for the full model on the  observed data  
-   oocoutP((TObject*)0,Eval) << "AsymptoticCalculator: Find  best unconditional NLL on observed data" << endl;
+   // evaluate the unconditional nll for the full model on the  observed data 
+   if (verbose >= 0)
+      oocoutP((TObject*)0,Eval) << "AsymptoticCalculator: Find  best unconditional NLL on observed data" << endl;
    fNLLObs = EvaluateNLL( *nullPdf, *obsData);
    // fill also snapshot of best poi
    poi->snapshot(fBestFitPoi);
-   if (verbose > 0) {
-      std::cout << "Best fitted POI\n";
-      fBestFitPoi.Print("v");
-      std::cout << std::endl;
-   }
+   RooRealVar * muBest = dynamic_cast<RooRealVar*>(fBestFitPoi.first());
+   assert(muBest);
+   if (verbose >= 0)  
+      oocoutP((TObject*)0,Eval) << "Best fitted POI value = " << muBest->getVal() << " +/- " << muBest->getError() << std::endl;   
    // keep snapshot of all best fit parameters
    allParams->snapshot(fBestFitParams);
    delete allParams;
@@ -162,14 +163,16 @@ AsymptoticCalculator::AsymptoticCalculator(
 
 
    if (!nominalAsimov) {
-      oocoutI((TObject*)0,InputArguments) << "AsymptoticCalculator: Asimov data will be generated using fitted nuisance parameter values" << endl;
+      if (verbose >= 0) 
+         oocoutI((TObject*)0,InputArguments) << "AsymptoticCalculator: Asimov data will be generated using fitted nuisance parameter values" << endl;
       RooArgSet * tmp = (RooArgSet*) poiAlt.snapshot(); 
       fAsimovData = MakeAsimovData( data, nullModel, poiAlt, fAsimovGlobObs,tmp);
    }
 
    else {
       // assume use current value of nuisance as nominal ones
-      oocoutI((TObject*)0,InputArguments) << "AsymptoticCalculator: Asimovdata set will be generated using nominal (current) nuisance parameter values" << endl;
+      if (verbose >= 0) 
+         oocoutI((TObject*)0,InputArguments) << "AsymptoticCalculator: Asimovdata set will be generated using nominal (current) nuisance parameter values" << endl;
       nominalParams = poiAlt; // set poi to alt value but keep nuisance at the nominal one
       fAsimovData = MakeAsimovData( nullModel, nominalParams, fAsimovGlobObs);
    }
@@ -196,8 +199,9 @@ AsymptoticCalculator::AsymptoticCalculator(
 
    RooRealVar * muAlt = (RooRealVar*) poiAlt.first();
    assert(muAlt);
-   oocoutP((TObject*)0,Eval) << "AsymptoticCalculator: Find  best conditional NLL on ASIMOV data set for given alt POI ( " << 
-      muAlt->GetName() << " ) = " << muAlt->getVal() << std::endl;
+   if (verbose>=0)
+      oocoutP((TObject*)0,Eval) << "AsymptoticCalculator: Find  best conditional NLL on ASIMOV data set for given alt POI ( " << 
+         muAlt->GetName() << " ) = " << muAlt->getVal() << std::endl;
 
    fNLLAsimov =  EvaluateNLL( *nullPdf, *fAsimovData, &poiAlt );
    // for unconditional fit 
@@ -207,6 +211,17 @@ AsymptoticCalculator::AsymptoticCalculator(
    // restore previous value 
    globObs = globObsSnapshot;
 
+   // try to guess default configuration
+   // (this part should be in constructor)
+   RooRealVar * muNull  = dynamic_cast<RooRealVar*>( nullSnapshot->first() );
+   assert (muNull);
+   if (muNull->getVal() == muNull->getMin()) { 
+      fOneSidedDiscovery = true; 
+      if (verbose > 0) 
+         oocoutI((TObject*)0,InputArguments) << "Minimum of POI is " << muNull->getMin() << " corresponds to null  snapshot   - default configuration is  one-sided discovery formulae  " << std::endl;
+   }
+
+
 
 }
 
@@ -607,7 +622,7 @@ HypoTestResult* AsymptoticCalculator::GetHypoTest() const {
    }
    if (fOneSidedDiscovery ) { 
       if ( muHat->getVal() < muTest->getVal() ) { 
-         oocoutI((TObject*)0,Eval) << "Using one-sided qmu - setting qmu to zero  muHat = " << muHat->getVal() 
+         oocoutI((TObject*)0,Eval) << "Using one-sided discovery qmu - setting qmu to zero  muHat = " << muHat->getVal() 
                                    << " muTest = " << muTest->getVal() << std::endl;
          qmu = 0;
       }
@@ -629,11 +644,18 @@ HypoTestResult* AsymptoticCalculator::GetHypoTest() const {
    
    if (fOneSided || fOneSidedDiscovery) {
       // for one-sided PL (q_mu : equations 56,57)
+      if (verbose>2) {
+         if (fOneSided) 
+            oocoutI((TObject*)0,Eval) << "Using one-sided limit asymptotic formula (qmu)" << endl;
+         else
+            oocoutI((TObject*)0,Eval) << "Using one-sided discovery asymptotic formula (q0)" << endl;
+      }
       pnull = ROOT::Math::normal_cdf_c( sqrtqmu, 1.);
       palt = ROOT::Math::normal_cdf( sqrtqmu_A - sqrtqmu, 1.);
    }
    else  {
       // for 2-sided PL (t_mu : equations 35,36 in asymptotic paper) 
+      if (verbose > 2) oocoutI((TObject*)0,Eval) << "Using two-sided asimptotic  formula (tmu)" << endl;
       pnull = 2.*ROOT::Math::normal_cdf_c( sqrtqmu, 1.);
       palt = ROOT::Math::normal_cdf_c( sqrtqmu + sqrtqmu_A, 1.) + 
          ROOT::Math::normal_cdf_c( sqrtqmu - sqrtqmu_A, 1.); 
@@ -644,6 +666,7 @@ HypoTestResult* AsymptoticCalculator::GetHypoTest() const {
       if (fOneSided) { 
          // for bounded one-sided (q_mu_tilde: equations 64,65)
          if ( qmu > qmu_A) { 
+            if (verbose > 2) oocoutI((TObject*)0,Eval) << "Using qmu_tilde (qmu is greater than qmu_A)" << endl;
             pnull = ROOT::Math::normal_cdf_c( (qmu + qmu_A)/(2 * sqrtqmu_A), 1.);
             palt = ROOT::Math::normal_cdf_c( (qmu - qmu_A)/(2 * sqrtqmu_A), 1.);
          }
@@ -652,6 +675,7 @@ HypoTestResult* AsymptoticCalculator::GetHypoTest() const {
          // for 2 sided bounded test statistic  (N.B there is no one sided discovery qtilde)
          // t_mu_tilde: equations 43,44 in asymptotic paper
          if ( qmu >  qmu_A) { 
+            if (verbose > 2) oocoutI((TObject*)0,Eval) << "Using tmu_tilde (qmu is greater than qmu_A)" << endl;
             pnull = ROOT::Math::normal_cdf_c(sqrtqmu,1.) + 
                     ROOT::Math::normal_cdf_c( (qmu + qmu_A)/(2 * sqrtqmu_A), 1.);
             palt = ROOT::Math::normal_cdf_c( sqrtqmu_A + sqrtqmu, 1.) + 
diff --git a/roofit/roostats/src/BayesianCalculator.cxx b/roofit/roostats/src/BayesianCalculator.cxx
index 195eb68..25c1bc9 100644
--- a/roofit/roostats/src/BayesianCalculator.cxx
+++ b/roofit/roostats/src/BayesianCalculator.cxx
@@ -1,4 +1,4 @@
-// @(#)root/roostats:$Id: BayesianCalculator.cxx 44092 2012-05-03 14:46:24Z moneta $
+// @(#)root/roostats:$Id: BayesianCalculator.cxx 44368 2012-05-30 15:38:44Z axel $
 // Author: Kyle Cranmer, Lorenzo Moneta, Gregory Schott, Wouter Verkerke
 /*************************************************************************
  * Copyright (C) 1995-2008, Rene Brun and Fons Rademakers.               *
@@ -88,6 +88,8 @@ END_HTML
 
 ClassImp(RooStats::BayesianCalculator)
 
+using namespace std;
+
 namespace RooStats { 
 
 
@@ -818,6 +820,7 @@ RooAbsReal* BayesianCalculator::GetPosteriorFunction() const
    }
 
 
+
    // need do find minimum of log-likelihood in the range to shift function 
    // to avoid numerical errors when we compute the likelihood (overflows in the exponent)
    // N.B.: this works for only 1 parameter of interest otherwise Minuit should be used for finding the minimum
@@ -827,12 +830,14 @@ RooAbsReal* BayesianCalculator::GetPosteriorFunction() const
    RooRealVar* poi = dynamic_cast<RooRealVar*>( fPOI.first() ); 
    assert(poi);
 
+   // try to reduce some error messages
+   //Bool_t silentMode = (RooMsgService::instance().globalKillBelow() >= RooFit::ERROR || RooMsgService::instance().silentMode()) ;
+   RooAbsReal::setEvalErrorLoggingMode(RooAbsReal::CountErrors);
+
+
    coutI(Eval) <<  "BayesianCalculator::GetPosteriorFunction : " 
                << " nll value " <<  nllVal << " poi value = " << poi->getVal() << std::endl;
 
-   // if pdf evaluates to zero, should be fixed, but this will
-   // stop error messages.
-   fLogLike->setEvalErrorLoggingMode(RooAbsReal::CountErrors);
 
    ROOT::Math::BrentMinimizer1D minim; 
    minim.SetFunction(wnllFunc,poi->getMin(),poi->getMax() );
@@ -900,7 +905,6 @@ RooAbsReal* BayesianCalculator::GetPosteriorFunction() const
          fIntegratedLikelihood = fLikelihood->createIntegral(fNuisanceParameters);
 
 
-      return fIntegratedLikelihood;
    }
 
    else if ( fIntegrationType.Contains("TOYMC") ) { 
@@ -943,11 +947,12 @@ RooAbsReal* BayesianCalculator::GetPosteriorFunction() const
 
    }
 
-   //fIntegratedLikelihood->setEvalErrorLoggingMode(RooAbsReal::CountErrors);
-
-   // ccoutD(Eval) << "BayesianCalculator::GetPosteriorFunction : use ROOT numerical integration algorithm. "; 
-   // ccoutD(Eval) << " Integrated log-likelihood = " << fIntegratedLikelihood->getVal() << std::endl;
 
+   if (RooAbsReal::numEvalErrors() > 0) 
+      coutW(Eval) << "BayesianCalculator::GetPosteriorFunction : " << RooAbsReal::numEvalErrors() << " errors reported in evaluating log-likelihood function "
+                   << std::endl;         
+   RooAbsReal::clearEvalErrorLog();
+   RooAbsReal::setEvalErrorLoggingMode(RooAbsReal::PrintErrors);
    
    return fIntegratedLikelihood;  
 
@@ -1002,12 +1007,16 @@ RooPlot* BayesianCalculator::GetPosteriorPlot(bool norm, double precision ) cons
    if (!plot) return 0;
 
    // try to reduce some error messages
-   posterior->setEvalErrorLoggingMode(RooAbsReal::CountErrors);
+   RooAbsReal::setEvalErrorLoggingMode(RooAbsReal::CountErrors);
 
    plot->SetTitle(TString("Posterior probability of parameter \"")+TString(poi->GetName())+TString("\""));  
    posterior->plotOn(plot,RooFit::Range(fLower,fUpper,kFALSE),RooFit::VLines(),RooFit::DrawOption("F"),RooFit::MoveToBack(),RooFit::FillColor(kGray),RooFit::Precision(precision));
    posterior->plotOn(plot);
    plot->GetYaxis()->SetTitle("posterior function");
+
+   // reset the counts and default mode
+   RooAbsReal::clearEvalErrorLog();
+   RooAbsReal::setEvalErrorLoggingMode(RooAbsReal::PrintErrors);
    
    return plot; 
 }
@@ -1073,9 +1082,14 @@ SimpleInterval* BayesianCalculator::GetInterval() const
       return 0; 
    } 
 
+
+
    // get integrated likelihood (posterior function) 
    GetPosteriorFunction();
 
+   //Bool_t silentMode = (RooMsgService::instance().globalKillBelow() >= RooFit::ERROR || RooMsgService::instance().silentMode()) ;
+   RooAbsReal::setEvalErrorLoggingMode(RooAbsReal::CountErrors);
+
    if (fLeftSideFraction < 0 ) { 
       // compute short intervals
       ComputeShortestInterval(); 
@@ -1110,6 +1124,15 @@ SimpleInterval* BayesianCalculator::GetInterval() const
       }
    }
 
+
+   // reset the counts and default mode
+   if (RooAbsReal::numEvalErrors() > 0) 
+      coutW(Eval) << "BayesianCalculator::GetInterval : " << RooAbsReal::numEvalErrors() << " errors reported in evaluating log-likelihood function "
+                   << std::endl;         
+   
+   RooAbsReal::clearEvalErrorLog();
+   RooAbsReal::setEvalErrorLoggingMode(RooAbsReal::PrintErrors);
+
    if (!fValidInterval) { 
       fLower = 1; fUpper = 0;
       coutE(Eval) << "BayesianCalculator::GetInterval - cannot compute a valid interval - return a dummy [1,0] interval"
@@ -1275,11 +1298,10 @@ void BayesianCalculator::ApproximatePosterior() const {
       fApproxPosterior = 0;
    }      
 
+
    RooAbsReal * posterior = GetPosteriorFunction();
    if (!posterior) return; 
 
-   // try to reduce some error messages
-   posterior->setEvalErrorLoggingMode(RooAbsReal::CountErrors);
 
    TF1 * tmp = posterior->asTF(fPOI); 
    assert(tmp != 0);
diff --git a/roofit/roostats/src/BernsteinCorrection.cxx b/roofit/roostats/src/BernsteinCorrection.cxx
index 3afcd13..634d1e5 100644
--- a/roofit/roostats/src/BernsteinCorrection.cxx
+++ b/roofit/roostats/src/BernsteinCorrection.cxx
@@ -1,4 +1,4 @@
-// @(#)root/roostats:$Id: BernsteinCorrection.cxx 44171 2012-05-08 10:19:13Z moneta $
+// @(#)root/roostats:$Id: BernsteinCorrection.cxx 44368 2012-05-30 15:38:44Z axel $
 // Author: Kyle Cranmer   28/07/2008
 
 /*************************************************************************
@@ -79,6 +79,7 @@ ClassImp(RooStats::BernsteinCorrection) ;
 
 using namespace RooFit;
 using namespace RooStats;
+using namespace std;
 
 //____________________________________
 BernsteinCorrection::BernsteinCorrection(Double_t tolerance):
diff --git a/roofit/roostats/src/ConfidenceBelt.cxx b/roofit/roostats/src/ConfidenceBelt.cxx
index 2d1b03d..7b2c20b 100644
--- a/roofit/roostats/src/ConfidenceBelt.cxx
+++ b/roofit/roostats/src/ConfidenceBelt.cxx
@@ -1,4 +1,4 @@
-// @(#)root/roostats:$Id: ConfidenceBelt.cxx 44034 2012-04-30 14:54:15Z moneta $
+// @(#)root/roostats:$Id: ConfidenceBelt.cxx 44368 2012-05-30 15:38:44Z axel $
 // Author: Kyle Cranmer, Lorenzo Moneta, Gregory Schott, Wouter Verkerke
 /*************************************************************************
  * Copyright (C) 1995-2008, Rene Brun and Fons Rademakers.               *
@@ -11,7 +11,7 @@
 /*****************************************************************************
  * Project: RooStats
  * Package: RooFit/RooStats  
- * @(#)root/roofit/roostats:$Id: ConfidenceBelt.cxx 44034 2012-04-30 14:54:15Z moneta $
+ * @(#)root/roofit/roostats:$Id: ConfidenceBelt.cxx 44368 2012-05-30 15:38:44Z axel $
  * Original Author: Kyle Cranmer
  *   Kyle Cranmer, Lorenzo Moneta, Gregory Schott, Wouter Verkerke
  *
@@ -44,6 +44,7 @@
 ClassImp(RooStats::ConfidenceBelt) ;
 
 using namespace RooStats;
+using namespace std;
 
 //____________________________________________________________________
 ConfidenceBelt::ConfidenceBelt() : 
diff --git a/roofit/roostats/src/DetailedOutputAggregator.cxx b/roofit/roostats/src/DetailedOutputAggregator.cxx
new file mode 100644
index 0000000..33d17c6
--- /dev/null
+++ b/roofit/roostats/src/DetailedOutputAggregator.cxx
@@ -0,0 +1,151 @@
+// @(#)root/roostats:$Id: DetailedOutputAggregator.cxx 44482 2012-06-02 10:10:40Z moneta $
+// Author: Sven Kreiss, Kyle Cranmer, Lorenzo Moneta  Nov 2010
+/*************************************************************************
+ * Copyright (C) 1995-2008, Rene Brun and Fons Rademakers.               *
+ * All rights reserved.                                                  *
+ *                                                                       *
+ * For the licensing terms see $ROOTSYS/LICENSE.                         *
+ * For the list of contributors see $ROOTSYS/README/CREDITS.             *
+ *************************************************************************/
+
+// implementation file of DetailedOutputAggregator
+
+#include <limits>
+
+
+#include "RooFitResult.h"
+#include "RooPullVar.h"
+#include "RooRealVar.h"
+#include "RooDataSet.h"
+
+#include "RooStats/DetailedOutputAggregator.h"
+
+namespace RooStats {
+
+   DetailedOutputAggregator::~DetailedOutputAggregator() {
+      // destructor
+      if (fResult != NULL) delete fResult;
+      if (fBuiltSet != NULL) delete fBuiltSet;
+   }
+
+
+   RooArgSet * DetailedOutputAggregator::GetAsArgSet(RooFitResult *result, TString prefix, bool withErrorsAndPulls) {
+      // static function to translate the given fit result to a RooArgSet in a generic way.
+      // Prefix is prepended to all variable names.
+      RooArgSet *detailedOutput = new RooArgSet;
+      const RooArgList &detOut = result->floatParsFinal();
+      const RooArgList &truthSet = result->floatParsInit();
+      TIterator *it = detOut.createIterator();
+      while(RooAbsArg* v = dynamic_cast<RooAbsArg*>(it->Next())) {
+         RooAbsArg* clone = v->cloneTree(TString().Append(prefix).Append(v->GetName()));
+         clone->SetTitle( TString().Append(prefix).Append(v->GetTitle()) );
+         RooRealVar* var = dynamic_cast<RooRealVar*>(v);
+         if (var) clone->setAttribute("StoreError");
+         detailedOutput->addOwned(*clone);
+         
+         if( withErrorsAndPulls && var ) {
+            clone->setAttribute("StoreAsymError");
+
+            TString pullname = TString().Append(prefix).Append(TString::Format("%s_pull", var->GetName()));
+            //             TString pulldesc = TString::Format("%s pull for fit %u", var->GetTitle(), fitNumber);
+            RooRealVar* truth = dynamic_cast<RooRealVar*>(truthSet.find(var->GetName()));
+            RooPullVar pulltemp("temppull", "temppull", *var, *truth);
+            RooRealVar* pull = new RooRealVar(pullname, pullname, pulltemp.getVal());
+            detailedOutput->addOwned(*pull);
+         }
+      }
+      delete it;
+
+      // monitor a few more variables
+      detailedOutput->addOwned( *new RooRealVar(TString().Append(prefix).Append("minNLL"), TString().Append(prefix).Append("minNLL"), result->minNll() ) );
+      detailedOutput->addOwned( *new RooRealVar(TString().Append(prefix).Append("fitStatus"), TString().Append(prefix).Append("fitStatus"), result->status() ) );
+      detailedOutput->addOwned( *new RooRealVar(TString().Append(prefix).Append("covQual"), TString().Append(prefix).Append("covQual"), result->covQual() ) );
+      detailedOutput->addOwned( *new RooRealVar(TString().Append(prefix).Append("numInvalidNLLEval"), TString().Append(prefix).Append("numInvalidNLLEval"), result->numInvalidNLL() ) );
+      return detailedOutput;
+   }
+
+   void DetailedOutputAggregator::AppendArgSet(const RooAbsCollection *aset, TString prefix) {
+      // For each variable in aset, prepend prefix to its name and add
+      // to the internal store. Note this will not appear in the produced
+      // dataset unless CommitSet is called.
+
+      if (aset == NULL) {
+         // silently ignore
+         //std::cout << "Attempted to append NULL" << endl;
+         return;
+      }
+      if (fBuiltSet == NULL) {
+         fBuiltSet = new RooArgList();
+      }
+      TIterator* iter = aset->createIterator();
+      while(RooAbsArg* v = dynamic_cast<RooAbsArg*>( iter->Next() ) ) {
+         TString renamed(TString::Format("%s%s", prefix.Data(), v->GetName()));
+         if (fResult == NULL) {
+            // we never commited, so by default all columns are expected to not exist
+            RooAbsArg* var = v->createFundamental();
+            assert(var != NULL);
+            (RooArgSet(*var)) = RooArgSet(*v);
+            var->SetName(renamed);
+            if (RooRealVar* rvar= dynamic_cast<RooRealVar*>(var)) {
+               if (v->getAttribute("StoreError"))     var->setAttribute("StoreError");
+               else rvar->removeError();
+               if (v->getAttribute("StoreAsymError")) var->setAttribute("StoreAsymError");
+               else rvar->removeAsymError();
+            }
+            if (fBuiltSet->addOwned(*var)) continue;  // OK - can skip past setting value
+         }
+         if (RooAbsArg* var = fBuiltSet->find(renamed)) {
+            // we already commited an argset once, so we expect all columns to already be in the set
+            var->SetName(v->GetName());
+            (RooArgSet(*var)) = RooArgSet(*v); // copy values and errors
+            var->SetName(renamed);
+         }
+      }
+      delete iter;
+   }
+
+   // Commit to the result RooDataSet.
+   void DetailedOutputAggregator::CommitSet(double weight) {
+      if (fResult == NULL) {
+         // Store dataset as a tree - problem with VectorStore and StoreError (bug #94908)
+         RooAbsData::StorageType defStore= RooAbsData::getDefaultStorageType();
+         RooAbsData::setDefaultStorageType(RooAbsData::Tree);
+         RooRealVar wgt("weight","weight",1.0);
+         fResult = new RooDataSet("", "", RooArgSet(*fBuiltSet,wgt), RooFit::WeightVar(wgt));
+         RooAbsData::setDefaultStorageType(defStore);
+      }
+      fResult->add(RooArgSet(*fBuiltSet), weight);
+      TIterator* iter = fBuiltSet->createIterator();
+      while(RooAbsArg* v = dynamic_cast<RooAbsArg*>( iter->Next() ) ) {
+         if (RooRealVar* var= dynamic_cast<RooRealVar*>(v)) {
+            // Invalidate values in case we don't set some of them next time round (eg. if fit not done)
+            var->setVal(std::numeric_limits<Double_t>::quiet_NaN());
+            var->removeError();
+            var->removeAsymError();
+         }
+      }
+      delete iter;
+   }
+
+
+   RooDataSet * DetailedOutputAggregator::GetAsDataSet(TString name, TString title) {
+      // Returns all detailed output as a dataset.
+      // Ownership of the dataset is transferred to the caller.
+      RooDataSet* temp = NULL;
+      if( fResult ) {
+         temp = fResult;
+         fResult = NULL;   // we no longer own the dataset
+         temp->SetNameTitle( name.Data(), title.Data() );
+      }else{
+         RooRealVar wgt("weight","weight",1.0);
+         temp = new RooDataSet(name.Data(), title.Data(), RooArgSet(wgt), RooFit::WeightVar(wgt));
+      }
+      delete fBuiltSet;
+      fBuiltSet = NULL;
+
+      return temp;
+   }
+
+
+}  // end namespace RooStats
+
diff --git a/roofit/roostats/src/FeldmanCousins.cxx b/roofit/roostats/src/FeldmanCousins.cxx
index eb48dfb..ff017e0 100644
--- a/roofit/roostats/src/FeldmanCousins.cxx
+++ b/roofit/roostats/src/FeldmanCousins.cxx
@@ -1,4 +1,4 @@
-// @(#)root/roostats:$Id: FeldmanCousins.cxx 38599 2011-03-24 08:37:05Z moneta $
+// @(#)root/roostats:$Id: FeldmanCousins.cxx 44368 2012-05-30 15:38:44Z axel $
 // Author: Kyle Cranmer   January 2009
 
 /*************************************************************************
@@ -60,6 +60,7 @@ ClassImp(RooStats::FeldmanCousins) ;
 
 using namespace RooFit;
 using namespace RooStats;
+using namespace std;
 
 
 /*
diff --git a/roofit/roostats/src/FrequentistCalculator.cxx b/roofit/roostats/src/FrequentistCalculator.cxx
index b5b095e..8da2c75 100644
--- a/roofit/roostats/src/FrequentistCalculator.cxx
+++ b/roofit/roostats/src/FrequentistCalculator.cxx
@@ -22,6 +22,7 @@ MLEs.
 ClassImp(RooStats::FrequentistCalculator)
 
 using namespace RooStats;
+using namespace std;
 
 void FrequentistCalculator::PreHook() const {
    if (fFitInfo != NULL) {
diff --git a/roofit/roostats/src/HLFactory.cxx b/roofit/roostats/src/HLFactory.cxx
index 8734985..5c4becc 100644
--- a/roofit/roostats/src/HLFactory.cxx
+++ b/roofit/roostats/src/HLFactory.cxx
@@ -1,4 +1,4 @@
-// @(#)root/roostats:$Id: HLFactory.cxx 44171 2012-05-08 10:19:13Z moneta $
+// @(#)root/roostats:$Id: HLFactory.cxx 44269 2012-05-16 12:53:49Z moneta $
 // Author: Danilo Piparo   25/08/2009
 
 
@@ -318,13 +318,15 @@ RooDataSet* HLFactory::GetTotDataSet(){
     while ((obj = it->Next())){
         ostring=(TObjString*) obj;
         catindex++;
-        RooDataSet* dummy = new RooDataSet(*(RooDataSet*)fWs->data(ostring->String()),"");
+        RooDataSet * data = (RooDataSet*)fWs->data(ostring->String());
+        if (!data) return NULL;
+        RooDataSet* dummy = new RooDataSet(*data,"");
         fComboCat->setIndex(catindex);
         fComboCat->Print();
         dummy->addColumn(*fComboCat);
         fComboDataset->append(*dummy);
         delete dummy;
-        }
+    }
 
     delete it;
     return fComboDataset;
diff --git a/roofit/roostats/src/HybridCalculator.cxx b/roofit/roostats/src/HybridCalculator.cxx
index fd89718..4aeee2f 100644
--- a/roofit/roostats/src/HybridCalculator.cxx
+++ b/roofit/roostats/src/HybridCalculator.cxx
@@ -1,4 +1,4 @@
-// @(#)root/roostats:$Id: HybridCalculator.cxx 43199 2012-03-01 20:17:42Z moneta $
+// @(#)root/roostats:$Id: HybridCalculator.cxx 44368 2012-05-30 15:38:44Z axel $
 // Author: Kyle Cranmer, Sven Kreiss   23/05/10
 /*************************************************************************
  * Copyright (C) 1995-2008, Rene Brun and Fons Rademakers.               *
@@ -19,6 +19,7 @@ Same purpose as HybridCalculatorOriginal, but different implementation.
 ClassImp(RooStats::HybridCalculator)
 
 using namespace RooStats;
+using namespace std;
 
 
 
diff --git a/roofit/roostats/src/HypoTestCalculatorGeneric.cxx b/roofit/roostats/src/HypoTestCalculatorGeneric.cxx
index ecb3930..5851864 100644
--- a/roofit/roostats/src/HypoTestCalculatorGeneric.cxx
+++ b/roofit/roostats/src/HypoTestCalculatorGeneric.cxx
@@ -26,7 +26,7 @@ ToyMCSampler as its TestStatSampler.
 ClassImp(RooStats::HypoTestCalculatorGeneric)
 
 using namespace RooStats;
-
+using namespace std;
 
 //___________________________________
 HypoTestCalculatorGeneric::HypoTestCalculatorGeneric(
@@ -132,10 +132,15 @@ HypoTestResult* HypoTestCalculatorGeneric::GetHypoTest() const {
    RooArgList* allTS = NULL;
    if( toymcs ) {
       allTS = toymcs->EvaluateAllTestStatistics(*const_cast<RooAbsData*>(fData), nullP);
+      if (!allTS) return 0;
       //oocoutP((TObject*)0,Generation) << "All Test Statistics on data: " << endl;
       //allTS->Print("v");
       RooRealVar* firstTS = (RooRealVar*)allTS->at(0);
       obsTestStat = firstTS->getVal();
+      if (allTS->getSize()<=1) {
+        delete allTS;
+        allTS= 0;  // don't save
+      }
    }else{
       obsTestStat = fTestStatSampler->EvaluateTestStatistic(*const_cast<RooAbsData*>(fData), nullP);
    }
@@ -158,7 +163,13 @@ HypoTestResult* HypoTestCalculatorGeneric::GetHypoTest() const {
    RooDataSet* detOut_null = NULL;
    if(toymcs) {
       detOut_null = toymcs->GetSamplingDistributions(paramPointNull);
-      if( detOut_null ) samp_null = new SamplingDistribution( detOut_null->GetName(), detOut_null->GetTitle(), *detOut_null );
+      if( detOut_null ) {
+        samp_null = new SamplingDistribution( detOut_null->GetName(), detOut_null->GetTitle(), *detOut_null );
+        if (detOut_null->get()->getSize()<=1) {
+          delete detOut_null;
+          detOut_null= 0;
+        }
+      }
    }else samp_null = fTestStatSampler->GetSamplingDistribution(paramPointNull);
 
    // set parameters back
@@ -174,7 +185,13 @@ HypoTestResult* HypoTestCalculatorGeneric::GetHypoTest() const {
    RooDataSet* detOut_alt = NULL;
    if(toymcs) {
       detOut_alt = toymcs->GetSamplingDistributions(paramPointAlt);
-      if( detOut_alt ) samp_alt = new SamplingDistribution( detOut_alt->GetName(), detOut_alt->GetTitle(), *detOut_alt );
+      if( detOut_alt ) {
+        samp_alt = new SamplingDistribution( detOut_alt->GetName(), detOut_alt->GetTitle(), *detOut_alt );
+        if (detOut_alt->get()->getSize()<=1) {
+          delete detOut_alt;
+          detOut_alt= 0;
+        }
+      }
    }else samp_alt = fTestStatSampler->GetSamplingDistribution(paramPointAlt);
 
 
@@ -197,6 +214,7 @@ HypoTestResult* HypoTestCalculatorGeneric::GetHypoTest() const {
    }
 
    *bothParams = *saveAll;
+   delete allTS;
    delete bothParams;
    delete saveAll;
    delete altParams;
diff --git a/roofit/roostats/src/HypoTestInverter.cxx b/roofit/roostats/src/HypoTestInverter.cxx
index 9d85c87..2e867c0 100644
--- a/roofit/roostats/src/HypoTestInverter.cxx
+++ b/roofit/roostats/src/HypoTestInverter.cxx
@@ -1,4 +1,4 @@
-// @(#)root/roostats:$Id: HypoTestInverter.cxx 44126 2012-05-04 16:55:47Z moneta $
+// @(#)root/roostats:$Id: HypoTestInverter.cxx 44368 2012-05-30 15:38:44Z axel $
 // Author: Kyle Cranmer, Lorenzo Moneta, Gregory Schott, Wouter Verkerke
 /*************************************************************************
  * Copyright (C) 1995-2008, Rene Brun and Fons Rademakers.               *
@@ -62,6 +62,7 @@ The class can scan the CLs+b values or alternativly CLs (if the method HypoTestI
 ClassImp(RooStats::HypoTestInverter)
 
 using namespace RooStats;
+using namespace std;
 
 // static variable definitions
 double HypoTestInverter::fgCLAccuracy = 0.005;
diff --git a/roofit/roostats/src/HypoTestInverterOriginal.cxx b/roofit/roostats/src/HypoTestInverterOriginal.cxx
index 6b4d7af..5a245d5 100644
--- a/roofit/roostats/src/HypoTestInverterOriginal.cxx
+++ b/roofit/roostats/src/HypoTestInverterOriginal.cxx
@@ -1,4 +1,4 @@
-// @(#)root/roostats:$Id: HypoTestInverterOriginal.cxx 43683 2012-04-10 16:46:02Z pcanal $
+// @(#)root/roostats:$Id: HypoTestInverterOriginal.cxx 44368 2012-05-30 15:38:44Z axel $
 // Author: Kyle Cranmer, Lorenzo Moneta, Gregory Schott, Wouter Verkerke
 /*************************************************************************
  * Copyright (C) 1995-2008, Rene Brun and Fons Rademakers.               *
@@ -41,6 +41,7 @@ The class can scan the CLs+b values or alternativly CLs (if the method HypoTestI
 ClassImp(RooStats::HypoTestInverterOriginal)
 
 using namespace RooStats;
+using namespace std;
 
 
 HypoTestInverterOriginal::HypoTestInverterOriginal( ) :
diff --git a/roofit/roostats/src/HypoTestInverterResult.cxx b/roofit/roostats/src/HypoTestInverterResult.cxx
index d1d5ca4..cfcf364 100644
--- a/roofit/roostats/src/HypoTestInverterResult.cxx
+++ b/roofit/roostats/src/HypoTestInverterResult.cxx
@@ -1,4 +1,4 @@
-// @(#)root/roostats:$Id: HypoTestInverterResult.cxx 44171 2012-05-08 10:19:13Z moneta $
+// @(#)root/roostats:$Id: HypoTestInverterResult.cxx 44368 2012-05-30 15:38:44Z axel $
 // Author: Kyle Cranmer, Lorenzo Moneta, Gregory Schott, Wouter Verkerke
 /*************************************************************************
  * Copyright (C) 1995-2008, Rene Brun and Fons Rademakers.               *
@@ -41,6 +41,7 @@ ClassImp(RooStats::HypoTestInverterResult)
 
 using namespace RooStats;
 using namespace RooFit;
+using namespace std;
 
 
 // initialize static value 
diff --git a/roofit/roostats/src/HypoTestPlot.cxx b/roofit/roostats/src/HypoTestPlot.cxx
index 215891f..8d6be44 100644
--- a/roofit/roostats/src/HypoTestPlot.cxx
+++ b/roofit/roostats/src/HypoTestPlot.cxx
@@ -1,4 +1,4 @@
-// @(#)root/roostats:$Id: HypoTestPlot.cxx 43068 2012-02-21 16:09:05Z moneta $
+// @(#)root/roostats:$Id: HypoTestPlot.cxx 44368 2012-05-30 15:38:44Z axel $
 // Author: Sven Kreiss   June 2010
 /*************************************************************************
  * Copyright (C) 1995-2008, Rene Brun and Fons Rademakers.               *
@@ -16,12 +16,12 @@
 
 
 #include "RooStats/HypoTestPlot.h"
-
+#include "TStyle.h"
 
 ClassImp(RooStats::HypoTestPlot)
 
 using namespace RooStats;
-#include "TStyle.h"
+using namespace std;
 
 HypoTestPlot::HypoTestPlot(HypoTestResult& result, Int_t bins, Option_t* opt) :
    SamplingDistPlot(bins),
diff --git a/roofit/roostats/src/HypoTestResult.cxx b/roofit/roostats/src/HypoTestResult.cxx
index f271ab3..d35145b 100644
--- a/roofit/roostats/src/HypoTestResult.cxx
+++ b/roofit/roostats/src/HypoTestResult.cxx
@@ -1,4 +1,4 @@
-// @(#)root/roostats:$Id: HypoTestResult.cxx 44157 2012-05-07 16:41:44Z moneta $
+// @(#)root/roostats:$Id: HypoTestResult.cxx 44473 2012-06-01 16:12:31Z moneta $
 // Author: Kyle Cranmer, Lorenzo Moneta, Gregory Schott, Wouter Verkerke, Sven Kreiss
 /*************************************************************************
  * Copyright (C) 1995-2008, Rene Brun and Fons Rademakers.               *
@@ -11,7 +11,7 @@
 /*****************************************************************************
  * Project: RooStats
  * Package: RooFit/RooStats  
- * @(#)root/roofit/roostats:$Id: HypoTestResult.cxx 44157 2012-05-07 16:41:44Z moneta $
+ * @(#)root/roofit/roostats:$Id: HypoTestResult.cxx 44473 2012-06-01 16:12:31Z moneta $
  * Authors:                     
  *   Kyle Cranmer, Lorenzo Moneta, Gregory Schott, Wouter Verkerke, Sven Kreiss
  *
@@ -50,6 +50,7 @@ END_HTML
 ClassImp(RooStats::HypoTestResult) ;
 
 using namespace RooStats;
+using namespace std;
 
 
 //____________________________________________________________________
@@ -113,6 +114,35 @@ HypoTestResult::~HypoTestResult()
    if( fAllTestStatisticsData ) delete fAllTestStatisticsData;
 }
 
+//____________________________________________________________________
+HypoTestResult & HypoTestResult::operator=(const HypoTestResult& other) { 
+   // assignment operator
+
+   if (this == &other) return *this;
+   SetName(other.GetName());
+   SetTitle(other.GetTitle());
+   fNullPValue = other.fNullPValue; 
+   fAlternatePValue = other.fAlternatePValue; 
+   fNullPValueError = other.fNullPValueError;
+   fAlternatePValueError = other.fAlternatePValueError;
+   fTestStatisticData = other.fTestStatisticData;
+
+   if( fAllTestStatisticsData ) delete fAllTestStatisticsData;
+   fAllTestStatisticsData = NULL;
+   if( fNullDistr ) delete fNullDistr; fNullDistr = NULL;
+   if( fAltDistr ) delete fAltDistr; fAltDistr = NULL;   
+   if( fNullDetailedOutput ) delete fNullDetailedOutput; fNullDetailedOutput = NULL;
+   if( fAltDetailedOutput ) delete fAltDetailedOutput;  fAltDetailedOutput = NULL;
+   if (fFitInfo) delete fFitInfo; fFitInfo = NULL;
+   
+   fPValueIsRightTail =  other.GetPValueIsRightTail();
+   fBackgroundIsAlt = other.GetBackGroundIsAlt();
+
+   this->Append( &other );
+
+   return *this; 
+}
+
 
 void HypoTestResult::Append(const HypoTestResult* other) {
    // Add additional toy-MC experiments to the current results.
@@ -218,6 +248,11 @@ Double_t HypoTestResult::CLsplusbError() const {
    return fBackgroundIsAlt ? fNullPValueError : fAlternatePValueError;
 }
 
+//____________________________________________________________________
+Double_t HypoTestResult::SignificanceError() const {
+   // Taylor expansion series approximation for standard deviation (error propagation)
+   return NullPValueError() / ROOT::Math::normal_pdf(Significance());
+}
 
 //____________________________________________________________________
 Double_t HypoTestResult::CLsError() const {
@@ -274,26 +309,28 @@ void HypoTestResult::Print(Option_t * ) const
    
    bool fromToys = (fAltDistr || fNullDistr);
    
-   cout << endl << "Results " << GetName() << ": " << endl;
-   cout << " - Null p-value = " << NullPValue(); 
-   if (fromToys) cout << " +/- " << NullPValueError();
-   cout << endl;
-   cout << " - Significance = " << Significance() << " sigma" << endl;
+   std::cout << std::endl << "Results " << GetName() << ": " << endl;
+   std::cout << " - Null p-value = " << NullPValue(); 
+   if (fromToys) std::cout << " +/- " << NullPValueError();
+   std::cout << std::endl;
+   std::cout << " - Significance = " << Significance();
+   if (fromToys) std::cout << " +/- " << SignificanceError() << " sigma";
+   std::cout << std::endl;
    if(fAltDistr)
-      cout << " - Number of Alt toys: " << fAltDistr->GetSize() << std::endl;
+      std::cout << " - Number of Alt toys: " << fAltDistr->GetSize() << std::endl;
    if(fNullDistr)
-      cout << " - Number of Null toys: " << fNullDistr->GetSize() << std::endl;
+      std::cout << " - Number of Null toys: " << fNullDistr->GetSize() << std::endl;
    
-   if (HasTestStatisticData() ) cout << " - Test statistic evaluated on data: " << fTestStatisticData << std::endl;
-   cout << " - CL_b: " << CLb();
-   if (fromToys) cout << " +/- " << CLbError();
-   cout << std::endl;
-   cout << " - CL_s+b: " << CLsplusb();
-   if (fromToys) cout << " +/- " << CLsplusbError();
-   cout << std::endl;
-   cout << " - CL_s: " << CLs();
-   if (fromToys) cout << " +/- " << CLsError();
-   cout << std::endl;
+   if (HasTestStatisticData() ) std::cout << " - Test statistic evaluated on data: " << fTestStatisticData << std::endl;
+   std::cout << " - CL_b: " << CLb();
+   if (fromToys) std::cout << " +/- " << CLbError();
+   std::cout << std::endl;
+   std::cout << " - CL_s+b: " << CLsplusb();
+   if (fromToys) std::cout << " +/- " << CLsplusbError();
+   std::cout << std::endl;
+   std::cout << " - CL_s: " << CLs();
+   if (fromToys) std::cout << " +/- " << CLsError();
+   std::cout << std::endl;
    
    return;
 }
diff --git a/roofit/roostats/src/LikelihoodInterval.cxx b/roofit/roostats/src/LikelihoodInterval.cxx
index da078d9..931b71e 100644
--- a/roofit/roostats/src/LikelihoodInterval.cxx
+++ b/roofit/roostats/src/LikelihoodInterval.cxx
@@ -1,4 +1,4 @@
-// @(#)root/roostats:$Id: LikelihoodInterval.cxx 37928 2011-02-01 16:03:58Z moneta $
+// @(#)root/roostats:$Id: LikelihoodInterval.cxx 44368 2012-05-30 15:38:44Z axel $
 // Author: Kyle Cranmer, Lorenzo Moneta, Gregory Schott, Wouter Verkerke
 /*************************************************************************
  * Copyright (C) 1995-2008, Rene Brun and Fons Rademakers.               *
@@ -11,7 +11,7 @@
 /*****************************************************************************
  * Project: RooStats
  * Package: RooFit/RooStats  
- * @(#)root/roofit/roostats:$Id: LikelihoodInterval.cxx 37928 2011-02-01 16:03:58Z moneta $
+ * @(#)root/roofit/roostats:$Id: LikelihoodInterval.cxx 44368 2012-05-30 15:38:44Z axel $
  * Authors:                     
  *   Kyle Cranmer, Lorenzo Moneta, Gregory Schott, Wouter Verkerke
  *
@@ -81,6 +81,7 @@ END_HTML
 ClassImp(RooStats::LikelihoodInterval) ;
 
 using namespace RooStats;
+using namespace std;
 
 
 //____________________________________________________________________
diff --git a/roofit/roostats/src/MCMCCalculator.cxx b/roofit/roostats/src/MCMCCalculator.cxx
index 69c0ef9..fff3c82 100644
--- a/roofit/roostats/src/MCMCCalculator.cxx
+++ b/roofit/roostats/src/MCMCCalculator.cxx
@@ -1,4 +1,4 @@
-// @(#)root/roostats:$Id: MCMCCalculator.cxx 40959 2011-09-20 16:33:21Z moneta $
+// @(#)root/roostats:$Id: MCMCCalculator.cxx 44368 2012-05-30 15:38:44Z axel $
 // Authors: Kevin Belasco        17/06/2009
 // Authors: Kyle Cranmer         17/06/2009
 /*************************************************************************
@@ -82,6 +82,7 @@ ClassImp(RooStats::MCMCCalculator);
 
 using namespace RooFit;
 using namespace RooStats;
+using namespace std;
 
 // default constructor
 MCMCCalculator::MCMCCalculator() : 
diff --git a/roofit/roostats/src/MetropolisHastings.cxx b/roofit/roostats/src/MetropolisHastings.cxx
index 9113033..3a2f5c8 100644
--- a/roofit/roostats/src/MetropolisHastings.cxx
+++ b/roofit/roostats/src/MetropolisHastings.cxx
@@ -1,4 +1,4 @@
-// @(#)root/roostats:$Id: MetropolisHastings.cxx 44140 2012-05-06 20:04:25Z moneta $
+// @(#)root/roostats:$Id: MetropolisHastings.cxx 44368 2012-05-30 15:38:44Z axel $
 // Authors: Kevin Belasco        17/06/2009
 // Authors: Kyle Cranmer         17/06/2009
 /*************************************************************************
@@ -98,6 +98,7 @@ ClassImp(RooStats::MetropolisHastings);
 
 using namespace RooFit;
 using namespace RooStats;
+using namespace std;
 
 MetropolisHastings::MetropolisHastings()
 {
@@ -160,8 +161,12 @@ MarkovChain* MetropolisHastings::ConstructChain()
 
    // We will need to check if log-likelihood evaluation left an error status.
    // Now using faster eval error logging with CountErrors.
-   if (fType == kLog)
-     fFunction->setEvalErrorLoggingMode(RooAbsReal::CountErrors);
+   if (fType == kLog) {
+     RooAbsReal::setEvalErrorLoggingMode(RooAbsReal::CountErrors);
+     //N.B: need to clear the count in case of previous errors !
+     // the clear needs also to be done after calling setEvalErrorLoggingMode 
+     RooAbsReal::clearEvalErrorLog();
+   }
 
    bool hadEvalError = true;
 
@@ -179,8 +184,8 @@ MarkovChain* MetropolisHastings::ConstructChain()
       xL = fFunction->getVal();
 
       if (fType == kLog) {
-         if (fFunction->numEvalErrors() > 0) {
-            fFunction->clearEvalErrorLog();
+         if (RooAbsReal::numEvalErrors() > 0) {
+            RooAbsReal::clearEvalErrorLog();
             hadEvalError = true;
          } else
             hadEvalError = false;
diff --git a/roofit/roostats/src/ModelConfig.cxx b/roofit/roostats/src/ModelConfig.cxx
index eb997ee..6b9510d 100644
--- a/roofit/roostats/src/ModelConfig.cxx
+++ b/roofit/roostats/src/ModelConfig.cxx
@@ -1,4 +1,4 @@
-// @(#)root/roostats:$Id: ModelConfig.cxx 40899 2011-09-16 09:28:50Z moneta $
+// @(#)root/roostats:$Id: ModelConfig.cxx 44368 2012-05-30 15:38:44Z axel $
 // Author: Kyle Cranmer, Lorenzo Moneta, Gregory Schott, Wouter Verkerke, Sven Kreiss
 /*************************************************************************
  * Copyright (C) 1995-2008, Rene Brun and Fons Rademakers.               *
@@ -25,6 +25,7 @@
 
 ClassImp(RooStats::ModelConfig)
 
+using namespace std;
 
 namespace RooStats {
 
diff --git a/roofit/roostats/src/NeymanConstruction.cxx b/roofit/roostats/src/NeymanConstruction.cxx
index 04169ef..d55c3b7 100644
--- a/roofit/roostats/src/NeymanConstruction.cxx
+++ b/roofit/roostats/src/NeymanConstruction.cxx
@@ -1,4 +1,4 @@
-// @(#)root/roostats:$Id: NeymanConstruction.cxx 44034 2012-04-30 14:54:15Z moneta $
+// @(#)root/roostats:$Id: NeymanConstruction.cxx 44368 2012-05-30 15:38:44Z axel $
 // Author: Kyle Cranmer   January 2009
 
 /*************************************************************************
@@ -73,6 +73,7 @@ ClassImp(RooStats::NeymanConstruction) ;
 
 using namespace RooFit;
 using namespace RooStats;
+using namespace std;
 
 
 //_______________________________________________________
diff --git a/roofit/roostats/src/NumberCountingPdfFactory.cxx b/roofit/roostats/src/NumberCountingPdfFactory.cxx
index ede078e..b3d436d 100644
--- a/roofit/roostats/src/NumberCountingPdfFactory.cxx
+++ b/roofit/roostats/src/NumberCountingPdfFactory.cxx
@@ -1,4 +1,4 @@
-// @(#)root/roostats:$Id: NumberCountingPdfFactory.cxx 43992 2012-04-27 16:11:41Z moneta $
+// @(#)root/roostats:$Id: NumberCountingPdfFactory.cxx 44368 2012-05-30 15:38:44Z axel $
 // Author: Kyle Cranmer   28/07/2008
 
 /*************************************************************************
@@ -65,6 +65,7 @@ ClassImp(RooStats::NumberCountingPdfFactory) ;
 
 using namespace RooStats;
 using namespace RooFit;
+using namespace std;
 
 
 //_______________________________________________________
diff --git a/roofit/roostats/src/PdfProposal.cxx b/roofit/roostats/src/PdfProposal.cxx
index 2c060c0..4a7e719 100644
--- a/roofit/roostats/src/PdfProposal.cxx
+++ b/roofit/roostats/src/PdfProposal.cxx
@@ -1,4 +1,4 @@
-// @(#)root/roostats:$Id: PdfProposal.cxx 34109 2010-06-24 15:00:16Z moneta $
+// @(#)root/roostats:$Id: PdfProposal.cxx 44368 2012-05-30 15:38:44Z axel $
 // Authors: Kevin Belasco        17/06/2009
 // Authors: Kyle Cranmer         17/06/2009
 /*************************************************************************
@@ -89,6 +89,7 @@ ClassImp(RooStats::PdfProposal);
 
 using namespace RooFit;
 using namespace RooStats;
+using namespace std;
 
 // By default, PdfProposal does NOT own the PDF that serves as the
 // proposal density function
diff --git a/roofit/roostats/src/ProfileInspector.cxx b/roofit/roostats/src/ProfileInspector.cxx
index 3b5add0..0032eb4 100644
--- a/roofit/roostats/src/ProfileInspector.cxx
+++ b/roofit/roostats/src/ProfileInspector.cxx
@@ -34,6 +34,7 @@ Utility class to plot conditional MLE of nuisance parameters vs. Parameters of I
 ClassImp(RooStats::ProfileInspector);
 
 using namespace RooStats;
+using namespace std;
 
 //_______________________________________________________
 ProfileInspector::ProfileInspector()
diff --git a/roofit/roostats/src/ProfileLikelihoodTestStat.cxx b/roofit/roostats/src/ProfileLikelihoodTestStat.cxx
index 0538690..b773df2 100644
--- a/roofit/roostats/src/ProfileLikelihoodTestStat.cxx
+++ b/roofit/roostats/src/ProfileLikelihoodTestStat.cxx
@@ -1,4 +1,4 @@
-// @(#)root/roostats:$Id: ProfileLikelihoodTestStat.cxx 44171 2012-05-08 10:19:13Z moneta $
+// @(#)root/roostats:$Id: ProfileLikelihoodTestStat.cxx 44429 2012-06-01 08:10:00Z moneta $
 // Author: Kyle Cranmer, Lorenzo Moneta, Gregory Schott, Wouter Verkerke
 // Additional Contributions: Giovanni Petrucciani 
 /*************************************************************************
@@ -24,6 +24,7 @@
 
 #include "RooStats/RooStatsUtils.h"
 
+using namespace std;
 
 Bool_t RooStats::ProfileLikelihoodTestStat::fgAlwaysReuseNll = kTRUE ;
 
@@ -53,7 +54,7 @@ Double_t RooStats::ProfileLikelihoodTestStat::EvaluateProfileLikelihood(int type
        RooRealVar* firstPOI = dynamic_cast<RooRealVar*>( paramsOfInterest.first());       
        if (firstPOI) initial_mu_value = firstPOI->getVal();
        //paramsOfInterest.getRealValue(firstPOI->GetName());
-       if (fPrintLevel > 0) { 
+       if (fPrintLevel > 1) { 
             cout << "POIs: " << endl;
             paramsOfInterest.Print("v");
        }
diff --git a/roofit/roostats/src/ProposalHelper.cxx b/roofit/roostats/src/ProposalHelper.cxx
index 1c61fe6..753661b 100644
--- a/roofit/roostats/src/ProposalHelper.cxx
+++ b/roofit/roostats/src/ProposalHelper.cxx
@@ -1,4 +1,4 @@
-// @(#)root/roostats:$Id: ProposalHelper.cxx 44034 2012-04-30 14:54:15Z moneta $
+// @(#)root/roostats:$Id: ProposalHelper.cxx 44368 2012-05-30 15:38:44Z axel $
 // Authors: Kevin Belasco        7/22/2009
 // Authors: Kyle Cranmer         7/22/2009
 /*************************************************************************
@@ -71,6 +71,7 @@ ClassImp(RooStats::ProposalHelper);
 
 using namespace RooFit;
 using namespace RooStats;
+using namespace std;
 
 //static const Double_t DEFAULT_UNI_FRAC = 0.10;
 static const Double_t DEFAULT_CLUES_FRAC = 0.20;
diff --git a/roofit/roostats/src/RooStatsUtils.cxx b/roofit/roostats/src/RooStatsUtils.cxx
index 966177e..978c1c9 100644
--- a/roofit/roostats/src/RooStatsUtils.cxx
+++ b/roofit/roostats/src/RooStatsUtils.cxx
@@ -1,4 +1,4 @@
-// @(#)root/roostats:$Id: RooStatsUtils.cxx 44171 2012-05-08 10:19:13Z moneta $
+// @(#)root/roostats:$Id: RooStatsUtils.cxx 44368 2012-05-30 15:38:44Z axel $
 // Author: Kyle Cranmer   28/07/2008
 
 /*************************************************************************
@@ -28,6 +28,8 @@ NamespaceImp(RooStats)
 #include "RooStats/RooStatsUtils.h"
 #include <typeinfo>
 
+using namespace std;
+
 // this file is only for the documentation of RooStats namespace
 
 namespace RooStats { 
diff --git a/roofit/roostats/src/SPlot.cxx b/roofit/roostats/src/SPlot.cxx
index 7ffccd4..46992c0 100644
--- a/roofit/roostats/src/SPlot.cxx
+++ b/roofit/roostats/src/SPlot.cxx
@@ -1,4 +1,4 @@
-// @(#)root/roostats:$Id: SPlot.cxx 41030 2011-09-27 15:06:01Z moneta $
+// @(#)root/roostats:$Id: SPlot.cxx 44368 2012-05-30 15:38:44Z axel $
 // Author: Kyle Cranmer   28/07/2008
 
 /*************************************************************************
@@ -65,6 +65,7 @@
 ClassImp(RooStats::SPlot) ;
 
 using namespace RooStats;
+using namespace std;
 
 
 
diff --git a/roofit/roostats/src/ToyMCImportanceSampler.cxx b/roofit/roostats/src/ToyMCImportanceSampler.cxx
index abc6efc..15bb14a 100644
--- a/roofit/roostats/src/ToyMCImportanceSampler.cxx
+++ b/roofit/roostats/src/ToyMCImportanceSampler.cxx
@@ -16,8 +16,10 @@
 #endif
 
 #include "RooCategory.h"
+#include "TMath.h"
 
 using namespace RooFit;
+using namespace std;
 
 
 ClassImp(RooStats::ToyMCImportanceSampler)
@@ -74,13 +76,13 @@ RooDataSet* ToyMCImportanceSampler::GetSamplingDistributionsSingleWorker(RooArgS
       // apply strategy for how to distribute the #toys between the distributions
       if( fToysStrategy == EQUALTOYSPERDENSITY ) {
          // assuming alltoys = one null + N imp densities. And round up.
-         fNToys = ceil(  double(allToys)/(fImportanceDensities.size()+1)  ); 
+         fNToys = TMath::CeilNint(  double(allToys)/(fImportanceDensities.size()+1)  ); 
       }else if(fToysStrategy == EXPONENTIALTOYDISTRIBUTION ) {
          // for N densities, split the toys into (2^(N+1))-1 parts, and assign 2^0 parts to the first
          // density (which is the null), 2^1 to the second (first imp dens), etc, up to 2^N
-         fNToys = ceil(  double(allToys) * pow( double(2) , i+1 )  /  (pow( double(2), int(fImportanceDensities.size()+1) )-1)  );
+         fNToys = TMath::CeilNint(  double(allToys) * pow( double(2) , i+1 )  /  (pow( double(2), int(fImportanceDensities.size()+1) )-1)  );
          
-         int largestNToys = ceil(  allToys * pow( double(2), int(fImportanceDensities.size()) )  /  (pow( double(2), int(fImportanceDensities.size()+1) )-1)  );
+         int largestNToys = TMath::CeilNint(  allToys * pow( double(2), int(fImportanceDensities.size()) )  /  (pow( double(2), int(fImportanceDensities.size()+1) )-1)  );
          reweight.setVal( ((double)largestNToys) / fNToys );
       }
       
@@ -90,33 +92,36 @@ RooDataSet* ToyMCImportanceSampler::GetSamplingDistributionsSingleWorker(RooArgS
 
       RooDataSet* result = ToyMCSampler::GetSamplingDistributionsSingleWorker( paramPoint );
 
-      // add label
-      densityLabel.setIndex( i );
-      result->addColumn( densityLabel );
-      result->addColumn( reweight );
+      if (result->get()->getSize() > Int_t(fTestStatistics.size())) {
+         // add label
+         densityLabel.setIndex( i );
+         result->addColumn( densityLabel );
+         result->addColumn( reweight );
+      }
       
-      RooArgSet columns( *result->get() );
-      columns.add( *(new RooRealVar( "weight", "weight", 1.0 )) );
+      if( !fullResult ) {
+         RooArgSet columns( *result->get() );
+         RooRealVar weightVar ( "weight", "weight", 1.0 );
+         columns.add( weightVar );
 //       cout << endl << endl << "Reweighted data columns: " << endl;
 //       columns.Print("v");
 //       cout << endl;
-      RooDataSet* reweightedResult = new RooDataSet( "rewRes", "rewRes", columns, "weight" );
+         // Store dataset as a tree - problem with VectorStore and StoreError (bug #94908)
+         RooAbsData::StorageType defStore = RooAbsData::getDefaultStorageType();
+         RooAbsData::setDefaultStorageType(RooAbsData::Tree);
+         fullResult = new RooDataSet( result->GetName(), result->GetTitle(), columns, "weight" );
+         RooAbsData::setDefaultStorageType(defStore);
+      }
+
       for( int j=0; j < result->numEntries(); j++ ) {
 //          cout << "entry: " << j << endl;
 //          result->get(j)->Print();
 //          cout << "weight: " << result->weight() << endl;
 //          cout << "reweight: " << reweight.getVal() << endl;
          const RooArgSet* row = result->get(j);
-         reweightedResult->add( *row, result->weight()*reweight.getVal() );
+         fullResult->add( *row, result->weight()*reweight.getVal() );
       }
       delete result;
-      
-      if( !fullResult ) {
-         fullResult = reweightedResult;
-      }else{
-         fullResult->append( *reweightedResult );
-         delete reweightedResult;
-      }
    }
 
    // restore #toys
@@ -152,7 +157,7 @@ RooAbsData* ToyMCImportanceSampler::GenerateToyData(
    // do not do anything if the given parameter point if fNullSnapshots[0]
    // ... which is the most common case
    if( fNullSnapshots[0] != &paramPoint ) {
-      ooccoutI((TObject*)NULL,InputArguments) << "Using given parameter point. Replaces snapshot for the only null currently defined." << endl;
+      ooccoutD((TObject*)NULL,InputArguments) << "Using given parameter point. Replaces snapshot for the only null currently defined." << endl;
       if(fNullSnapshots[0]) delete fNullSnapshots[0];
       fNullSnapshots.clear();
       fNullSnapshots.push_back( (RooArgSet*)paramPoint.snapshot() );
@@ -234,8 +239,8 @@ RooAbsData* ToyMCImportanceSampler::GenerateToyData(
    // test statistics.
 
 
-   oocoutI((TObject*)0,InputArguments) << endl;
-   oocoutI((TObject*)0,InputArguments) << "GenerateToyDataImportanceSampling" << endl;
+   ooccoutD((TObject*)0,InputArguments) << endl;
+   ooccoutD((TObject*)0,InputArguments) << "GenerateToyDataImportanceSampling" << endl;
 
    if(!fObservables) {
       ooccoutE((TObject*)NULL,InputArguments) << "Observables not set." << endl;
@@ -345,7 +350,7 @@ RooAbsData* ToyMCImportanceSampler::GenerateToyData(
    // Importance Sampling: adjust weight
    // Sources: Alex Read, presentation by Michael Woodroofe
 
-   oocoutI((TObject*)0,InputArguments) << "About to create/calculate all nullNLLs." << endl;
+   ooccoutD((TObject*)0,InputArguments) << "About to create/calculate all nullNLLs." << endl;
    for( unsigned int i=0; i < fNullDensities.size(); i++ ) {
       //oocoutI((TObject*)0,InputArguments) << "Setting variables to nullSnapshot["<<i<<"]"<<endl;
       //fNullSnapshots[i]->Print("v");
@@ -365,7 +370,7 @@ RooAbsData* ToyMCImportanceSampler::GenerateToyData(
    
    
    // for each null: find minNLLVal of null and all imp densities
-   oocoutI((TObject*)0,InputArguments) << "About to find the minimum NLLs." << endl;
+   ooccoutD((TObject*)0,InputArguments) << "About to find the minimum NLLs." << endl;
    vector<double> minNLLVals;
    for( unsigned int i=0; i < nullNLLVals.size(); i++ ) minNLLVals.push_back( nullNLLVals[i] );
    
@@ -387,13 +392,13 @@ RooAbsData* ToyMCImportanceSampler::GenerateToyData(
       
       for( unsigned int j=0; j < nullNLLVals.size(); j++ ) {
          if( impNLLVals[i] < minNLLVals[j] ) minNLLVals[j] = impNLLVals[i];
-         oocoutI((TObject*)0,InputArguments) << "minNLLVals["<<j<<"]: " << minNLLVals[j] << "  nullNLLVals["<<j<<"]: " << nullNLLVals[j] << "    impNLLVals["<<i<<"]: " << impNLLVals[i] << endl;
+         ooccoutD((TObject*)0,InputArguments) << "minNLLVals["<<j<<"]: " << minNLLVals[j] << "  nullNLLVals["<<j<<"]: " << nullNLLVals[j] << "    impNLLVals["<<i<<"]: " << impNLLVals[i] << endl;
       }
    }
    
    // veto toys: this is a sort of "overlap removal" of the various distributions
    // if not vetoed: apply weight
-   oocoutI((TObject*)0,InputArguments) << "About to apply vetos and calculate weights." << endl;
+   ooccoutD((TObject*)0,InputArguments) << "About to apply vetos and calculate weights." << endl;
    for( unsigned int j=0; j < nullNLLVals.size(); j++ ) {
       if     ( fApplyVeto  &&  fGenerateFromNull  &&  minNLLVals[j] != nullNLLVals[j] ) weights[j] = 0.0;
       else if( fApplyVeto  &&  !fGenerateFromNull  &&  minNLLVals[j] != impNLLVals[fIndexGenDensity] ) weights[j] = 0.0;
@@ -404,7 +409,7 @@ RooAbsData* ToyMCImportanceSampler::GenerateToyData(
          weights[j] *= exp(minNLLVals[j] - nullNLLVals[j]);
       }
 
-      oocoutI((TObject*)0,InputArguments) << "weights["<<j<<"]: " << weights[j] << endl;
+      ooccoutD((TObject*)0,InputArguments) << "weights["<<j<<"]: " << weights[j] << endl;
    }
 
 
@@ -430,7 +435,7 @@ int ToyMCImportanceSampler::CreateImpDensitiesForOnePOIAdaptively( RooAbsPdf& pd
    
    // check whether error is trustworthy
    if( poi.getError() > 0.01  &&  poi.getError() < 5.0 ) {
-      n = poi.getVal() / (2.*nStdDevOverlap*poi.getError())  + 1; // round up
+      n = TMath::CeilNint( poi.getVal() / (2.*nStdDevOverlap*poi.getError()) ); // round up
       oocoutI((TObject*)0,InputArguments) << "Using fitFavoredMu and error to set the number of imp points" << endl;
       oocoutI((TObject*)0,InputArguments) << "muhat: " << poi.getVal() << "    optimize for distance: " << 2.*nStdDevOverlap*poi.getError() << endl;
       oocoutI((TObject*)0,InputArguments) << "n = " << n << endl;
diff --git a/roofit/roostats/src/ToyMCSampler.cxx b/roofit/roostats/src/ToyMCSampler.cxx
index beef2fe..f7773d2 100644
--- a/roofit/roostats/src/ToyMCSampler.cxx
+++ b/roofit/roostats/src/ToyMCSampler.cxx
@@ -1,4 +1,4 @@
-// @(#)root/roostats:$Id: ToyMCSampler.cxx 44157 2012-05-07 16:41:44Z moneta $
+// @(#)root/roostats:$Id: ToyMCSampler.cxx 44444 2012-06-01 09:12:33Z moneta $
 // Author: Sven Kreiss    June 2010
 // Author: Kyle Cranmer, Lorenzo Moneta, Gregory Schott, Wouter Verkerke
 /*************************************************************************
@@ -31,11 +31,13 @@
 #include "RooStats/ToyMCStudy.h"
 #include "RooStats/DetailedOutputAggregator.h"
 #include "RooSimultaneous.h"
+#include "RooCategory.h"
 
 #include "TMath.h"
 
 
 using namespace RooFit;
+using namespace std;
 
 
 ClassImp(RooStats::ToyMCSampler)
@@ -238,6 +240,40 @@ Bool_t ToyMCSampler::CheckConfig(void) {
 }
 
 
+RooArgList* ToyMCSampler::EvaluateAllTestStatistics(RooAbsData& data, const RooArgSet& poi) {
+   // Evaluate all test statistics, returning result and any detailed output.
+   // PDF parameter values are saved in case they are modified by
+   // TestStatistic::Evaluate (eg. SimpleLikelihoodRatioTestStat).
+   DetailedOutputAggregator detOutAgg;
+   const RooArgList* allTS = EvaluateAllTestStatistics(data, poi, detOutAgg);
+   if (!allTS) return 0;
+   return dynamic_cast<RooArgList*>(allTS->snapshot());
+}
+
+
+const RooArgList* ToyMCSampler::EvaluateAllTestStatistics(RooAbsData& data, const RooArgSet& poi, DetailedOutputAggregator& detOutAgg) {
+   RooArgSet *allVars = fPdf ? fPdf->getVariables() : 0;
+   RooArgSet *saveAll = allVars ? dynamic_cast<RooArgSet*>(allVars->snapshot()) : 0;
+   for( unsigned int i = 0; i < fTestStatistics.size(); i++ ) {
+      if( fTestStatistics[i] == NULL ) continue;
+      TString name( TString::Format("%s_TS%u", fSamplingDistName.c_str(), i) );
+      RooArgSet* parForTS = dynamic_cast<RooArgSet*>(poi.snapshot());
+      RooRealVar ts( name, fTestStatistics[i]->GetVarName(), fTestStatistics[i]->Evaluate( data, *parForTS ) );
+      RooArgList tset(ts);
+      detOutAgg.AppendArgSet(&tset);
+      delete parForTS;
+      if (const RooArgSet* detOut = fTestStatistics[i]->GetDetailedOutput()) {
+        name.Append("_");
+        detOutAgg.AppendArgSet(detOut, name);
+      }
+      if (saveAll) *allVars = *saveAll;  // restore values, perhaps modified by fTestStatistics[i]->Evaluate()
+   }
+   delete saveAll;
+   delete allVars;
+   return detOutAgg.GetAsArgList();
+}
+
+
 SamplingDistribution* ToyMCSampler::GetSamplingDistribution(RooArgSet& paramPointIn) {
    if(fTestStatistics.size() > 1) {
       oocoutW((TObject*)NULL, InputArguments) << "Multiple test statistics defined, but only one distribution will be returned." << endl;
@@ -252,7 +288,9 @@ SamplingDistribution* ToyMCSampler::GetSamplingDistribution(RooArgSet& paramPoin
       return NULL;
    }
    
-   return new SamplingDistribution( r->GetName(), r->GetTitle(), *r );
+   SamplingDistribution* samp = new SamplingDistribution( r->GetName(), r->GetTitle(), *r );
+   delete r;
+   return samp;
 }
 
 
@@ -307,6 +345,12 @@ RooDataSet* ToyMCSampler::GetSamplingDistributionsSingleWorker(RooArgSet& paramP
    // be used by ToyMCStudy on the workers (ie. when you explicitly want
    // a serial run although ProofConfig is present).
 
+   // Make sure the cache is clear. It is important to clear it hear, because
+   // the cache might be invalid even when just the firstPOI was changed, for which
+   // no accessor has to be called. (Fixes a bug when ToyMCSampler is
+   // used with the Neyman Construction)
+   ClearCache();
+
    CheckConfig();
 
    // important to cache the paramPoint b/c test statistic might 
@@ -318,15 +362,6 @@ RooDataSet* ToyMCSampler::GetSamplingDistributionsSingleWorker(RooArgSet& paramP
 
    DetailedOutputAggregator detOutAgg;
 
-
-   vector<TString> namesOfTSColumns;
-   RooArgSet* allVarsToBeSaved = new RooArgSet("tsValues");
-   for( unsigned int i=0; i < fTestStatistics.size(); i++ ) {
-      TString name( TString::Format("%s_TS%d", fSamplingDistName.c_str(), i) );
-      namesOfTSColumns.push_back( name );
-      allVarsToBeSaved->addOwned( *new RooRealVar(name, fTestStatistics[i]->GetVarName(), -1) );
-   }
-      
    // counts the number of toys in the limits set for adaptive sampling
    // (taking weights into account; always on first test statistic)
    Double_t toysInTails = 0.0;
@@ -353,28 +388,13 @@ RooDataSet* ToyMCSampler::GetSamplingDistributionsSingleWorker(RooArgSet& paramP
       *allVars = *fParametersForTestStat;
       
       RooAbsData* toydata = GenerateToyData(*paramPoint, weight);
-      RooArgSet* saveVarsWithGlobObsSet = (RooArgSet*)allVars->snapshot();
-      detOutAgg.AppendArgSet( fGlobalObservables, "globObs_" );
-
-      // evaluate all test statistics
-      for( unsigned int tsi = 0; tsi < fTestStatistics.size(); tsi++ ) {
-         *allVars = *saveVarsWithGlobObsSet;
-         *allVars = *fParametersForTestStat;
-         
-         // evaluate test statistic; only depends on null POI
-         RooArgSet* parForTS = (RooArgSet*)fParametersForTestStat->snapshot();
-         Double_t value = fTestStatistics[tsi]->Evaluate(*toydata, *parForTS);
-         delete parForTS;
-         allVarsToBeSaved->setRealValue( namesOfTSColumns[tsi], value );
-         
-         // get detailed output, construct name in dataset, store
-         const RooArgSet *ndetout = fTestStatistics[tsi]->GetDetailedOutput();
-         if (ndetout != NULL)
-            detOutAgg.AppendArgSet(ndetout, TString(namesOfTSColumns[tsi]).Append("_"));
-         
-         if(valueFirst < 0.0) { valueFirst = value; }
-      }
-      delete saveVarsWithGlobObsSet;      
+
+      const RooArgList* allTS = EvaluateAllTestStatistics(*toydata, *fParametersForTestStat, detOutAgg);
+      if (allTS->getSize() > Int_t(fTestStatistics.size()))
+        detOutAgg.AppendArgSet( fGlobalObservables, "globObs_" );
+      if (RooRealVar* firstTS = dynamic_cast<RooRealVar*>(allTS->first()))
+         valueFirst = firstTS->getVal();
+
       delete toydata;
 
       // check for nan
@@ -383,7 +403,6 @@ RooDataSet* ToyMCSampler::GetSamplingDistributionsSingleWorker(RooArgSet& paramP
          continue;
       }
 
-      detOutAgg.AppendArgSet(allVarsToBeSaved);
       detOutAgg.CommitSet(weight);
 
       // adaptive sampling checks
@@ -393,8 +412,6 @@ RooDataSet* ToyMCSampler::GetSamplingDistributionsSingleWorker(RooArgSet& paramP
       }
    }
 
-   delete allVarsToBeSaved;
-
    // clean up
    *allVars = *saveAll;
    delete saveAll;
@@ -410,29 +427,32 @@ void ToyMCSampler::GenerateGlobalObservables(RooAbsPdf& pdf) const {
       ooccoutE((TObject*)NULL,InputArguments) << "Global Observables not set." << endl;
       return;
    }
+   
+   
+   if (fUseMultiGen || fgAlwaysUseMultiGen) {
 
-
-   // generate one set of global observables and assign it
-   // has problem for sim pdfs
-   RooSimultaneous* simPdf = dynamic_cast<RooSimultaneous*>( &pdf );
-   if (!simPdf) {
-      RooDataSet *one = pdf.generate(*fGlobalObservables, 1);
-
-      const RooArgSet *values = one->get();
-      if (!_allVars) {
-         _allVars = pdf.getVariables();
-      }
-      *_allVars = *values;
-      delete one;
-
-   } else {
-
-      if (_pdfList.size() == 0) {
-         TIterator* citer = simPdf->indexCat().typeIterator();
-         RooCatType* tt = NULL;
-         while ((tt = (RooCatType*) citer->Next())) {
-            RooAbsPdf* pdftmp = simPdf->getPdf(tt->GetName());
-            if (pdftmp) { 
+      // generate one set of global observables and assign it
+      // has problem for sim pdfs
+      RooSimultaneous* simPdf = dynamic_cast<RooSimultaneous*>( &pdf );
+      if (!simPdf) {
+         RooDataSet *one = pdf.generate(*fGlobalObservables, 1);
+   
+         const RooArgSet *values = one->get();
+         if (!_allVars) {
+            _allVars = pdf.getVariables();
+         }
+         *_allVars = *values;
+         delete one;
+   
+      } else {
+   
+         if (_pdfList.size() == 0) {
+            RooCategory& channelCat = (RooCategory&)simPdf->indexCat();
+            int nCat = channelCat.numTypes();
+            for (int i=0; i < nCat; ++i){
+               channelCat.setIndex(i);
+               RooAbsPdf* pdftmp = simPdf->getPdf(channelCat.getLabel());
+               assert(pdftmp);
                RooArgSet* globtmp = pdftmp->getObservables(*fGlobalObservables);
                RooAbsPdf::GenSpec* gs = pdftmp->prepareMultiGen(*globtmp, NumEvents(1));
                _pdfList.push_back(pdftmp);
@@ -440,16 +460,28 @@ void ToyMCSampler::GenerateGlobalObservables(RooAbsPdf& pdf) const {
                _gsList.push_back(gs);
             }
          }
+   
+         list<RooArgSet*>::iterator oiter = _obsList.begin();
+         list<RooAbsPdf::GenSpec*>::iterator giter = _gsList.begin();
+         for (list<RooAbsPdf*>::iterator iter = _pdfList.begin(); iter != _pdfList.end(); ++iter, ++giter, ++oiter) {
+            //RooDataSet* tmp = (*iter)->generate(**oiter,1) ;
+            RooDataSet* tmp = (*iter)->generate(**giter);
+            **oiter = *tmp->get(0);
+            delete tmp;
+         }
       }
 
-      list<RooArgSet*>::iterator oiter = _obsList.begin();
-      list<RooAbsPdf::GenSpec*>::iterator giter = _gsList.begin();
-      for (list<RooAbsPdf*>::iterator iter = _pdfList.begin(); iter != _pdfList.end(); ++iter, ++giter, ++oiter) {
-         //RooDataSet* tmp = (*iter)->generate(**oiter,1) ;
-         RooDataSet* tmp = (*iter)->generate(**giter);
-         **oiter = *tmp->get(0);
-         delete tmp;
-      }
+
+   } else {
+   
+      // not using multigen for global observables
+      RooDataSet* one = pdf.generate( *fGlobalObservables, 1 );
+      const RooArgSet *values = one->get();
+      RooArgSet* allVars = pdf.getVariables();
+      *allVars = *values;
+      delete allVars;
+      delete one;
+
    }
 }
 
diff --git a/roofit/roostats/src/ToyMCStudy.cxx b/roofit/roostats/src/ToyMCStudy.cxx
index 57cdeb0..2a8ccf1 100644
--- a/roofit/roostats/src/ToyMCStudy.cxx
+++ b/roofit/roostats/src/ToyMCStudy.cxx
@@ -1,4 +1,4 @@
-// @(#)root/roostats:$Id: ToyMCStudy.cxx 44157 2012-05-07 16:41:44Z moneta $
+// @(#)root/roostats:$Id: ToyMCStudy.cxx 44368 2012-05-30 15:38:44Z axel $
 // Author: Sven Kreiss and Kyle Cranmer    June 2010
 /*************************************************************************
  * Copyright (C) 1995-2008, Rene Brun and Fons Rademakers.               *
@@ -25,6 +25,7 @@ ClassImp(RooStats::ToyMCStudy);
 
 ClassImp(RooStats::ToyMCPayload);
 
+using namespace std;
 
 
 namespace RooStats {
diff --git a/sql/oracle/inc/TOracleResult.h b/sql/oracle/inc/TOracleResult.h
index e4401af..b7b1b37 100644
--- a/sql/oracle/inc/TOracleResult.h
+++ b/sql/oracle/inc/TOracleResult.h
@@ -1,4 +1,4 @@
-// @(#)root/physics:$Id: TOracleResult.h 43276 2012-03-07 17:13:42Z pcanal $
+// @(#)root/physics:$Id: TOracleResult.h 44342 2012-05-29 15:17:27Z axel $
 // Author: Yan Liu and Shaowen Wang   23/11/04
 
 /*************************************************************************
@@ -23,15 +23,16 @@
 #include <sys/time.h>
 #endif
 #include <occi.h>
-using namespace oracle::occi;
 #ifdef CONST
 #undef CONST
 #endif
 #else
+namespace oracle { namespace occi {
 class Connection;
 class Statement;
 class ResultSet;
 class MetaData;
+   }}
 #endif
 
 class TList;
@@ -39,10 +40,10 @@ class TList;
 class TOracleResult : public TSQLResult {
 
 private:
-   Connection            *fConn;        // connection to Oracle 
-   Statement             *fStmt;        // executed statement
-   ResultSet             *fResult;      // query result (rows)
-   std::vector<MetaData> *fFieldInfo;   // info for each field in the row
+   oracle::occi::Connection*fConn;        // connection to Oracle 
+   oracle::occi::Statement *fStmt;        // executed statement
+   oracle::occi::ResultSet *fResult;      // query result (rows)
+   std::vector<oracle::occi::MetaData> *fFieldInfo;   // info for each field in the row
    Int_t                  fFieldCount;  // num of fields in resultset
    UInt_t                 fUpdateCount; // for dml query, mutual exclusive with above
    Int_t                  fResultType;  // 0 - nothing; 1 - Select; 2 - table metainfo, 3 - update counter
@@ -55,12 +56,12 @@ private:
    TOracleResult &operator=(const TOracleResult&); // Not implemented;
    
 protected:
-   void    initResultSet(Statement *stmt);
+   void    initResultSet(oracle::occi::Statement *stmt);
    void    ProducePool();
 
 public:
-   TOracleResult(Connection *conn, Statement *stmt);
-   TOracleResult(Connection *conn, const char *tableName);
+   TOracleResult(oracle::occi::Connection *conn, oracle::occi::Statement *stmt);
+   TOracleResult(oracle::occi::Connection *conn, const char *tableName);
    ~TOracleResult();
 
    void        Close(Option_t *opt="");
diff --git a/sql/oracle/inc/TOracleRow.h b/sql/oracle/inc/TOracleRow.h
index 6601493..ebabda7 100644
--- a/sql/oracle/inc/TOracleRow.h
+++ b/sql/oracle/inc/TOracleRow.h
@@ -1,4 +1,4 @@
-// @(#)root/physics:$Id: TOracleRow.h 43276 2012-03-07 17:13:42Z pcanal $
+// @(#)root/physics:$Id: TOracleRow.h 44342 2012-05-29 15:17:27Z axel $
 // Author: Yan Liu and Shaowen Wang   23/11/04
 
 /*************************************************************************
@@ -21,22 +21,23 @@
 #include <sys/time.h>
 #endif
 #include <occi.h>
-using namespace oracle::occi;
 #ifdef CONST
 #undef CONST
 #endif
 #else
+namespace oracle { namespace occi {
 class ResultSet;
 class MetaData;
+   }}
 #endif
 
 class TOracleRow : public TSQLRow {
 
 private:
-   ResultSet                *fResult;      // current result set
-   std::vector<MetaData>    *fFieldInfo;   // metadata for columns
-   Int_t                     fFieldCount;
-   char                    **fFieldsBuffer;
+   oracle::occi::ResultSet *fResult;      // current result set
+   std::vector<oracle::occi::MetaData> *fFieldInfo;   // metadata for columns
+   Int_t                    fFieldCount;
+   char                   **fFieldsBuffer;
 
    Bool_t  IsValid(Int_t field);
 
@@ -47,7 +48,8 @@ protected:
    void        GetRowData();
 
 public:
-   TOracleRow(ResultSet *rs, std::vector<MetaData> *fieldMetaData);
+   TOracleRow(oracle::occi::ResultSet *rs,
+              std::vector<oracle::occi::MetaData> *fieldMetaData);
    ~TOracleRow();
 
    void        Close(Option_t *opt="");
diff --git a/sql/oracle/inc/TOracleServer.h b/sql/oracle/inc/TOracleServer.h
index fb6cf73..5d140f7 100644
--- a/sql/oracle/inc/TOracleServer.h
+++ b/sql/oracle/inc/TOracleServer.h
@@ -1,4 +1,4 @@
-// @(#)root/physics:$Id: TOracleServer.h 29321 2009-07-03 10:42:10Z brun $
+// @(#)root/physics:$Id: TOracleServer.h 44342 2012-05-29 15:17:27Z axel $
 // Author: Yan Liu and Shaowen Wang   23/11/04
 
 /*************************************************************************
@@ -21,22 +21,22 @@
 #include <sys/time.h>
 #endif
 #include <occi.h>
-using namespace std;
-using namespace oracle::occi;
 #ifdef CONST
 #undef CONST
 #endif
 #else
+namespace oracle { namespace occi {
 class Environment;
 class Connection;
+}}
 #endif
 
 
 class TOracleServer : public TSQLServer {
 
 private:
-   Environment  *fEnv;    // environment of Oracle access
-   Connection   *fConn;   // connection to Oracle server
+   oracle::occi::Environment  *fEnv;    // environment of Oracle access
+   oracle::occi::Connection   *fConn;   // connection to Oracle server
    TString       fInfo;  // info string with Oracle version information
    
    static const char* fgDatimeFormat; //! format for converting date and time stamps into string 
diff --git a/sql/oracle/inc/TOracleStatement.h b/sql/oracle/inc/TOracleStatement.h
index ce750dd..91922a2 100644
--- a/sql/oracle/inc/TOracleStatement.h
+++ b/sql/oracle/inc/TOracleStatement.h
@@ -1,4 +1,4 @@
-// @(#)root/oracle:$Id: TOracleStatement.h 27990 2009-03-30 14:33:07Z brun $
+// @(#)root/oracle:$Id: TOracleStatement.h 44342 2012-05-29 15:17:27Z axel $
 // Author: Sergey Linev   6/02/2006
 
 /*************************************************************************
@@ -18,16 +18,17 @@
 
 #if !defined(__CINT__)
 #include <occi.h>
-using namespace oracle::occi;
 #ifdef CONST
 #undef CONST
 #endif
 #else
+namespace oracle { namespace occi {
 class Environment;
 class Connection;
 class Statement;
 class ResultSet;
 class MetaData;
+   }}
 #endif
 
 class TOracleStatement : public TSQLStatement {
@@ -40,11 +41,11 @@ protected:
       char* namebuf;
    };
 
-   Environment           *fEnv;         // enviroment 
-   Connection            *fConn;        // connection to Oracle
-   Statement             *fStmt;        // executed statement
-   ResultSet             *fResult;      // query result (rows)
-   std::vector<MetaData> *fFieldInfo;   // info for each field in the row
+   oracle::occi::Environment *fEnv;         // enviroment 
+   oracle::occi::Connection  *fConn;        // connection to Oracle
+   oracle::occi::Statement   *fStmt;        // executed statement
+   oracle::occi::ResultSet   *fResult;      // query result (rows)
+   std::vector<oracle::occi::MetaData> *fFieldInfo;   // info for each field in the row
    TBufferRec            *fBuffer;       // buffer of values and field names
    Int_t                  fBufferSize;   // size of fBuffer
    Int_t                  fNumIterations;  // size of internal statement buffer
@@ -59,7 +60,10 @@ protected:
    void        CloseBuffer();
    
 public:
-   TOracleStatement(Environment* env, Connection* conn, Statement* stmt, Int_t niter, Bool_t errout = kTRUE);
+   TOracleStatement(oracle::occi::Environment* env,
+                    oracle::occi::Connection* conn,
+                    oracle::occi::Statement* stmt,
+                    Int_t niter, Bool_t errout = kTRUE);
    virtual ~TOracleStatement();
 
    virtual void        Close(Option_t * = "");
diff --git a/sql/oracle/src/TOracleResult.cxx b/sql/oracle/src/TOracleResult.cxx
index af6d9ca..bdee9ed 100644
--- a/sql/oracle/src/TOracleResult.cxx
+++ b/sql/oracle/src/TOracleResult.cxx
@@ -1,4 +1,4 @@
-// @(#)root/oracle:$Id: TOracleResult.cxx 35211 2010-09-08 16:06:13Z pcanal $
+// @(#)root/oracle:$Id: TOracleResult.cxx 44342 2012-05-29 15:17:27Z axel $
 // Author: Yan Liu and Shaowen Wang   23/11/04
 
 /*************************************************************************
@@ -14,7 +14,7 @@
 #include "TList.h"
 
 using namespace std;
-
+using namespace oracle::occi;
 
 ClassImp(TOracleResult)
 
diff --git a/sql/oracle/src/TOracleRow.cxx b/sql/oracle/src/TOracleRow.cxx
index 43f075e..c424fea 100644
--- a/sql/oracle/src/TOracleRow.cxx
+++ b/sql/oracle/src/TOracleRow.cxx
@@ -1,4 +1,4 @@
-// @(#)root/oracle:$Id: TOracleRow.cxx 35527 2010-09-21 12:27:01Z brun $
+// @(#)root/oracle:$Id: TOracleRow.cxx 44342 2012-05-29 15:17:27Z axel $
 // Author: Yan Liu and Shaowen Wang   23/11/04
 
 /*************************************************************************
@@ -15,6 +15,10 @@
 
 ClassImp(TOracleRow);
 
+using namespace std;
+using namespace oracle::occi;
+
+
 //______________________________________________________________________________
 TOracleRow::TOracleRow(ResultSet *rs, vector<MetaData> *fieldMetaData)
 {
diff --git a/sql/oracle/src/TOracleServer.cxx b/sql/oracle/src/TOracleServer.cxx
index 25ed3aa..aef4f7a 100644
--- a/sql/oracle/src/TOracleServer.cxx
+++ b/sql/oracle/src/TOracleServer.cxx
@@ -1,4 +1,4 @@
-// @(#)root/oracle:$Id: TOracleServer.cxx 35344 2010-09-16 21:34:21Z pcanal $
+// @(#)root/oracle:$Id: TOracleServer.cxx 44342 2012-05-29 15:17:27Z axel $
 // Author: Yan Liu and Shaowen Wang   23/11/04
 
 /*************************************************************************
@@ -57,6 +57,9 @@
 
 ClassImp(TOracleServer)
 
+using namespace std;
+using namespace oracle::occi;
+
 const char* TOracleServer::fgDatimeFormat = "MM/DD/YYYY, HH24:MI:SS";
 
 
diff --git a/sql/oracle/src/TOracleStatement.cxx b/sql/oracle/src/TOracleStatement.cxx
index 2c466a0..f40f0b4 100644
--- a/sql/oracle/src/TOracleStatement.cxx
+++ b/sql/oracle/src/TOracleStatement.cxx
@@ -1,4 +1,4 @@
-// @(#)root/oracle:$Id: TOracleStatement.cxx 35983 2010-10-01 10:12:54Z pcanal $
+// @(#)root/oracle:$Id: TOracleStatement.cxx 44342 2012-05-29 15:17:27Z axel $
 // Author: Sergey Linev   6/02/2006
 
 
@@ -25,6 +25,10 @@
 
 ClassImp(TOracleStatement)
 
+using namespace std;
+using namespace oracle::occi;
+
+
 //______________________________________________________________________________
 TOracleStatement::TOracleStatement(Environment* env, Connection* conn, Statement* stmt, Int_t niter, Bool_t errout) :
    TSQLStatement(errout),
diff --git a/test/stressRooStats.cxx b/test/stressRooStats.cxx
index 2d9fda5..53fb4a1 100644
--- a/test/stressRooStats.cxx
+++ b/test/stressRooStats.cxx
@@ -5,6 +5,7 @@
 #include <string>
 #include <list>
 #include <iostream>
+#include <iomanip>
 #include <cmath>
 
 // ROOT headers
@@ -61,10 +62,10 @@ void StatusPrint(const Int_t id, const TString &title, const Int_t status, const
 }
 
 //______________________________________________________________________________
-Int_t stressRooStats(const char* refFile, Bool_t writeRef, Int_t verbose, Int_t oneTest, Bool_t dryRun, Bool_t doDump, Bool_t doTreeStore)
+Int_t stressRooStats(const char* refFile, Bool_t writeRef, Int_t verbose, Bool_t allTests, Bool_t oneTest, Int_t testNumber, Bool_t dryRun, Bool_t doDump, Bool_t doTreeStore)
 {
    // width of lines when printing test results
-   const Int_t lineWidth = 80;
+   const Int_t lineWidth = 120;
 
    // Save memory directory location
    RooUnitTest::setMemDir(gDirectory) ;
@@ -111,7 +112,7 @@ Int_t stressRooStats(const char* refFile, Bool_t writeRef, Int_t verbose, Int_t
    TStopwatch timer;
    timer.Start();
 
-   list<RooUnitTest*> testList ;
+   list<RooUnitTest*> testList;
 
    // TEST PLC CONFINT SIMPLE GAUSSIAN : Confidence Level range is (0,1)
    testList.push_back(new TestProfileLikelihoodCalculator1(fref, writeRef, verbose, 0.99999)); // boundary case CL -> 1
@@ -154,80 +155,72 @@ Int_t stressRooStats(const char* refFile, Bool_t writeRef, Int_t verbose, Int_t
    testList.push_back(new TestMCMCCalculator(fref, writeRef, verbose, 20, 25));
    testList.push_back(new TestMCMCCalculator(fref, writeRef, verbose, 15, 20, 2 * ROOT::Math::normal_cdf(2) - 1));
 
-   // TEST HYPOTEST INVERTER PRODUCT POISSON :  Observed value range is [0,40] for x=s+b and [0,120] for y=2*s*1.2^beta
+   // TEST ZBI SIGNIFICANCE
+   testList.push_back(new TestZBi(fref, writeRef, verbose));
+
+   // TEST PLC VS AC SIGNIFICANCE : Observed value range is [0,300] for on source and [0,1100] for off-source; tau has the range [0.1,5.0]
+   testList.push_back(new TestHypoTestCalculator1(fref, writeRef, verbose, 150, 100, 1.0));
+   testList.push_back(new TestHypoTestCalculator1(fref, writeRef, verbose, 200, 100, 1.0));
+   testList.push_back(new TestHypoTestCalculator1(fref, writeRef, verbose, 105, 100, 1.0));
+   testList.push_back(new TestHypoTestCalculator1(fref, writeRef, verbose, 150, 10, 0.1));
+   testList.push_back(new TestHypoTestCalculator1(fref, writeRef, verbose, 150, 400, 4.0));
+
+   // TEST HTI PRODUCT POISSON : Observed value range is [0,40] for x=s+b and [0,120] for y=2*s*1.2^beta
+   testList.push_back(new TestHypoTestInverter1(fref, writeRef, verbose, HypoTestInverter::kAsymptotic, kProfileLR, 10, 30));
+   testList.push_back(new TestHypoTestInverter1(fref, writeRef, verbose, HypoTestInverter::kAsymptotic, kProfileLR, 20, 25));
+   testList.push_back(new TestHypoTestInverter1(fref, writeRef, verbose, HypoTestInverter::kAsymptotic, kProfileLR, 15, 20, 2 * normal_cdf(2) - 1));
    testList.push_back(new TestHypoTestInverter1(fref, writeRef, verbose, HypoTestInverter::kFrequentist, kProfileLR, 10, 30));
    testList.push_back(new TestHypoTestInverter1(fref, writeRef, verbose, HypoTestInverter::kFrequentist, kProfileLR, 20, 25));
    testList.push_back(new TestHypoTestInverter1(fref, writeRef, verbose, HypoTestInverter::kFrequentist, kProfileLR, 15, 20, 2 * normal_cdf(2) - 1));
- 
-   // TEST PLC CONFINT PRODUCT POISSON : Observed value range is [0,40] for x=s+b and [0,120] for y=2*s*1.2^beta
-//   testList.push_back(new TestProfileLikelihoodCalculator3(fref, writeRef, verbose, 10, 30));
-//   testList.push_back(new TestProfileLikelihoodCalculator3(fref, writeRef, verbose, 20, 25));
-//   testList.push_back(new TestProfileLikelihoodCalculator3(fref, writeRef, verbose, 15, 20, 2 * ROOT::Math::normal_cdf(2) - 1));
+   testList.push_back(new TestHypoTestInverter1(fref, writeRef, verbose, HypoTestInverter::kHybrid, kProfileLR, 10, 30));
+   testList.push_back(new TestHypoTestInverter1(fref, writeRef, verbose, HypoTestInverter::kHybrid, kProfileLR, 20, 25));
+   testList.push_back(new TestHypoTestInverter1(fref, writeRef, verbose, HypoTestInverter::kHybrid, kProfileLR, 15, 20, 2 * normal_cdf(2) - 1));
 
-//   testList.push_back(new TestBasic101(fref, writeRef, verbose));
-//   testList.push_back(new TestHypoTestCalculator(fref, writeRef, verbose));
-//   testList.push_back(new TestHypoTestCalculator2(fref, writeRef, verbose));
-//   testList.push_back(new TestHypoTestCalculator3(fref, writeRef, verbose));
 
-/*   testList.push_back(new TestHypoTestInverter1(fref, writeRef, verbose, HypoTestInverter::kFrequentist, kProfileLR, 10, 30));
-   testList.push_back(new TestHypoTestInverter1(fref, writeRef, verbose, HypoTestInverter::kFrequentist, kProfileLR, 20, 25));
-   testList.push_back(new TestHypoTestInverter1(fref, writeRef, verbose, HypoTestInverter::kFrequentist, kProfileLR, 15, 20, 2 * normal_cdf(2) - 1));
+   //testList.push_back(new TestProfileLikelihoodCalculator4(fref, writeRef, verbose));
+   // testList.push_back(new TestHypoTestCalculator2(fref, writeRef, verbose));
+   //  testList.push_back(new TestHypoTestCalculator3(fref, writeRef, verbose));
+
+   // TEST HYPO TEST CALCULATOR
+
+
+   TString suiteType = TString::Format(" Starting S.T.R.E.S.S. %s",
+                                       allTests ? "full suite" : (oneTest ? TString::Format("test %d", testNumber).Data() : "basic suite")
+                                      );
 
-   testList.push_back(new TestHypoTestInverter1(fref, writeRef, verbose, HypoTestInverter::kFrequentist, kSimpleLR, 10, 30));
-   testList.push_back(new TestHypoTestInverter1(fref, writeRef, verbose, HypoTestInverter::kFrequentist, kSimpleLR, 20, 25));
-   testList.push_back(new TestHypoTestInverter1(fref, writeRef, verbose, HypoTestInverter::kFrequentist, kSimpleLR, 15, 20, 2 * normal_cdf(2) - 1));
-   testList.push_back(new TestHypoTestInverter1(fref, writeRef, verbose, HypoTestInverter::kFrequentist, kRatioLR, 10, 30));
-   testList.push_back(new TestHypoTestInverter1(fref, writeRef, verbose, HypoTestInverter::kFrequentist, kRatioLR, 20, 25));
-   testList.push_back(new TestHypoTestInverter1(fref, writeRef, verbose, HypoTestInverter::kFrequentist, kRatioLR, 15, 20, 2 * normal_cdf(2) - 1));
-   testList.push_back(new TestHypoTestInverter1(fref, writeRef, verbose, HypoTestInverter::kFrequentist, kMLE, 10, 30));
-   testList.push_back(new TestHypoTestInverter1(fref, writeRef, verbose, HypoTestInverter::kFrequentist, kMLE, 20, 25));
-   testList.push_back(new TestHypoTestInverter1(fref, writeRef, verbose, HypoTestInverter::kFrequentist, kMLE, 15, 20, 2 * normal_cdf(2) - 1));
-   testList.push_back(new TestHypoTestInverter1(fref, writeRef, verbose, HypoTestInverter::kFrequentist, kNEvts, 10, 30));
-   testList.push_back(new TestHypoTestInverter1(fref, writeRef, verbose, HypoTestInverter::kFrequentist, kRatioLR, 20, 25));
-   testList.push_back(new TestHypoTestInverter1(fref, writeRef, verbose, HypoTestInverter::kFrequentist, kRatioLR, 15, 20, 2 * normal_cdf(2) - 1));
-*/
-
-//   testList.push_back(new TestHypoTestInverter1(fref, writeRef, verbose, HypoTestInverter::kHybrid, kSimpleLR));
-//   testList.push_back(new TestHypoTestInverter1(fref, writeRef, verbose, HypoTestInverter::kHybrid, kRatioLR));
-//   testList.push_back(new TestHypoTestInverter1(fref, writeRef, verbose, HypoTestInverter::kHybrid, kProfileLR));
-//   testList.push_back(new TestHypoTestInverter1(fref, writeRef, verbose, HypoTestInverter::kHybrid, kProfileLROneSided));
-//   testList.push_back(new TestHypoTestInverter1(fref, writeRef, verbose, HypoTestInverter::kHybrid, kProfileLRSigned));
-//   testList.push_back(new TestHypoTestInverter1(fref, writeRef, verbose, HypoTestInverter::kHybrid, kMLE));
-//   testList.push_back(new TestHypoTestInverter1(fref, writeRef, verbose, HypoTestInverter::kHybrid, kNObs));
-//   testList.push_back(new TestHypoTestInverter2(fref, writeRef, verbose, HypoTestInverter::kFrequentist, kSimpleLR));
-//   testList.push_back(new TestHypoTestInverter2(fref, writeRef, verbose, HypoTestInverter::kFrequentist, kRatioLR));
-//   testList.push_back(new TestHypoTestInverter2(fref, writeRef, verbose, HypoTestInverter::kFrequentist, kProfileLR));
-//   testList.push_back(new TestHypoTestInverter2(fref, writeRef, verbose, HypoTestInverter::kFrequentist, kProfileLROneSided));
-//   testList.push_back(new TestHypoTestInverter2(fref, writeRef, verbose, HypoTestInverter::kFrequentist, kProfileLRSigned));
-//   testList.push_back(new TestHypoTestInverter2(fref, writeRef, verbose, HypoTestInverter::kFrequentist, kMLE));
-//   testList.push_back(new TestHypoTestInverter2(fref, writeRef, verbose, HypoTestInverter::kFrequentist, kNObs));
-
-   cout << "*" << setw(lineWidth - 2) << setfill(' ') << " Starting S.T.R.E.S.S. basic suite " << "*" << endl;
+   cout << "*" << setw(lineWidth - 3) << setfill(' ') << suiteType << " *" << endl;
    cout << setw(lineWidth) << setfill('*') << "" << endl;
 
    if (doDump) {
       TFile fdbg("stressRooStats_DEBUG.root", "RECREATE") ;
    }
 
-   gBenchmark->Start("StressRooStats");
+   gBenchmark->Start("stressRooStats");
 
-   Int_t i(1) ;
-   for (list<RooUnitTest*>::iterator iter = testList.begin() ; iter != testList.end() ; ++iter) {
-      if (oneTest < 0 || oneTest == i) {
-         if (doDump) {
-            (*iter)->setDebug(kTRUE);
+   {
+      Int_t i;
+      list<RooUnitTest*>::iterator iter;
+
+      if (oneTest && (testNumber <= 0 || (UInt_t) testNumber > testList.size())) {
+         cout << "Tests are numbered from 1 to " << testList.size() << endl;
+      } else {
+         for (iter = testList.begin(), i = 1; iter != testList.end(); iter++, i++) {
+            if (!oneTest || testNumber == i) {
+               if (doDump) {
+                  (*iter)->setDebug(kTRUE);
+               }
+               StatusPrint(i, (*iter)->GetName(), (*iter)->isTestAvailable() ? (*iter)->runTest() : -1, lineWidth);
+            }
+            delete *iter;
          }
-         StatusPrint(i, (*iter)->GetName(), (*iter)->isTestAvailable() ? (*iter)->runTest() : -1, lineWidth);
       }
-      delete *iter;
-      i++;
    }
 
    if (dryRun) {
       RooTrace::dump();
    }
 
-   gBenchmark->Stop("StressRooStats");
+   gBenchmark->Stop("stressRooStats");
 
 
    //Print table with results
@@ -252,16 +245,16 @@ Int_t stressRooStats(const char* refFile, Bool_t writeRef, Int_t verbose, Int_t
    }
 
    cout << setw(lineWidth) << setfill('*') << "" << endl;
-   gBenchmark->Print("StressFit");
+   gBenchmark->Print("stressRooStats");
 #ifdef __CINT__
    Double_t reftime = 186.34; //pcbrun4 interpreted
 #else
    Double_t reftime = 93.59; //pcbrun4 compiled
 #endif
-   const Double_t rootmarks = 860 * reftime / gBenchmark->GetCpuTime("StressRooStats");
+   const Double_t rootmarks = 860 * reftime / gBenchmark->GetCpuTime("stressRooStats");
 
    cout << setw(lineWidth) << setfill('*') << "" << endl;
-   cout << TString::Format("*  ROOTMARKS = %6.1f   *  Root%-8s  %d/%d", rootmarks, gROOT->GetVersion(),
+   cout << TString::Format("*  ROOTMARKS = %6.1f  *  Root %-8s %d/%d", rootmarks, gROOT->GetVersion(),
                            gROOT->GetVersionDate(), gROOT->GetVersionTime()) << endl;
    cout << setw(lineWidth) << setfill('*') << "" << endl;
 
@@ -284,12 +277,14 @@ Int_t stressRooStats(const char* refFile, Bool_t writeRef, Int_t verbose, Int_t
 
 int main(int argc, const char *argv[])
 {
-   Bool_t doWrite     = kFALSE ;
-   Int_t verbose    = 0 ;
-   Int_t oneTest      = -1 ;
-   Bool_t dryRun      = kFALSE ;
-   Bool_t doDump      = kFALSE ;
-   Bool_t doTreeStore = kFALSE ;
+   Bool_t doWrite     = kFALSE;
+   Int_t  verbose     =      0;
+   Bool_t allTests    = kFALSE;
+   Bool_t oneTest     = kFALSE;
+   Int_t testNumber   =      0;
+   Bool_t dryRun      = kFALSE;
+   Bool_t doDump      = kFALSE;
+   Bool_t doTreeStore = kFALSE;
 
    string refFileName = "http://root.cern.ch/files/stressRooStats_v534_ref.root" ;
 
@@ -300,59 +295,45 @@ int main(int argc, const char *argv[])
       if (arg == "-f") {
          cout << "stressRooStats: using reference file " << argv[i + 1] << endl ;
          refFileName = argv[++i] ;
-      }
-
-      if (arg == "-w") {
+      } else if (arg == "-w") {
          cout << "stressRooStats: running in writing mode to update reference file" << endl ;
          doWrite = kTRUE ;
-      }
-
-      if (arg == "-mc") {
-         cout << "stressRooStats: running in memcheck mode, no regression tests are performed" << endl ;
-         dryRun = kTRUE ;
-      }
-
-      if (arg == "-ts") {
-         cout << "stressRooStats: setting tree-based storage for datasets" << endl ;
-         doTreeStore = kTRUE ;
-      }
-
-      if (arg == "-v") {
-         cout << "stressRooStats: running in verbose mode" << endl ;
-         verbose = 1 ;
-      }
-
-      if (arg == "-vv") {
-         cout << "stressRooStats: running in very verbose mode" << endl ;
-         verbose = 2 ;
-      }
-
-      if (arg == "-n") {
-         cout << "stressRooStats: running single test " << argv[i + 1] << endl ;
-         oneTest = atoi(argv[++i]) ;
-      }
-
-      if (arg == "-d") {
-         cout << "stressRooStats: setting gDebug to " << argv[i + 1] << endl ;
-         gDebug = atoi(argv[++i]) ;
-      }
-
-      if (arg == "-c") {
-         cout << "stressRooStats: dumping comparison file for failed tests " << endl ;
-         doDump = kTRUE ;
-      }
-
-      if (arg == "-h") {
-         cout << "usage: stressRooStats [ options ] " << endl ;
-         cout << "" << endl ;
-         cout << "       -f <file> : use given reference file instead of default (" <<  refFileName << ")" << endl ;
-         cout << "       -w        : write reference file, instead of reading file and running comparison tests" << endl ;
-         cout << " " << endl ;
-         cout << "       -n N      : Only run test with sequential number N instead of full suite of tests" << endl ;
-         cout << "       -c        : dump file stressRooStats_DEBUG.root to which results of both current result and reference for each failed test are written" << endl ;
-         cout << "       -mc       : memory check mode, no regression test are performed. Set this flag when running with valgrind" << endl ;
-         cout << "       -vs       : Use vector-based storage for all datasets (default is tree-based storage)" << endl ;
-         cout << "       -v/-vv    : set verbose mode (show result of each regression test) or very verbose mode (show all roofit output as well)" << endl ;
+      } else if (arg == "-mc") {
+         cout << "stressRooStats: running in memcheck mode, no regression tests are performed" << endl;
+         dryRun = kTRUE;
+      } else if (arg == "-ts") {
+         cout << "stressRooStats: setting tree-based storage for datasets" << endl;
+         doTreeStore = kTRUE;
+      } else if (arg == "-v") {
+         cout << "stressRooStats: running in verbose mode" << endl;
+         verbose = 1;
+      } else if (arg == "-vv") {
+         cout << "stressRooStats: running in very verbose mode" << endl;
+         verbose = 2;
+      } else if (arg == "-a") {
+         cout << "stressRooStats: deploying full suite of tests" << endl;
+         allTests = kTRUE;
+      } else if (arg == "-n") {
+         cout << "stressRooStats: running single test" << endl;
+         oneTest = kTRUE;
+         testNumber = atoi(argv[++i]);
+      } else if (arg == "-d") {
+         cout << "stressRooStats: setting gDebug to " << argv[i + 1] << endl;
+         gDebug = atoi(argv[++i]);
+      } else if (arg == "-c") {
+         cout << "stressRooStats: dumping comparison file for failed tests " << endl;
+         doDump = kTRUE;
+      } else if (arg == "-h") {
+         cout << "usage: stressRooStats [ options ] " << endl;
+         cout << "" << endl;
+         cout << "       -f <file> : use given reference file instead of default (" << refFileName << ")" << endl;
+         cout << "       -w        : write reference file, instead of reading file and running comparison tests" << endl;
+         cout << "       -n N      : only run test with sequential number N" << endl;
+         cout << "       -a        : run full suite of tests (default is basic suite); this overrides the -n single test option" << endl;
+         cout << "       -c        : dump file stressRooStats_DEBUG.root to which results of both current result and reference for each failed test are written" << endl;
+         cout << "       -mc       : memory check mode, no regression test are performed. Set this flag when running with valgrind" << endl;
+         cout << "       -vs       : use vector-based storage for all datasets (default is tree-based storage)" << endl;
+         cout << "       -v/-vv    : set verbose mode (show result of each regression test) or very verbose mode (show all roofit output as well)" << endl;
          cout << "       -d N      : set ROOT gDebug flag to N" << endl ;
          cout << " " << endl ;
          return 0 ;
@@ -366,13 +347,12 @@ int main(int argc, const char *argv[])
       char* buf = new char[refFileName.size() + 1];
       strcpy(buf, refFileName.c_str());
       char *ptr = strrchr(buf, '/');
-      if (!ptr) {
-         ptr = strrchr(buf, ':');
-      }
+      if (!ptr) ptr = strrchr(buf, ':');
       refFileName = ptr + 1;
       delete[] buf;
 
-      cout << "stressRooStats: WARNING running in write mode, but reference file is web file, writing local file instead: " << refFileName << endl;
+      cout << "stressRooStats: WARNING running in write mode, but reference file is web file, writing local file instead: "
+           << refFileName << endl;
    }
 
    // Disable caching of complex error function calculation, as we don't
@@ -380,7 +360,7 @@ int main(int argc, const char *argv[])
    RooMath::cacheCERF(kFALSE) ;
 
    gBenchmark = new TBenchmark();
-   stressRooStats(refFileName.c_str(), doWrite, verbose, oneTest, dryRun, doDump, doTreeStore);
+   stressRooStats(refFileName.c_str(), doWrite, verbose, allTests, oneTest, testNumber, dryRun, doDump, doTreeStore);
    return 0;
 }
 
diff --git a/test/stressRooStats_models.cxx b/test/stressRooStats_models.cxx
index 56f436e..da4b75d 100644
--- a/test/stressRooStats_models.cxx
+++ b/test/stressRooStats_models.cxx
@@ -6,103 +6,110 @@
 // RooStats headers
 #include "RooStats/ModelConfig.h"
 
+using namespace RooFit;
 using namespace RooStats;
 
 //__________________________________________________________________________________
 void buildPoissonProductModel(RooWorkspace *w)
 {
    // Build product model
-   w->factory("expr::compsig('2*sig*pow(1.2, beta)', sig[0,20], beta[-5,5])");
-   w->factory("Poisson::poiss1(x[0,40], sum::splusb1(sig, bkg1[0,20]))");
-   w->factory("Poisson::poiss2(y[0,120], sum::splusb2(compsig, bkg2[0,20]))");
-   w->factory("Poisson::constr1(gbkg1[10,0,20], bkg1)");
-   w->factory("Poisson::constr2(gbkg2[10,0,20], bkg2)");
-   w->factory("Gaussian::constr3(beta0[0,-5,5], beta, 1)"); 
+   w->factory("expr::compsig('2*sig*pow(1.2, beta)', sig[0,20], beta[-3,3])");
+   w->factory("Poisson::poiss1(x[0,40], sum::splusb1(sig, bkg1[0,10]))");
+   w->factory("Poisson::poiss2(y[0,120], sum::splusb2(compsig, bkg2[0,10]))");
+   w->factory("Poisson::constr1(gbkg1[5,0,10], bkg1)");
+   w->factory("Poisson::constr2(gbkg2[5,0,10], bkg2)");
+   w->factory("Gaussian::constr3(beta0[0,-3,3], beta, 1)");
    w->factory("PROD::pdf(poiss1, poiss2, constr1, constr2, constr3)");
 
-   // set POI prior Pdf (for BayesianCalculator and other Bayesian methods) 
+   // POI prior Pdf (for BayesianCalculator and other Bayesian methods)
    w->factory("Uniform::prior(sig)");
+   // Nuisance parameters Pdf (for HybridCalculator)
+   w->factory("PROD::prior_nuis(constr1,constr2,constr3)");
 
-   // build argument sets
-   w->defineSet("obs", "x,y");
-   w->defineSet("poi", "sig");
-   w->defineSet("nuis", "bkg1,bkg2,beta");
-   w->defineSet("globObs", "beta0,gbkg1,gbkg2");
-
-   // set global observables to constant values
-   RooFIter iter = w->set("globObs")->fwdIterator();
-   RooRealVar *var;
-   while((var = (RooRealVar *)iter.next()) != NULL) var->setConstant();
+   // extended pdfs and simultaneous pdf
+   w->factory("ExtendPdf::epdf1(PROD::pdf1(poiss1,constr1),n1[0,10])");
+   w->factory("ExtendPdf::epdf2(PROD::pdf2(poiss2,constr2,constr3),n2[0,10])");
+   w->factory("SIMUL::sim_pdf(index[cat1,cat2],cat1=epdf1,cat2=epdf2)");
 
-   // build data set and import it into the workspace sets
-   RooDataSet *data = new RooDataSet("data", "data", *w->set("obs"));
-   w->import(*data);
+   // build argument sets
+//   w->defineSet("obs", "x,y");
+//   w->defineSet("poi", "sig");
+//   w->defineSet("nuis", "bkg1,bkg2,beta");
+//   w->defineSet("globObs", "beta0,gbkg1,gbkg2");
 
    // create signal + background model configuration
    ModelConfig *sbModel = new ModelConfig("S+B", w);
-   sbModel->SetObservables(*w->set("obs"));
-   sbModel->SetGlobalObservables(*w->set("globObs"));
-   sbModel->SetParametersOfInterest(*w->set("poi"));
-   sbModel->SetNuisanceParameters(*w->set("nuis"));
+   sbModel->SetObservables("x,y");
+   sbModel->SetGlobalObservables("beta0,gbkg1,gbkg2");
+   sbModel->SetParametersOfInterest("sig");
+   sbModel->SetNuisanceParameters("bkg1,bkg2,beta");
    sbModel->SetPdf("pdf");
-   sbModel->SetPriorPdf("prior");
 
    // create background model configuration
    ModelConfig *bModel = new ModelConfig(*sbModel);
    bModel->SetName("B");
 
+   // set global observables to constant values
+   RooFIter iter = sbModel->GetGlobalObservables()->fwdIterator();
+   RooRealVar *var = dynamic_cast<RooRealVar *>(iter.next());
+   while(var != NULL) {
+      var->setConstant(); 
+      var = dynamic_cast<RooRealVar *>(iter.next());
+   }
+
+   // build data set and import it into the workspace sets
+   RooDataSet *data = new RooDataSet("data", "data", *sbModel->GetObservables());
+   w->import(*data);
+
    w->import(*sbModel);
    w->import(*bModel);
 }
 
 
+//__________________________________________________________________________________
+// Insightful comments on model courtesy of Kyle Cranmer, Wouter Verkerke, Sven Kreiss
+//    from $ROOTSYS/tutorials/roostats/HybridInstructional.C
 void buildOnOffModel(RooWorkspace *w)
 {
    // Build model for prototype on/off problem
    // Poiss(x | s+b) * Poiss(y | tau b )
-   w->factory("Poisson::on_pdf(n_on[0,500],sum::splusb(sig[0,500],bkg[0,500]))");
-   w->factory("Poisson::off_pdf(n_off[0,500],prod::taub(tau[0.1,5.0],bkg))");
-   w->factory("PROD::prod_pdf(on_pdf, off_pdf)");        
+   w->factory("Poisson::on_pdf(n_on[0,300],sum::splusb(sig[0,100],bkg[0,200]))");
+   w->factory("Poisson::off_pdf(n_off[0,1100],prod::taub(tau[0.1,5.0],bkg))");
+   w->factory("PROD::prod_pdf(on_pdf, off_pdf)");
 
    // construct the Bayesian-averaged model (eg. a projection pdf)
    // p'(x|s) = \int db p(x|s+b) * [ p(y|b) * prior(b) ]
    w->factory("Uniform::prior(bkg)");
    w->factory("PROJ::averagedModel(PROD::foo(on_pdf|bkg,off_pdf,prior),bkg)") ;
 
-   // define sets of variables obs={x} and poi={sig}
-   // x is the only observable in the main measurement and y is treated as a separate measurement,
-   // which is used to produce the prior that will be used in the calculation to randomize the nuisance parameters
-   w->defineSet("obs", "n_on,n_off,tau");
-   w->defineSet("poi", "sig");
-   w->defineSet("nuis", "bkg");
-
-   // define data set and import it into workspace
-   RooDataSet *data = new RooDataSet("data", "data", *w->set("obs"));
-   w->import(*data);
-
    // create signal + background model configuration
    ModelConfig *sbModel = new ModelConfig("S+B", w);
-   sbModel->SetPdf(*w->pdf("prod_pdf"));
-   sbModel->SetObservables(*w->set("obs"));      
-   sbModel->SetParametersOfInterest(*w->set("poi"));
-   sbModel->SetNuisanceParameters(*w->set("nuis"));
+   sbModel->SetPdf("prod_pdf");
+   sbModel->SetObservables("n_on,n_off");
+   sbModel->SetParametersOfInterest("sig");
+   sbModel->SetNuisanceParameters("bkg");
 
    // create background model configuration
    ModelConfig *bModel = new ModelConfig(*sbModel);
    bModel->SetName("B");
-   
+
    // alternate priors
    w->factory("Gaussian::gauss_prior(bkg, n_off, expr::sqrty('sqrt(n_off)', n_off))");
    w->factory("Lognormal::lognorm_prior(bkg, n_off, expr::kappa('1+1./sqrt(n_off)',n_off))");
 
+   // define data set and import it into workspace
+   RooDataSet *data = new RooDataSet("data", "data", *sbModel->GetObservables());
+   w->import(*data);
+
    w->import(*sbModel);
    w->import(*bModel);
 }
 
 
-void createPoissonEfficiencyModel(RooWorkspace *w) {
-   
-   // build models 
+void createPoissonEfficiencyModel(RooWorkspace *w)
+{
+
+   // build models
    w->factory("Gaussian::constrb(b0[-5,5], b1[-5,5], 1)");
    w->factory("Gaussian::constre(e0[-5,5], e1[-5,5], 1)");
    w->factory("expr::bkg('5 * pow(1.3, b1)', b1)"); // background model
@@ -129,20 +136,20 @@ void createPoissonEfficiencyModel(RooWorkspace *w) {
 
    // create model configuration
    ModelConfig *sbModel = new ModelConfig("S+B", w);
-   sbModel->SetObservables(*w->set("obs"));
-   sbModel->SetParametersOfInterest(*w->set("poi"));
-   sbModel->SetNuisanceParameters(*w->set("nuis"));
+   sbModel->SetObservables("x");
+   sbModel->SetParametersOfInterest("sig");
+   sbModel->SetNuisanceParameters("b1,e1");
+   sbModel->SetGlobalObservables("b0,e0");
    sbModel->SetPdf("sb_pdf");
    //sbModel->SetPriorPdf("prior");
-   sbModel->SetSnapshot(*w->set("poi"));
-   sbModel->SetGlobalObservables(*w->set("globObs"));
- 
+   sbModel->SetSnapshot(*sbModel->GetParametersOfInterest());
+
    ModelConfig *bModel = new ModelConfig(*sbModel);
    bModel->SetName("B");
    bModel->SetPdf("b_pdf");
-   
+
    w->import(*sbModel);
-   w->import(*bModel);   
+   w->import(*bModel);
 }
 
 
diff --git a/test/stressRooStats_tests.cxx b/test/stressRooStats_tests.cxx
index 3914ed3..7253cc5 100644
--- a/test/stressRooStats_tests.cxx
+++ b/test/stressRooStats_tests.cxx
@@ -21,6 +21,7 @@
 using namespace ROOT::Math;
 using namespace RooFit;
 using namespace RooStats;
+using namespace std;
 
 // testStatType = 0 Simple Likelihood Ratio (the LEP TestStat)
 //              = 1 Ratio of Profiled Likelihood Ratios (the Tevatron TestStat)
@@ -29,9 +30,9 @@ using namespace RooStats;
 //              = 4 Profile Likelihood Signed (pll = -pll if mu < mu_hat)
 //              = 5 Max Likelihood Estimate as test statistic
 //              = 6 Number of Observed Events as test statistic
-enum ETestStatType { kSimpleLR = 0, kRatioLR = 1, kProfileLR= 2, kProfileLROneSided = 3, kProfileLRSigned = 4, kMLE = 5, kNObs = 6 };
-static const char *kECalculatorTypeString[] = { "Undefined", "Hybrid", "Frequentist", "Asymptotic" };
-static const char *kETestStatTypeString[] = { "Simple Likelihood Ratio", "Ratio Likelihood Ratio", "Profile Likelihood Ratio", "Profile Likelihood One Sided", "Profile Likelihood Signed", "Max Likelihood Estimate", "Number of Observed Events" };
+enum ETestStatType { kSimpleLR = 0, kRatioLR = 1, kProfileLR = 2, kProfileLROneSided = 3, kProfileLRSigned = 4, kMLE = 5, kNObs = 6 };
+static const char * const kECalculatorTypeString[] = { "Undefined", "Hybrid", "Frequentist", "Asymptotic" };
+static const char * const kETestStatTypeString[] = { "Simple Likelihood Ratio", "Ratio Likelihood Ratio", "Profile Likelihood Ratio", "Profile Likelihood One Sided", "Profile Likelihood Signed", "Max Likelihood Estimate", "Number of Observed Events" };
 static TestStatistic *buildTestStatistic(const ETestStatType testStatType, const ModelConfig &sbModel, const ModelConfig &bModel);
 
 
@@ -78,22 +79,22 @@ private:
 
 public:
    TestProfileLikelihoodCalculator1(
-      TFile* refFile, 
-      Bool_t writeRef, 
-      Int_t verbose, 
+      TFile* refFile,
+      Bool_t writeRef,
+      Int_t verbose,
       Double_t confidenceLevel = 0.95
-   ) : 
+   ) :
       RooUnitTest("ProfileLikelihoodCalculator Interval - Gaussian Model", refFile, writeRef, verbose),
-      fConfidenceLevel(confidenceLevel) 
+      fConfidenceLevel(confidenceLevel)
    {};
 
    // Basic checks for the parameters passed to the test
    // In case of invalid parameters, a warning is printed and the test is skipped
    Bool_t isTestAvailable() {
-      if(fConfidenceLevel <= 0.0 || fConfidenceLevel >= 1.0) {
+      if (fConfidenceLevel <= 0.0 || fConfidenceLevel >= 1.0) {
          Warning("isTestAvailable", "Confidence level must be in the range (0,1). Skipping test...");
          return kFALSE;
-      }      
+      }
       return kTRUE;
    }
 
@@ -103,18 +104,18 @@ public:
       // the compared values / objects must have the same name in write / compare modes
       const TString lowerLimitString = TString::Format("tplc2_lower_limit_mean_%lf", fConfidenceLevel);
       const TString upperLimitString = TString::Format("tplc2_upper_limit_mean_%lf", fConfidenceLevel);
-      
+
       //TODO: see why it fails for a small number of observations
-      // Create Gaussian model, generate data set and define 
+      // Create Gaussian model, generate data set and define
       RooWorkspace* w = new RooWorkspace("w", kTRUE);
-      w->factory("Gaussian::gauss(x[-5,5], mean[0,-5,5], sigma[1])"); 
+      w->factory("Gaussian::gauss(x[-5,5], mean[0,-5,5], sigma[1])");
       RooDataSet *data = w->pdf("gauss")->generate(*w->var("x"), N);
 
       if (_write == kTRUE) {
 
          // Calculate likelihood interval from data via analytic methods
          Double_t estMean = data->mean(*w->var("x"));
-         Double_t intervalHalfWidth = 
+         Double_t intervalHalfWidth =
             normal_quantile_c((1.0 - fConfidenceLevel) / 2.0, w->var("sigma")->getValV() / sqrt(N));
          Double_t lowerLimit = estMean - intervalHalfWidth;
          Double_t upperLimit = estMean + intervalHalfWidth;
@@ -138,7 +139,7 @@ public:
          delete plc;
          delete interval;
       }
-      
+
       // Cleanup local objects
       delete data;
       delete w;
@@ -173,22 +174,22 @@ private:
 
 public:
    TestProfileLikelihoodCalculator2(
-      TFile* refFile, 
-      Bool_t writeRef, 
-      Int_t verbose, 
+      TFile* refFile,
+      Bool_t writeRef,
+      Int_t verbose,
       Int_t obsValue = 5
-   ) : 
-      RooUnitTest("ProfileLikelihoodCalculator Interval - Poisson Simple Model", refFile, writeRef, verbose), 
-      fObsValue(obsValue) 
+   ) :
+      RooUnitTest("ProfileLikelihoodCalculator Interval - Poisson Simple Model", refFile, writeRef, verbose),
+      fObsValue(obsValue)
    {};
 
    // Basic checks for the parameters passed to the test
    // In case of invalid parameters, a warning is printed and the test is skipped
    Bool_t isTestAvailable() {
-      if(fObsValue < 0 || fObsValue > 1000) {
+      if (fObsValue < 0 || fObsValue > 1000) {
          Warning("isTestAvailable", "Observed value must be in the range [0,1000]. Skipping test...");
          return kFALSE;
-      }      
+      }
       return kTRUE;
    }
 
@@ -223,7 +224,7 @@ public:
       } else {
 
          // Set a 68% confidence level for the interval
-         const Double_t confidenceLevel = 2 * normal_cdf(1) - 1.0; 
+         const Double_t confidenceLevel = 2 * normal_cdf(1) - 1.0;
 
          // Create Poisson model and dataset
          RooWorkspace* w = new RooWorkspace("w", kTRUE);
@@ -254,16 +255,16 @@ public:
 
 ///////////////////////////////////////////////////////////////////////////////
 //
-// PROFILE LIKELIHOOD CALCULATOR - LIKELIHOOD INTERVAL - POISSON COMPLEX MODEL
+// PROFILE LIKELIHOOD CALCULATOR - LIKELIHOOD INTERVAL - POISSON PRODUCT MODEL
 //
 // Test the 68% likelihood interval computed by the ProfileLikelihoodCalculator
-// on a complex model. Reference values and test values are both computed with 
-// the ProfileLikelihoodCalculator. As such, this test can only confirm if the 
+// on a complex model. Reference values and test values are both computed with
+// the ProfileLikelihoodCalculator. As such, this test can only confirm if the
 // ProfileLikelihoodCalculator has the same behaviour across different computer
 // platforms or RooStats revisions.
 //
 // ModelConfig (explicit) : Poisson Product Model
-//    built in stressRooStats_models.cxx 
+//    built in stressRooStats_models.cxx
 //
 // Input Parameters:
 //    obsValueX -> observed value "x" when measuring sig + bkg1
@@ -282,15 +283,15 @@ private:
 
 public:
    TestProfileLikelihoodCalculator3(
-      TFile* refFile, 
-      Bool_t writeRef, 
-      Int_t verbose, 
-      Int_t obsValueX = 15, 
+      TFile* refFile,
+      Bool_t writeRef,
+      Int_t verbose,
+      Int_t obsValueX = 15,
       Int_t obsValueY = 30,
       Double_t confidenceLevel = 2 * normal_cdf(1) - 1
-   ) : 
-      RooUnitTest("ProfileLikelihoodCalculator Interval - Poisson Product Model", refFile, writeRef, verbose), 
-      fObsValueX(obsValueX), 
+   ) :
+      RooUnitTest("ProfileLikelihoodCalculator Interval - Poisson Product Model", refFile, writeRef, verbose),
+      fObsValueX(obsValueX),
       fObsValueY(obsValueY),
       fConfidenceLevel(confidenceLevel)
    {};
@@ -298,18 +299,18 @@ public:
    // Basic checks for the parameters passed to the test
    // In case of invalid parameters, a warning is printed and the test is skipped
    Bool_t isTestAvailable() {
-      if(fObsValueX < 0 || fObsValueX > 40) {
+      if (fObsValueX < 0 || fObsValueX > 40) {
          Warning("isTestAvailable", "Observed value X=s+b must be in the range [0,40]. Skipping test...");
          return kFALSE;
       }
-      if(fObsValueY < 0 || fObsValueY > 120) {
+      if (fObsValueY < 0 || fObsValueY > 120) {
          Warning("isTestAvailable", "Observed value Y=2*s*1.2^beta+b must be in the range [0,120]. Skipping test...");
          return kFALSE;
-      }         
-      if(fConfidenceLevel <= 0.0 || fConfidenceLevel >= 1.0) {
+      }
+      if (fConfidenceLevel <= 0.0 || fConfidenceLevel >= 1.0) {
          Warning("isTestAvailable", "Confidence level must be in the range (0,1). Skipping test...");
          return kFALSE;
-      }      
+      }
       return kTRUE;
    }
 
@@ -318,24 +319,24 @@ public:
       // Create workspace and model
       RooWorkspace *w = new RooWorkspace("w", kTRUE);
       buildPoissonProductModel(w);
-      ModelConfig *model = (ModelConfig *)w->obj("S+B");     
- 
-      // add observed values to data set 
+      ModelConfig *model = (ModelConfig *)w->obj("S+B");
+
+      // add observed values to data set
       w->var("x")->setVal(fObsValueX);
       w->var("y")->setVal(fObsValueY);
-      w->data("data")->add(*w->set("obs"));
-      
+      w->data("data")->add(*model->GetObservables());
+
       // build likelihood interval with ProfileLikelihoodCalculator
       ProfileLikelihoodCalculator *plc = new ProfileLikelihoodCalculator(*w->data("data"), *model);
       plc->SetConfidenceLevel(fConfidenceLevel);
       LikelihoodInterval *interval = plc->GetInterval();
 
       regValue(
-         interval->LowerLimit(*w->var("sig")), 
+         interval->LowerLimit(*w->var("sig")),
          TString::Format("tplc3_lower_limit_sig_%d_%d_%lf", fObsValueX, fObsValueY, fConfidenceLevel)
       );
       regValue(
-         interval->UpperLimit(*w->var("sig")), 
+         interval->UpperLimit(*w->var("sig")),
          TString::Format("tplc3_upper_limit_sig_%d_%d_%lf", fObsValueX, fObsValueY, fConfidenceLevel)
       );
 
@@ -351,20 +352,21 @@ public:
 
 ///////////////////////////////////////////////////////////////////////////////
 //
-// PROFILE LIKELIHOOD CALCULATOR - HYPOTHESIS TEST
+// PROFILE LIKELIHOOD CALCULATOR HYPOTHESIS TEST - ON / OFF MODEL
 //
 // Perform a hypothesis test using the ProfileLikelihoodCalculator on the
-// on/off model. Reference values and test values are both computed with the 
-// ProfileLikelihoodCalculator. As such, this test can only confirm if the 
-// ProfileLikelihoodCalculator has the same behaviour on a different machine.
+// on/off model. Reference values and test values are both computed with the
+// ProfileLikelihoodCalculator. As such, this test can only confirm if the
+// ProfileLikelihoodCalculator has the same behaviour accross different
+// computing platforms or RooStats revisions.
 //
 // ModelConfig (explicit) : Poisson On / Off Model
-//    built in stressRooStats_models.cxx 
+//    built in stressRooStats_models.cxx
 //
-// For a detailed description of the on/off model, see the paper: "Evaluation 
+// For a detailed description of the on/off model, see the paper: "Evaluation
 // of three methods for calculating statistical significance when incorporating
-// a systematic uncertainty into a test of the background-only hypothesis for 
-// a Poisson process" by Robert D. Cousins, James T. Linnemann, Jordan Tucker 
+// a systematic uncertainty into a test of the background-only hypothesis for
+// a Poisson process" by Robert D. Cousins, James T. Linnemann, Jordan Tucker
 //
 // 04/2012 - Ioan Gabriel Bucur
 //
@@ -373,17 +375,19 @@ public:
 class TestProfileLikelihoodCalculator4 : public RooUnitTest {
 public:
    TestProfileLikelihoodCalculator4(
-      TFile* refFile, 
-      Bool_t writeRef, 
+      TFile* refFile,
+      Bool_t writeRef,
       Int_t verbose
-   ) : 
-      RooUnitTest("ProfileLikelihoodCalculator Hypothesis Test", refFile, writeRef, verbose) 
+   ) :
+      RooUnitTest("ProfileLikelihoodCalculator Hypothesis Test", refFile, writeRef, verbose)
    {};
 
    // Override test value tolerance
    // A larger tolerance is needed since the values in the Cousins paper are given with 1e-2 precision
-   Double_t vtol() { return 1e-2; }
- 
+   Double_t vtol() {
+      return 1e-2;
+   }
+
    Bool_t testCode() {
 
       // For testing purposes, we consider four special cases for which the values are known from
@@ -393,20 +397,20 @@ public:
       const Int_t numberTestSets = 3;
       const Int_t numberOnEvents[numberTestSets] = {4, 50, 67};
       const Int_t numberOffEvents[numberTestSets] = {5, 55, 15};
-      const Double_t tau[numberTestSets] = {5.0, 2.0, 0.5}; 
+      const Double_t tau[numberTestSets] = {5.0, 2.0, 0.5};
       const Double_t significance[numberTestSets] =  {1.95, 3.02, 3.04};
 
-      for(Int_t i = 0; i < numberTestSets; i++) {
+      for (Int_t i = 0; i < numberTestSets; i++) {
 
          TString stringSignificance = TString::Format("tplc4_significance_%d_%d_%lf", numberOnEvents[i], numberOffEvents[i], tau[i]);
 
-         if(_write == kTRUE) {
+         if (_write == kTRUE) {
 
             // register reference values from Cousins et al. paper
             regValue(significance[i], stringSignificance);
 
          } else {
-      
+
             // build workspace and model
             RooWorkspace *w = new RooWorkspace("w", kTRUE);
             buildOnOffModel(w);
@@ -416,26 +420,24 @@ public:
             // add observable values to data set
             w->var("n_on")->setVal(numberOnEvents[i]);
             w->var("n_off")->setVal(numberOffEvents[i]);
-            w->var("tau")->setVal(tau[i]); 
+            w->var("tau")->setVal(tau[i]);
             w->var("tau")->setConstant();
-            w->data("data")->add(*w->set("obs"));
+            w->data("data")->add(*sbModel->GetObservables());
 
             // set snapshots
             w->var("sig")->setVal(numberOnEvents[i] - numberOffEvents[i] / tau[i]);
-            sbModel->SetSnapshot(*w->set("poi"));
+            sbModel->SetSnapshot(*sbModel->GetParametersOfInterest());
             w->var("sig")->setVal(0);
-            bModel->SetSnapshot(*w->set("poi")); 
+            bModel->SetSnapshot(*bModel->GetParametersOfInterest());
 
+            // get significance using the ProfileLikelihoodCalculator
             ProfileLikelihoodCalculator *plc = new ProfileLikelihoodCalculator(*w->data("data"), *sbModel);
             plc->SetNullParameters(*bModel->GetSnapshot());
             plc->SetAlternateParameters(*sbModel->GetSnapshot());
-            HypoTestResult *htr = plc->GetHypoTest();
-
-            regValue(htr->Significance(), stringSignificance);
+            regValue(plc->GetHypoTest()->Significance(), stringSignificance);
 
             // cleanup
             delete plc;
-            delete htr;
             delete w;
          }
       }
@@ -497,17 +499,21 @@ class TestBayesianCalculator1 : public RooUnitTest {
 private:
    Int_t fObsValue;
    Double_t fConfidenceLevel;
-   static Double_t priorInv(Double_t mean) { return 1.0 / mean; }
-   static Double_t priorInvSqrt(Double_t mean) { return 1.0 / sqrt(mean); }
+   static Double_t priorInv(Double_t mean) {
+      return 1.0 / mean;
+   }
+   static Double_t priorInvSqrt(Double_t mean) {
+      return 1.0 / sqrt(mean);
+   }
 
 public:
    TestBayesianCalculator1(
-      TFile* refFile, 
-      Bool_t writeRef, 
+      TFile* refFile,
+      Bool_t writeRef,
       Int_t verbose,
       Int_t obsValue = 3,
       Double_t confidenceLevel = 2 * normal_cdf(1) - 1
-   ) : 
+   ) :
       RooUnitTest("BayesianCalculator Central Interval - Poisson Simple Model", refFile, writeRef, verbose),
       fObsValue(obsValue),
       fConfidenceLevel(confidenceLevel)
@@ -516,14 +522,14 @@ public:
    // Basic checks for the parameters passed to the test
    // In case of invalid parameters, a warning is printed and the test is skipped
    Bool_t isTestAvailable() {
-      if(fObsValue < 0 || fObsValue > 100) {
+      if (fObsValue < 0 || fObsValue > 100) {
          Warning("isTestAvailable", "Observed value must be in the range [0,100]. Skipping test...");
          return kFALSE;
       }
-      if(fConfidenceLevel <= 0.0 || fConfidenceLevel >= 1.0) {
+      if (fConfidenceLevel <= 0.0 || fConfidenceLevel >= 1.0) {
          Warning("isTestAvailable", "Confidence level must be in the range (0,1). Skipping test...");
          return kFALSE;
-      }      
+      }
       return kTRUE;
    }
 
@@ -617,7 +623,7 @@ public:
          interval = bc->GetInterval();
          regValue(interval->LowerLimit(), lowerLimitInvSqrtString);
          regValue(interval->UpperLimit(), upperLimitInvSqrtString);
-         
+
          delete bc;
          delete interval;
 
@@ -666,16 +672,18 @@ public:
 class TestBayesianCalculator2 : public RooUnitTest {
 public:
    TestBayesianCalculator2(
-      TFile* refFile, 
-      Bool_t writeRef, 
+      TFile* refFile,
+      Bool_t writeRef,
       Int_t verbose
-   ) : 
-      RooUnitTest("BayesianCalculator Shortest Interval - Poisson Simple Model", refFile, writeRef, verbose) 
+   ) :
+      RooUnitTest("BayesianCalculator Shortest Interval - Poisson Simple Model", refFile, writeRef, verbose)
    {};
 
    // the references values in the paper have a precision of only two decimal points
    // in such a situation, it is natural that we increase the value tolerance
-   Double_t vtol() { return 1e-2; }
+   Double_t vtol() {
+      return 1e-2;
+   }
 
    Bool_t testCode() {
 
@@ -755,14 +763,14 @@ public:
 // BAYESIAN CENTRAL INTERVAL - POISSON PRODUCT MODEL
 //
 // Test the validity of the central interval computed by the BayesianCalculator
-// on a complex Poisson model distribution. Reference values and test values 
+// on a complex Poisson model distribution. Reference values and test values
 // are both computed with the BayesianCalculator. As such, this test can only
 // confirm if the BayesianCalculator has the same behaviour across different
-// computer platforms or RooStats revisions. A uniform prior PDF is used for the
+// computing platforms or RooStats revisions. A uniform prior PDF is used for the
 // parameter of interest ("sig").
 //
 // ModelConfig (explicit) : Poisson Product Model
-//    built in stressRooStats_models.cxx 
+//    built in stressRooStats_models.cxx
 //
 // Input Parameters:
 //    obsValueX -> observed value "x" when measuring sig + bkg1
@@ -781,14 +789,14 @@ private:
 
 public:
    TestBayesianCalculator3(
-      TFile* refFile, 
-      Bool_t writeRef, 
+      TFile* refFile,
+      Bool_t writeRef,
       Int_t verbose,
       Int_t obsValueX = 15,
       Int_t obsValueY = 30,
       Double_t confidenceLevel = 2 * normal_cdf(1) - 1
-   ) : 
-      RooUnitTest("BayesianCalculator Central Interval - Poisson Product Model", refFile, writeRef, verbose), 
+   ) :
+      RooUnitTest("BayesianCalculator Central Interval - Poisson Product Model", refFile, writeRef, verbose),
       fObsValueX(obsValueX),
       fObsValueY(obsValueY),
       fConfidenceLevel(confidenceLevel)
@@ -797,38 +805,38 @@ public:
    // Basic checks for the parameters passed to the test
    // In case of invalid parameters, a warning is printed and the test is skipped
    Bool_t isTestAvailable() {
-      if(fObsValueX < 0 || fObsValueX > 40) {
+      if (fObsValueX < 0 || fObsValueX > 40) {
          Warning("isTestAvailable", "Observed value X=s+b must be in the range [0,40]. Skipping test...");
          return kFALSE;
       }
-      if(fObsValueY < 0 || fObsValueY > 120) {
+      if (fObsValueY < 0 || fObsValueY > 120) {
          Warning("isTestAvailable", "Observed value Y=2*s*1.2^beta+b must be in the range [0,120]. Skipping test...");
          return kFALSE;
-      }         
-      if(fConfidenceLevel <= 0.0 || fConfidenceLevel >= 1.0) {
+      }
+      if (fConfidenceLevel <= 0.0 || fConfidenceLevel >= 1.0) {
          Warning("isTestAvailable", "Confidence level must be in the range (0,1). Skipping test...");
          return kFALSE;
-      }      
+      }
       return kTRUE;
    }
 
    Bool_t testCode() {
 
       const Int_t numberScans = 10; // sufficient number of scans
-      
+
       // Create workspace and model
       RooWorkspace *w = new RooWorkspace("w", kTRUE);
       buildPoissonProductModel(w);
-      ModelConfig *model = (ModelConfig *)w->obj("S+B"); 
- 
-      // add observed values to data set 
+      ModelConfig *model = (ModelConfig *)w->obj("S+B");
+
+      // add observed values to data set
       w->var("x")->setVal(fObsValueX);
       w->var("y")->setVal(fObsValueY);
-      w->data("data")->add(*w->set("obs"));
+      w->data("data")->add(*model->GetObservables());
 
       // NOTE: Roo1DIntegrator is too slow and gives poor results
       RooAbsReal::defaultIntegratorConfig()->method1D().setLabel("RooAdaptiveGaussKronrodIntegrator1D");
-     
+
       // Create BayesianCalculator and
       BayesianCalculator *bc = new BayesianCalculator(*w->data("data"), *model);
       bc->SetConfidenceLevel(fConfidenceLevel);
@@ -837,11 +845,11 @@ public:
       // Obtain confidence interval by scanning the posterior function in the given number of points
       SimpleInterval *interval = bc->GetInterval();
       regValue(
-         interval->LowerLimit(), 
+         interval->LowerLimit(),
          TString::Format("tbc3_lower_limit_sig_%d_%d_%lf", fObsValueX, fObsValueY, fConfidenceLevel)
       );
       regValue(
-         interval->UpperLimit(), 
+         interval->UpperLimit(),
          TString::Format("tbc3_upper_limit_sig_%d_%d_%lf", fObsValueX, fObsValueY, fConfidenceLevel)
       );
 
@@ -882,13 +890,13 @@ public:
 // MCMC INTERVAL CALCULATOR - POISSON PRODUCT MODEL
 //
 // Test the validity of the confidence interval computed by the MCMCCalculator
-// on a complex Poisson model distribution. Reference values and test values 
-// are both computed with the MCMCCalculator. As such, this test can only 
+// on a complex Poisson model distribution. Reference values and test values
+// are both computed with the MCMCCalculator. As such, this test can only
 // confirm if the BayesianCalculator has the same behaviour across different
-// computer platforms or RooStats revisions.
+// computing platforms or RooStats revisions.
 //
 // ModelConfig (explicit) : Poisson Product Model
-//    built in stressRooStats_models.cxx 
+//    built in stressRooStats_models.cxx
 //
 // Input Parameters:
 //    obsValueX -> observed value "x" when measuring sig + bkg1
@@ -907,13 +915,13 @@ private:
 
 public:
    TestMCMCCalculator(
-      TFile* refFile, 
-      Bool_t writeRef, 
+      TFile* refFile,
+      Bool_t writeRef,
       Int_t verbose,
       Int_t obsValueX = 15,
       Int_t obsValueY = 30,
       Double_t confidenceLevel = 2 * normal_cdf(1) - 1
-   ) : 
+   ) :
       RooUnitTest("MCMCCalculator Interval - Poisson Product Model", refFile, writeRef, verbose),
       fObsValueX(obsValueX),
       fObsValueY(obsValueY),
@@ -923,39 +931,36 @@ public:
    // Basic checks for the parameters passed to the test
    // In case of invalid parameters, a warning is printed and the test is skipped
    Bool_t isTestAvailable() {
-      if(fObsValueX < 0 || fObsValueX > 40) {
+      if (fObsValueX < 0 || fObsValueX > 40) {
          Warning("isTestAvailable", "Observed value X=s+b must be in the range [0,40]. Skipping test...");
          return kFALSE;
       }
-      if(fObsValueY < 0 || fObsValueY > 120) {
+      if (fObsValueY < 0 || fObsValueY > 120) {
          Warning("isTestAvailable", "Observed value Y=2*s*1.2^beta+b must be in the range [0,120]. Skipping test...");
          return kFALSE;
-      }         
-      if(fConfidenceLevel <= 0.0 || fConfidenceLevel >= 1.0) {
+      }
+      if (fConfidenceLevel <= 0.0 || fConfidenceLevel >= 1.0) {
          Warning("isTestAvailable", "Confidence level must be in the range (0,1). Skipping test...");
          return kFALSE;
-      }      
+      }
       return kTRUE;
    }
 
    Bool_t testCode() {
 
-      // Make MCMCCalculator results repeatable
-      RooRandom::randomGenerator()->SetSeed(12345);
-
       // Create workspace and model
       RooWorkspace *w = new RooWorkspace("w", kTRUE);
       buildPoissonProductModel(w);
       ModelConfig *model = (ModelConfig *)w->obj("S+B");
 
-      // add observed values to data set 
+      // add observed values to data set
       w->var("x")->setVal(fObsValueX);
       w->var("y")->setVal(fObsValueY);
-      w->data("data")->add(*w->set("obs"));
- 
+      w->data("data")->add(*model->GetObservables());
+
       // NOTE: Roo1DIntegrator is too slow and gives poor results
-     // RooAbsReal::defaultIntegratorConfig()->method1D().setLabel("RooAdaptiveGaussKronrodIntegrator1D");
-    
+      RooAbsReal::defaultIntegratorConfig()->method1D().setLabel("RooAdaptiveGaussKronrodIntegrator1D");
+
       // create and configure MCMC calculator
       SequentialProposal *sp = new SequentialProposal(0.1);
       MCMCCalculator *mcmcc = new MCMCCalculator(*w->data("data"), *model);
@@ -967,11 +972,11 @@ public:
       // calculate the confidence interval
       MCMCInterval *interval = mcmcc->GetInterval();
       regValue(
-         interval->LowerLimit(*w->var("sig")), 
+         interval->LowerLimit(*w->var("sig")),
          TString::Format("mcmcc_lower_limit_sig_%d_%d_%lf", fObsValueX, fObsValueY, fConfidenceLevel)
       );
       regValue(
-         interval->UpperLimit(*w->var("sig")), 
+         interval->UpperLimit(*w->var("sig")),
          TString::Format("mcmcc_upper_limit_sig_%d_%d_%lf", fObsValueX, fObsValueY, fConfidenceLevel)
       );
 
@@ -1002,29 +1007,231 @@ public:
 ///////////////////////////////////////////////////////////////////////////////
 //
 // PART FOUR:
+//    HYPOTHESIS TEST CALCULATOR UNIT TESTS
+//
+
+// Hypo Test Calculators
+#include "RooStats/HypoTestCalculatorGeneric.h"
+#include "RooStats/FrequentistCalculator.h"
+#include "RooStats/HybridCalculator.h"
+#include "RooStats/AsymptoticCalculator.h"
+// Test Statistics
+#include "RooStats/ProfileLikelihoodTestStat.h"
+#include "RooStats/RatioOfProfiledLikelihoodsTestStat.h"
+#include "RooStats/SimpleLikelihoodRatioTestStat.h"
+#include "RooStats/ProfileLikelihoodCalculator.h"
+#include "RooStats/MaxLikelihoodEstimateTestStat.h"
+#include "RooStats/NumEventsTestStat.h"
+
+/////////////////////////////////////////////////////////////////////////
+//
+// ZBI - ON / OFF MODEL
+//
+// Evaluate the functionality of the top level functions in RooStats
+// called NumberCountingUtils::BinomialWithTauObsZ. This function
+// computes the significance of a hypothesis test via a frequentist
+// solution. This significance, called ZBi, is detailed in the article
+// "Evaluation of three methods for calculating statistical significance
+// when incorporating a systematic uncertainty into a test of the
+// background-only hypothesis for a Poisson process" by Robert D. Cousins,
+// James T. Linnemann, Jordan Tucker. The reference values are taken
+// from the paper, as well as the On / Off model on which the test is
+// evaluated.
+//
+// ModelConfig (implicit) : Poisson On / Off Model
+//    built in stressRooStats_models.cxx
+//    implicit in NumberCountingUtils::BinomialWithTauObsZ
+//
+// 05/2012 - Wouter Verkerke, Lorenzo Moneta, Ioan Gabriel Bucur
+//
+/////////////////////////////////////////////////////////////////////////
+
+
+class TestZBi : public RooUnitTest {
+public:
+
+   TestZBi(
+      TFile* refFile,
+      Bool_t writeRef,
+      Int_t verbose
+   ) :
+      RooUnitTest("ZBi Significance - On / Off Model", refFile, writeRef, verbose)
+   {};
+
+   // Override test value tolerance
+   // A larger tolerance is needed since the values in the Cousins paper are given with 1e-2 precision
+   Double_t vtol() {
+      return 1e-2;
+   }
+
+   Bool_t testCode() {
+
+      // For testing purposes, we consider four special cases for which the values are known from
+      // the Cousins et al. paper mentioned above. The inputs for each of these cases are (using
+      // the notations from the paper): n_on, n_off and Z_PL. We provide a certain fixed input set
+      // for each case.
+      const Int_t numberTestSets = 4;
+      const Int_t numberOnEvents[numberTestSets] = {4, 50, 67, 200};
+      const Int_t numberOffEvents[numberTestSets] = {5, 55, 15, 10};
+      const Double_t tau[numberTestSets] = {5.0, 2.0, 0.5, 0.1};
+      const Double_t significance[numberTestSets] =  {1.66, 2.93, 2.89, 2.2};
+
+      for (Int_t i = 0; i < numberTestSets; i++) {
+
+         TString stringSignificance = TString::Format("tzbi_significance_%d_%d_%lf", numberOnEvents[i], numberOffEvents[i], tau[i]);
+
+         if (_write == kTRUE) {
+
+            // register reference values from Cousins et al. paper
+            regValue(significance[i], stringSignificance);
+
+         } else {
+
+            // call top level function
+            regValue(
+               NumberCountingUtils::BinomialWithTauObsZ(numberOnEvents[i], numberOffEvents[i], tau[i]),
+               stringSignificance
+            );
+
+         }
+      }
+
+      return kTRUE ;
+   }
+};
+
+
+///////////////////////////////////////////////////////////////////////////////
+//
+// ASYMPTOTIC CALCULATOR VS PROFILE LIKELIHOOD CALCULATOR HYPOTHESIS TEST
+//
+// This test evaluates the functionality of the AsymptoticCalculator by
+// comparing the significance given from a hypothesis test on the on/off model
+// with the significance given by the ProfileLikelihoodCalculator. The validity
+// of the PLC hypothesis test is evaluated in TestProfileLikelihoodCalculator4.
+// If working properly, the two methods should yield identical results.
+//
+// ModelConfig (explicit) : Poisson On / Off Model
+//    built in stressRooStats_models.cxx
+//
+// Input Parameters:
+//    obsValueOn -> observed value "n_on" of sig + bkg
+//    obsValueOff -> observed value "n_off" of tau * bkg
+//    tau -> parameter of the model (constant with regard to integration)
+//
+// 05/2012 - Ioan Gabriel Bucur
+//
+///////////////////////////////////////////////////////////////////////////////
+
+class TestHypoTestCalculator1 : public RooUnitTest {
+private:
+   Int_t fObsValueOn;
+   Int_t fObsValueOff;
+   Double_t fTau;
+
+public:
+   TestHypoTestCalculator1(
+      TFile* refFile,
+      Bool_t writeRef,
+      Int_t verbose,
+      Int_t obsValueOn = 150,
+      Int_t obsValueOff = 100,
+      Double_t tau = 1.0
+   ) :
+      RooUnitTest("AsymptoticCalculator vs ProfileLikelihoodCalculator Significance - On / Off Model", refFile, writeRef, verbose),
+      fObsValueOn(obsValueOn),
+      fObsValueOff(obsValueOff),
+      fTau(tau)
+   {};
+
+   Bool_t testCode() {
+
+      // names of tested variables must be the same in write / comparison modes
+      TString significanceString = TString::Format("thtc1_significance_%d_%d_%lf", fObsValueOn, fObsValueOff, fTau);
+
+      // build workspace and model
+      RooWorkspace* w = new RooWorkspace("w", kTRUE);
+      buildOnOffModel(w);
+      ModelConfig *sbModel = (ModelConfig *)w->obj("S+B");
+      ModelConfig *bModel = (ModelConfig *)w->obj("B");
+
+      // add observable values to data set and fix other parameters
+      w->var("n_on")->setVal(fObsValueOn);
+      w->var("n_off")->setVal(fObsValueOff);
+      w->var("tau")->setVal(fTau);
+      w->var("tau")->setConstant();
+      w->data("data")->add(*sbModel->GetObservables());
+      w->var("bkg")->setVal(fObsValueOff / fTau);
+
+      // Make snapshots
+      w->var("sig")->setVal(fObsValueOn - fObsValueOff / fTau);
+      sbModel->SetSnapshot(*sbModel->GetParametersOfInterest());
+      w->var("sig")->setVal(0.0);
+      bModel->SetSnapshot(*bModel->GetParametersOfInterest());
+
+      // Do hypothesis test with ProfileLikelihoodCalculator
+      if (_write == kTRUE) {
+
+         ProfileLikelihoodCalculator *plc = new ProfileLikelihoodCalculator(*w->data("data"), *sbModel);
+         plc->SetNullParameters(*bModel->GetSnapshot());
+         regValue(plc->GetHypoTest()->Significance(), significanceString);
+
+         // cleanup branch
+         delete plc;
+
+      } else { // Do hypothesis test with AsymptoticCalculator
+
+         AsymptoticCalculator::SetPrintLevel(0); // disable superfluous messaging
+         AsymptoticCalculator *atc = new AsymptoticCalculator(*w->data("data"), *sbModel, *bModel);
+         atc->SetOneSidedDiscovery(kTRUE);
+         regValue(atc->GetHypoTest()->Significance(), significanceString);
+
+         // cleanup branch
+         delete atc;
+      }
+
+      // cleanup
+      delete w;
+
+      return kTRUE ;
+   }
+} ;
+
+
+//
+// END OF PART FOUR
+//
+///////////////////////////////////////////////////////////////////////////////
+///////////////////////////////////////////////////////////////////////////////
+//_____________________________________________________________________________
+
+
+
+
+
+//_____________________________________________________________________________
+///////////////////////////////////////////////////////////////////////////////
+///////////////////////////////////////////////////////////////////////////////
+//
+// PART FIVE:
 //    HYPOTHESIS TEST INVERTER UNIT TESTS
 //
 
 #include "RooStats/HypoTestInverter.h"
 #include "RooStats/HypoTestInverterResult.h"
-#include "RooStats/HypoTestCalculatorGeneric.h"
 #include "RooStats/ToyMCSampler.h"
-#include "RooStats/HybridCalculator.h"
-#include "RooStats/ProfileLikelihoodTestStat.h"
-#include "RooStats/AsymptoticCalculator.h"
 #include "RooStats/HypoTestInverterPlot.h"
 #include "RooStats/SamplingDistPlot.h"
 
-
 ///////////////////////////////////////////////////////////////////////////////
 //
 // HYPOTESTINVERTER INTERVAL - POISSON PRODUCT MODEL
 //
 // Test the validity of the confidence interval computed by the HypoTestInverter
-// on a complex Poisson model distribution. Reference values and test values 
-// are both computed with the MCMCCalculator. As such, this test can only 
+// on a complex Poisson model distribution. Reference values and test values
+// are both computed with the MCMCCalculator. As such, this test can only
 // confirm if the BayesianCalculator has the same behaviour across different
-// computer platforms or RooStats revisions.
+// computing platforms or RooStats revisions.
 //
 // ModelConfig (explicit) : Poisson Product Model
 //    built in stressRooStats_models.cxx
@@ -1049,17 +1256,17 @@ private:
 
 public:
    TestHypoTestInverter1(
-      TFile* refFile, 
-      Bool_t writeRef, 
-      Int_t verbose, 
-      HypoTestInverter::ECalculatorType calculatorType, 
+      TFile* refFile,
+      Bool_t writeRef,
+      Int_t verbose,
+      HypoTestInverter::ECalculatorType calculatorType,
       ETestStatType testStatType,
       Int_t obsValueX = 15,
       Int_t obsValueY = 30,
       Double_t confidenceLevel = 2 * normal_cdf(1) - 1
-   ) : 
-      RooUnitTest(TString::Format("HypoTestInverter Interval - Poisson Product Model - %s %s", 
-         kECalculatorTypeString[calculatorType], kETestStatTypeString[testStatType]), refFile, writeRef, verbose),
+   ) :
+      RooUnitTest(TString::Format("HypoTestInverter Interval - Poisson Product Model - %s - %s",
+                                  kECalculatorTypeString[calculatorType], kETestStatTypeString[testStatType]), refFile, writeRef, verbose),
       fCalculatorType(calculatorType),
       fTestStatType(testStatType),
       fObsValueX(obsValueX),
@@ -1070,20 +1277,20 @@ public:
    // Basic checks for the parameters passed to the test
    // In case of invalid parameters, a warning is printed and the test is skipped
    Bool_t isTestAvailable() {
-      if(fObsValueX < 0 || fObsValueX > 40) {
+      if (fObsValueX < 0 || fObsValueX > 40) {
          Warning("isTestAvailable", "Observed value X=s+b must be in the range [0,40]. Skipping test...");
          return kFALSE;
       }
-      if(fObsValueY < 0 || fObsValueY > 120) {
+      if (fObsValueY < 0 || fObsValueY > 120) {
          Warning("isTestAvailable", "Observed value Y=2*s*1.2^beta+b must be in the range [0,120]. Skipping test...");
          return kFALSE;
-      }         
-      if(fConfidenceLevel <= 0.0 || fConfidenceLevel >= 1.0) {
+      }
+      if (fConfidenceLevel <= 0.0 || fConfidenceLevel >= 1.0) {
          Warning("isTestAvailable", "Confidence level must be in the range (0,1). Skipping test...");
          return kFALSE;
-      }      
+      }
       return kTRUE;
-   } 
+   }
 
    Bool_t testCode() {
 
@@ -1091,66 +1298,75 @@ public:
       RooWorkspace *w = new RooWorkspace("w", kTRUE);
       buildPoissonProductModel(w);
       ModelConfig *sbModel = (ModelConfig *)w->obj("S+B");
-      ModelConfig *bModel = (ModelConfig *)w->obj("B");   
+      ModelConfig *bModel = (ModelConfig *)w->obj("B");
 
-      // add observed values to data set 
+      // add observed values to data set
       w->var("x")->setVal(fObsValueX);
       w->var("y")->setVal(fObsValueY);
-      w->data("data")->add(*w->set("obs"));
-      
+      w->data("data")->add(*sbModel->GetObservables());
+
       // set snapshots
       w->var("sig")->setVal(fObsValueX - w->var("bkg1")->getValV());
-      sbModel->SetSnapshot(*w->set("poi"));
+      sbModel->SetSnapshot(*sbModel->GetParametersOfInterest());
       w->var("sig")->setVal(0);
-      bModel->SetSnapshot(*w->set("poi"));    
+      bModel->SetSnapshot(*bModel->GetParametersOfInterest());
 
-      //TODO: check how this code can be eliminated, maybe 0 should be default print level for AsymptoticCalculator
-      if(fCalculatorType == HypoTestInverter::kAsymptotic) {
+      //TODO: check how to eliminate this code, maybe 0 should be default print level for AsymptoticCalculator
+      if (fCalculatorType == HypoTestInverter::kAsymptotic) {
          AsymptoticCalculator::SetPrintLevel(0); // print only minimal output
       }
 
       // configure HypoTestInverter
-      HypoTestInverter *hti = new HypoTestInverter(*w->data("data"), *sbModel, *bModel, NULL, fCalculatorType, 1.0 - fConfidenceLevel);
+      HypoTestInverter *hti =
+         new HypoTestInverter(*w->data("data"), *sbModel, *bModel, NULL, fCalculatorType, 1.0 - fConfidenceLevel);
       hti->SetTestStatistic(*buildTestStatistic(fTestStatType, *sbModel, *bModel));
       hti->SetFixedScan(10, w->var("sig")->getMin(), w->var("sig")->getMax()); // significant speedup
- 
-      //TODO: check how to eliminate this code, calculator should autoconfigure itself     
-      if(fCalculatorType == HypoTestInverter::kHybrid) {
-         // force prior nuisance pdf
+
+      //TODO: check how to eliminate this code, calculator should autoconfigure itself
+      if (fCalculatorType == HypoTestInverter::kHybrid) {
+         // force prior nuisance pdf and set toys for speedup
          HybridCalculator *hc = (HybridCalculator *)hti->GetHypoTestCalculator();
-         hc->ForcePriorNuisanceNull(*w->pdf("priorbkg"));
-         hc->ForcePriorNuisanceAlt(*w->pdf("priorbkg"));
-      } 
+         hc->ForcePriorNuisanceNull(*MakeNuisancePdf(*sbModel, "nuis_prior_null"));
+         hc->ForcePriorNuisanceAlt(*MakeNuisancePdf(*bModel, "nuis_prior_alt"));
+         hc->SetToys(100, 1);
+      }
+
+      //TODO: check how to eliminate this code
+      if (fCalculatorType == HypoTestInverter::kFrequentist) {
+         // set toys for speedup
+         FrequentistCalculator *fc = (FrequentistCalculator *)hti->GetHypoTestCalculator();
+         fc->SetToys(100, 1);
+      }
 
       // ToyMCSampler configuration
       ToyMCSampler *tmcs = (ToyMCSampler *)hti->GetHypoTestCalculator()->GetTestStatSampler();
-      tmcs->SetMaxToys(100); // speedup
       tmcs->SetNEventsPerToy(1); // needed because we don't have an extended pdf
+      tmcs->SetAlwaysUseMultiGen(kTRUE); // speedup
 
       HypoTestInverterResult *interval = hti->GetInterval();
-      regValue(interval->LowerLimit(), TString::Format("hti1_lower_limit_sig1_calc_%s_%s_%d_%d_%lf", 
+      regValue(interval->LowerLimit(), TString::Format("hti1_lower_limit_sig1_calc_%s_%s_%d_%d_%lf",
                                                        kECalculatorTypeString[fCalculatorType],
                                                        kETestStatTypeString[fTestStatType],
-                                                       fObsValueX, fObsValueY, fConfidenceLevel ));
+                                                       fObsValueX, fObsValueY, fConfidenceLevel));
       regValue(interval->UpperLimit(), TString::Format("hti1_upper_limit_sig1_calc_%s_%s_%d_%d_%lf",
                                                        kECalculatorTypeString[fCalculatorType],
                                                        kETestStatTypeString[fTestStatType],
-                                                       fObsValueX, fObsValueY, fConfidenceLevel ));
+                                                       fObsValueX, fObsValueY, fConfidenceLevel));
 
-      if(_verb >= 1) {
-         HypoTestInverterPlot *plot = new HypoTestInverterPlot("hti1 Plot", "Feldman-Cousins Interval", interval);
-         TCanvas *c1 = new TCanvas("HypoTestInverter1 Scan");
+      if (_verb >= 1) {
+         HypoTestInverterPlot *plot = new HypoTestInverterPlot("hti1_scan", "Two-Sided Scan", interval);
+         TCanvas *c1 = new TCanvas("hti1_scan", "HTI Scan");
          c1->SetLogy(false);
-         plot->Draw("OBS");
+         plot->Draw("");
          c1->SaveAs(TString::Format("hti1_scan_%s_%s_%d_%d_%lf.pdf",
                                     kECalculatorTypeString[fCalculatorType],
                                     kETestStatTypeString[fTestStatType],
-                                    fObsValueX, fObsValueY, fConfidenceLevel ));
+                                    fObsValueX, fObsValueY, fConfidenceLevel));
 
-         if(_verb == 2) {
+         if (_verb == 2) {
             const int n = interval->ArraySize();
             if (n > 0 && interval->GetResult(0)->GetNullDistribution()) {
-               TCanvas *c2 = new TCanvas("Test Statistic Distributions", "", 2);
+               TCanvas *c2 = new TCanvas("HTI_TestStatistic_Distribution", "HTI Test Statistic Distributions", 2);
                if (n > 1) {
                   int ny = TMath::CeilNint(sqrt(n));
                   int nx = TMath::CeilNint(double(n) / ny);
@@ -1159,14 +1375,14 @@ public:
                for (int i = 0; i < n; i++) {
                   if (n > 1) c2->cd(i + 1);
                   SamplingDistPlot *pl = plot->MakeTestStatPlot(i);
-                  if(pl == NULL) return kTRUE;
+                  if (pl == NULL) return kTRUE;
                   pl->SetLogYaxis(kTRUE);
                   pl->Draw();
                }
                c2->SaveAs(TString::Format("hti1_teststat_distrib_%s_%s_%d_%d_%lf.pdf",
                                           kECalculatorTypeString[fCalculatorType],
                                           kETestStatTypeString[fTestStatType],
-                                          fObsValueX, fObsValueY, fConfidenceLevel ));
+                                          fObsValueX, fObsValueY, fConfidenceLevel));
             }
          }
       }
@@ -1181,100 +1397,23 @@ public:
 };
 
 
-
-
-// OTHER TESTS FOLLOW
-
-/////////////////////////////////////////////////////////////////////////
 //
-// 'BASIC FUNCTIONALITY' RooFit tutorial macro #101
+// END OF PART FIVE
 //
-// Fitting, plotting, toy data generation on one-dimensional p.d.f
-//
-// pdf = gauss(x,m,s)
-//
-//
-// 07/2008 - Wouter Verkerke
-//
-/////////////////////////////////////////////////////////////////////////
-
-
-class TestBasic101 : public RooUnitTest {
-public:
-   TestBasic101(TFile* refFile, Bool_t writeRef, Int_t verbose) : RooUnitTest("Zbi and Zgamma", refFile, writeRef, verbose) {};
-
-   Bool_t testCode() {
-
-      // Make model for prototype on/off problem
-      // Pois(x | s+b) * Pois(y | tau b )
-      // for Z_Gamma, use uniform prior on b.
-      RooWorkspace* w = new RooWorkspace("w", kTRUE);
-      w->factory("Poisson::px(x[150,0,500],sum::splusb(s[0,0,100],b[100,0,300]))");
-      w->factory("Poisson::py(y[100,0,500],prod::taub(tau[1.],b))");
-      w->factory("Uniform::prior_b(b)");
-
-      // construct the Bayesian-averaged model (eg. a projection pdf)
-      // p'(x|s) = \int db p(x|s+b) * [ p(y|b) * prior(b) ]
-      w->factory("PROJ::averagedModel(PROD::foo(px|b,py,prior_b),b)") ;
-
-      // plot it, blue is averaged model, red is b known exactly
-      RooPlot* frame = w->var("x")->frame();
-      w->pdf("averagedModel")->plotOn(frame);
-      w->pdf("px")->plotOn(frame, LineColor(kRed));
-
-      // compare analytic calculation of Z_Bi
-      // with the numerical RooFit implementation of Z_Gamma
-      // for an example with x = 150, y = 100
-
-      // numeric RooFit Z_Gamma
-      w->var("y")->setVal(100);
-      w->var("x")->setVal(150);
-      RooAbsReal* cdf = w->pdf("averagedModel")->createCdf(*w->var("x"));
-      cdf->getVal(); // get ugly print messages out of the way
+///////////////////////////////////////////////////////////////////////////////
+///////////////////////////////////////////////////////////////////////////////
+//_____________________________________________________________________________
 
-      Double_t hybrid_p_value = cdf->getVal() ;
-      Double_t zgamma_signif = PValueToSignificance(1 - cdf->getVal()) ;
 
-      // analytic Z_Bi
-      Double_t Z_Bi = NumberCountingUtils::BinomialWithTauObsZ(150, 100, 1);
 
-      // Register output quantities for regression test
-      regPlot(frame, "rs101_zbi_zgamma") ;
-      regValue(hybrid_p_value, "rs101_hybrid_p_value") ;
-      regValue(zgamma_signif, "rs101_zgamma_signif") ;
-      regValue(Z_Bi, "rs101_Z_Bi") ;
 
-//   delete w; // interesting why it doesn't work
 
-      return kTRUE ;
-   }
-} ;
 
 
 
-///////////////////////////////////////////////////////////////////////////////
-//
-// 'HYPOTESTCALCULATOR'
-//
-// This test evaluetes the functionality of the HypoTestCalculators.
-//
-// 04/2012 - Ioan Gabriel Bucur
-// Insightful comments courtesy of Kyle Cranmer, Wouter Verkerke, Sven Kreiss
-//    from $ROOTSYS/tutorials/roostats/HybridInstructional.C
-//
-///////////////////////////////////////////////////////////////////////////////
 
 
-#include "RooStats/ProfileLikelihoodTestStat.h"
-#include "RooStats/SimpleLikelihoodRatioTestStat.h"
-#include "RooStats/HypoTestCalculatorGeneric.h"
-#include "RooStats/FrequentistCalculator.h"
-#include "RooStats/HybridCalculator.h"
-#include "RooStats/AsymptoticCalculator.h"
-#include "RooStats/ProfileLikelihoodCalculator.h"
-#include "RooStats/MaxLikelihoodEstimateTestStat.h"
-#include "RooStats/NumEventsTestStat.h"
-#include "RooStats/RatioOfProfiledLikelihoodsTestStat.h"
+// Other tests currently not included in any suite
 
 
 class TestHypoTestCalculator : public RooUnitTest {
@@ -1285,29 +1424,29 @@ public:
 
       const Int_t xValue = 150;
       const Int_t yValue = 100;
-      const Double_t tauValue = 1;
-      
-      if(_write == kTRUE) {
+      const Double_t tauValue = 1.0;
+
+      if (_write == kTRUE) {
 
          // register analytical Z_Bi value
          Double_t Z_Bi = NumberCountingUtils::BinomialWithTauObsZ(xValue, yValue, tauValue);
          regValue(Z_Bi, "thtc_significance_hybrid");
 
       } else {
-      
+
          // Make model for prototype on/off problem
          // Pois(x | s+b) * Pois(y | tau b )
          RooWorkspace* w = new RooWorkspace("w", kTRUE);
          w->factory(TString::Format("Poisson::on_pdf(x[%d,0,500],sum::splusb(sig[0,0,100],bkg[100,0,300]))", xValue));
          w->factory(TString::Format("Poisson::off_pdf(y[%d,0,500],prod::taub(tau[%lf],bkg))", yValue, tauValue));
-         w->factory("PROD::prod_pdf(on_pdf, off_pdf)");        
+         w->factory("PROD::prod_pdf(on_pdf, off_pdf)");
 
          w->var("x")->setVal(xValue);
          w->var("y")->setVal(yValue);
          w->var("y")->setConstant();
-         w->var("tau")->setVal(tauValue); 
+         w->var("tau")->setVal(tauValue);
 
-        // construct the Bayesian-averaged model (eg. a projection pdf)
+         // construct the Bayesian-averaged model (eg. a projection pdf)
          // p'(x|s) = \int db p(x|s+b) * [ p(y|b) * prior(b) ]
          w->factory("Uniform::prior(bkg)");
          w->factory("PROJ::averagedModel(PROD::foo(on_pdf|bkg,off_pdf,prior),bkg)") ;
@@ -1326,7 +1465,7 @@ public:
          // Build S+B and B models
          ModelConfig *sbModel = new ModelConfig("SB_ModelConfig", w);
          sbModel->SetPdf(*w->pdf("prod_pdf"));
-         sbModel->SetObservables(*w->set("obs"));      
+         sbModel->SetObservables(*w->set("obs"));
          sbModel->SetParametersOfInterest(*w->set("poi"));
          w->var("sig")->setVal(xValue - yValue / tauValue); // important !
          sbModel->SetSnapshot(*w->set("poi"));
@@ -1355,15 +1494,11 @@ public:
          pllts->SetAlwaysReuseNLL(kTRUE);
          pllts->SetOneSidedDiscovery(kTRUE);
 
-         MaxLikelihoodEstimateTestStat *mlets = 
+         MaxLikelihoodEstimateTestStat *mlets =
             new MaxLikelihoodEstimateTestStat(*sbModel->GetPdf(), *((RooRealVar *)sbModel->GetParametersOfInterest()->first()));
-      
+
          NumEventsTestStat *nevts = new NumEventsTestStat(*sbModel->GetPdf());
 
-         // ProfileLikelihoodCalculator *plc = new ProfileLikelihoodCalculator(*data, *sbModel);
-         // plc->SetNullParameters(*bModel->GetSnapshot());
-         // HypoTestResult *htr0 = plc->GetHypoTest();
-         // htr0->Print(); 
 
 
 
@@ -1394,7 +1529,7 @@ public:
          htr = htc->GetHypoTest();
          htr->Print();
          cout << "ROPLTS " << htr->Significance() << endl;
- 
+
 
          regValue(htr->Significance(), "thtc_significance_hybrid");
 
@@ -1409,82 +1544,86 @@ public:
 } ;
 
 
+#include "RooPoisson.h"
+
 class TestHypoTestCalculator2 : public RooUnitTest {
 public:
-   TestHypoTestCalculator2(TFile* refFile, Bool_t writeRef, Int_t verbose) : RooUnitTest("HypoTestCalculator Frequentist - On / Off Problem", refFile, writeRef, verbose) {};
+   TestHypoTestCalculator2(
+      TFile* refFile,
+      Bool_t writeRef,
+      Int_t verbose
+   ) :
+      RooUnitTest("HypoTestCalculator Frequentist - Simultaneous Pdf", refFile, writeRef, verbose)
+   {};
 
    Bool_t testCode() {
 
-      const Int_t xValue = 150;
-      const Int_t yValue = 100;
-      const Double_t tauValue = 1;
-      
-      if(_write == kTRUE) {
+      const Int_t fObsValueX = 20;
+      const Int_t fObsValueY = 30;
+      const Double_t fTau = 1.0;
+
+      if (_write == kTRUE) {
 
          // register analytical Z_Bi value
-         Double_t Z_Bi = NumberCountingUtils::BinomialWithTauObsZ(xValue, yValue, tauValue);
+         Double_t Z_Bi = NumberCountingUtils::BinomialWithTauObsZ(fObsValueX, fObsValueY, fTau);
          regValue(Z_Bi, "thtc_significance_frequentist");
 
       } else {
-      
-         // Make model for prototype on/off problem
-         // Pois(x | s+b) * Pois(y | tau b )
+
+         // Build workspace and models
          RooWorkspace* w = new RooWorkspace("w", kTRUE);
-         w->factory("Poisson::on_pdf(x[150,0,500],sum::splusb(sig[0,0,100],bkg[100,0,300]))");
-         w->factory("Poisson::off_pdf(y[100,0,500],prod::taub(tau[1],bkg))");
-         w->factory("PROD::prod_pdf(on_pdf, off_pdf)");
-        
-         w->var("x")->setVal(xValue);
-         w->var("y")->setVal(yValue);
-         w->var("y")->setConstant();
-         w->var("tau")->setVal(tauValue);
-         w->var("tau")->setConstant();
-         // construct the Bayesian-averaged model (eg. a projection pdf)
-         // p'(x|s) = \int db p(x|s+b) * [ p(y|b) * prior(b) ]
-         //w->factory("PROJ::averagedModel(PROD::foo(on_pdf|bkg,off_pdf,prior),bkg)") ;
+         buildPoissonProductModel(w);
+         ModelConfig *sbModel = (ModelConfig *)w->obj("S+B");
+         ModelConfig *bModel = (ModelConfig *)w->obj("B");
+
+         sbModel->SetPdf(*w->pdf("sim_pdf"));
+         bModel->SetPdf(*w->pdf("sim_pdf"));
+
+         // add observed values to data set
+         w->var("x")->setVal(fObsValueX);
+         w->var("y")->setVal(fObsValueY);
+         w->data("data")->add(*sbModel->GetObservables());
+
+         // combined dataset for simultaneous pdf
+         RooDataSet *combData = new RooDataSet(
+            "combData",
+            "combined data",
+            *sbModel->GetObservables(),
+            Index(*dynamic_cast<RooCategory *>(w->obj("index"))),
+            Import("cat1", *dynamic_cast<RooDataSet *>(w->data("data"))),
+            Import("cat2", *dynamic_cast<RooDataSet *>(w->data("data")))
+         );
+
+   combData->Print("v");
+   for (Int_t i = 0; i < combData->numEntries(); i++) {
+      combData->get(i)->Print("v");
+   }
 
-         // define sets of variables obs={x} and poi={sig}
-         // x is the only observable in the main measurement and y is treated as a separate measurement,
-         // which is used to produce the prior that will be used in the calculation to randomize the nuisance parameters
-         w->defineSet("obs", "x");
-         w->defineSet("poi", "sig");
-         w->defineSet("nuis", "bkg");
-         w->defineSet("globObs", "y");
 
-         // Add observable value to a data set
-         RooDataSet *data = new RooDataSet("data", "data", *w->set("obs"));
-         data->add(*w->set("obs"));
 
+         //w->data("combData")->get(0)->Print("v");
+        // w->data("combData")->get(1)->Print("v");
 
-         // Build S+B and B models
-         ModelConfig *sbModel = new ModelConfig("SB_ModelConfig", w);
-         sbModel->SetPdf(*w->pdf("prod_pdf"));
-         sbModel->SetObservables(*w->set("obs"));
-         sbModel->SetGlobalObservables(*w->set("globObs"));      
-         sbModel->SetParametersOfInterest(*w->set("poi"));
-         sbModel->SetNuisanceParameters(*w->set("nuis"));
-         w->var("sig")->setVal(xValue - yValue / tauValue); // important !
-         sbModel->SetSnapshot(*w->set("poi"));
+/*
+         RooRealVar x("x","x",0,40);
+         RooRealVar mean("mean", "mean", 2, 0, 10);
+         RooRealVar mc("mc", "mc", 5, 0, 10);
+         RooPoisson p1("p1","p1",x,mean);
+         RooPoisson pc("pc","pc",mc,mean);
+         RooProdPdf pdf("pdf","pdf",RooArgList(p1,pc));
 
-         ModelConfig *bModel = new ModelConfig("B_ModelConfig", w);
-         bModel->SetPdf(*w->pdf("prod_pdf"));
-         bModel->SetObservables(*w->set("obs"));
-         bModel->SetGlobalObservables(*w->set("globObs"));
-         bModel->SetParametersOfInterest(*w->set("poi")); 
-         bModel->SetNuisanceParameters(*w->set("nuis"));
-         w->var("sig")->setVal(0.0); // important !
-         bModel->SetSnapshot(*w->set("poi"));
-   
-         w->import(*sbModel);
-         w->import(*bModel);
-         w->import(*data);
+         RooDataSet *data1 = p1.generate(x,100);
+         RooDataSet *data2 = pc.generate(x,50);
+*/
 
 
-         w->writeToFile("htc_ws.root");
+//         w->Print();
 
-         // alternate priors
-         w->factory("Gaussian::gauss_prior(bkg, y, expr::sqrty('sqrt(y)', y))");
-         w->factory("Lognormal::lognorm_prior(bkg, y, expr::kappa('1+1./sqrt(y)',y))");
+         // set snapshots
+         w->var("sig")->setVal(fObsValueX - w->var("bkg1")->getValV());
+         sbModel->SetSnapshot(*sbModel->GetParametersOfInterest());
+         w->var("sig")->setVal(0);
+         bModel->SetSnapshot(*bModel->GetParametersOfInterest());
 
          // build test statistic
          SimpleLikelihoodRatioTestStat *slrts =  new SimpleLikelihoodRatioTestStat(*bModel->GetPdf(), *sbModel->GetPdf());
@@ -1496,32 +1635,32 @@ public:
          roplts->SetAlwaysReuseNLL(kTRUE);
 
          ProfileLikelihoodTestStat *pllts = new ProfileLikelihoodTestStat(*bModel->GetPdf());
-         pllts->SetAlwaysReuseNLL(kTRUE);
          pllts->SetOneSidedDiscovery(kTRUE);
+         pllts->SetAlwaysReuseNLL(kTRUE);
 
-         MaxLikelihoodEstimateTestStat *mlets = 
+         MaxLikelihoodEstimateTestStat *mlets =
             new MaxLikelihoodEstimateTestStat(*sbModel->GetPdf(), *((RooRealVar *)sbModel->GetParametersOfInterest()->first()));
-      
+
          NumEventsTestStat *nevts = new NumEventsTestStat(*sbModel->GetPdf());
 
-        /* ProfileLikelihoodCalculator *plc = new ProfileLikelihoodCalculator(*data, *sbModel);
-         plc->SetNullParameters(*bModel->GetSnapshot());
-         plc->SetAlternateParameters(*sbModel->GetSnapshot());
-         HypoTestResult *htr0 = plc->GetHypoTest();
-         cout << "PLC " << htr0->Significance() << endl; 
-*/
 
-         FrequentistCalculator *ftc = new FrequentistCalculator(*data, *sbModel, *bModel);
-         ftc->SetToys(5000, 1000);
-         ftc->SetConditionalMLEsNull(w->set("nuis"));
-         ftc->SetConditionalMLEsAlt(w->set("nuis"));
+         FrequentistCalculator *ftc = new FrequentistCalculator(*combData, *sbModel, *bModel);
+         ftc->SetToys(50000, 1000);
+         //   ftc->SetConditionalMLEsNull(w->set("nuis"));
+         //   ftc->SetConditionalMLEsAlt(w->set("nuis"));
          ToyMCSampler *tmcs = (ToyMCSampler *)ftc->GetTestStatSampler();
-         tmcs->SetNEventsPerToy(1); // because the model is in number counting form     
-         tmcs->SetUseMultiGen(kTRUE);
+         tmcs->SetNEventsPerToy(1); // because the model is in number counting form
          tmcs->SetAlwaysUseMultiGen(kTRUE);
-         
+
+         HypoTestResult *htr;
+         ProfileLikelihoodCalculator *plc = new ProfileLikelihoodCalculator(*combData, *sbModel);
+         plc->SetNullParameters(*bModel->GetSnapshot());
+         htr = plc->GetHypoTest();
+         htr->Print();
+         cout << "PLC " << htr->Significance() << endl;
+
          tmcs->SetTestStatistic(slrts);
-         HypoTestResult *htr = ftc->GetHypoTest();
+         htr = ftc->GetHypoTest();
          htr->Print();
          cout << "SLRTS " << htr->Significance() << endl;
          tmcs->SetTestStatistic(pllts);
@@ -1545,98 +1684,16 @@ public:
 
          delete ftc;
          delete htr;
-         delete w; // interesting why it doesn't work
-         delete data;
+         delete w;
       }
       return kTRUE ;
    }
 } ;
 
 
-class TestHypoTestCalculator3 : public RooUnitTest {
-public:
-   TestHypoTestCalculator3(TFile* refFile, Bool_t writeRef, Int_t verbose) : RooUnitTest("HypoTestCalculator Asymptotic - On / Off Problem", refFile, writeRef, verbose) {};
 
-//   Double_t vtol() { return 0.2; } // tolerance may be too big
 
-   Bool_t testCode() {
 
-      const Int_t xValue = 150;
-      const Int_t yValue = 100;
-      const Double_t tauValue = 1;
-      
-      if(_write == kTRUE) {
-
-         // register analytical Z_Bi value
-         Double_t Z_Bi = NumberCountingUtils::BinomialWithTauObsZ(xValue, yValue, tauValue);
-         regValue(Z_Bi, "thtc_significance_asymptotic");
-
-      } else {
-      
-         // Make model for prototype on/off problem
-         // Pois(x | s+b) * Pois(y | tau b )
-         RooWorkspace* w = new RooWorkspace("w", kTRUE);
-         w->factory("Poisson::on_pdf(x[150,0,500],sum::splusb(sig[0,0,100],bkg[100,0,300]))");
-         w->factory("Poisson::off_pdf(y[100,0,500],prod::taub(tau[1],bkg))");
-         w->factory("PROD::prod_pdf(on_pdf, off_pdf)");
-        
-         w->var("x")->setVal(xValue);
-         w->var("y")->setVal(yValue);
-         w->var("y")->setConstant();
-         w->var("tau")->setVal(tauValue);
-         w->var("tau")->setConstant();
-         // construct the Bayesian-averaged model (eg. a projection pdf)
-         // p'(x|s) = \int db p(x|s+b) * [ p(y|b) * prior(b) ]
-         //w->factory("PROJ::averagedModel(PROD::foo(on_pdf|bkg,off_pdf,prior),bkg)") ;
-
-         // define sets of variables obs={x} and poi={sig}
-         // x is the only observable in the main measurement and y is treated as a separate measurement,
-         // which is used to produce the prior that will be used in the calculation to randomize the nuisance parameters
-         w->defineSet("obs", "x");
-         w->defineSet("poi", "sig");
-         w->defineSet("globObs", "y");
-
-         // Add observable value to a data set
-         RooDataSet *data = new RooDataSet("data", "data", *w->set("obs"));
-         data->add(*w->set("obs"));
-
-         // Build S+B and B models
-         ModelConfig *sbModel = new ModelConfig("SB_ModelConfig", w);
-         sbModel->SetPdf(*w->pdf("prod_pdf"));
-         sbModel->SetObservables(*w->set("obs"));
-       //  sbModel->SetGlobalObservables(*w->set("globObs"));      
-         sbModel->SetParametersOfInterest(*w->set("poi"));
-         w->var("sig")->setVal(xValue - yValue / tauValue); // important !
-         sbModel->SetSnapshot(*w->set("poi"));
-
-         ModelConfig *bModel = new ModelConfig("B_ModelConfig", w);
-         bModel->SetPdf(*w->pdf("prod_pdf"));
-         bModel->SetObservables(*w->set("obs"));
-       //  bModel->SetGlobalObservables(*w->set("globObs"));
-         bModel->SetParametersOfInterest(*w->set("poi"));
-         w->var("sig")->setVal(0.0); // important !
-         bModel->SetSnapshot(*w->set("poi"));
-
-
-         // alternate priors
-         w->factory("Gaussian::gauss_prior(bkg, y, expr::sqrty('sqrt(y)', y))");
-         w->factory("Lognormal::lognorm_prior(bkg, y, expr::kappa('1+1./sqrt(y)',y))");
-
-         AsymptoticCalculator *atc = new AsymptoticCalculator(*data, *sbModel, *bModel);
-         
-         HypoTestResult *htr = atc->GetHypoTest();
-         htr->Print();
-        
-         regValue(htr->Significance(), "thtc_significance_asymptotic");
-
-         delete atc;
-         delete htr;
-         delete w; // interesting why it doesn't work
-         delete data;
-      }
-      return kTRUE ;
-   }
-} ;
 
 
 
@@ -1649,7 +1706,7 @@ private:
 
 public:
    TestHypoTestInverter2(TFile* refFile, Bool_t writeRef, Int_t verbose, HypoTestInverter::ECalculatorType calculatorType, ETestStatType /* testStatType */) : RooUnitTest(TString::Format("HypoTestInverter Upper Limit - Poisson Model with Signal, Background and Efficiency - Calculator Type %d", calculatorType), refFile, writeRef, verbose) {
-      fCalculatorType = calculatorType;  
+      fCalculatorType = calculatorType;
    };
 
    Bool_t testCode() {
@@ -1666,12 +1723,12 @@ public:
       HypoTestInverter *hti = new HypoTestInverter(*w->data("data"), *sbModel, *bModel, w->var("x"), fCalculatorType, testSize);
       hti->SetFixedScan(10, 0, 20);
       hti->UseCLs(kTRUE);
-      
-      if(fCalculatorType == HypoTestInverter::kAsymptotic && _verb == 0) {
+
+      if (fCalculatorType == HypoTestInverter::kAsymptotic && _verb == 0) {
          AsymptoticCalculator::SetPrintLevel(0); // print only minimal output
       }
 
-      if(fCalculatorType == HypoTestInverter::kHybrid) {
+      if (fCalculatorType == HypoTestInverter::kHybrid) {
          // force prior nuisance pdf
          HybridCalculator *hc = (HybridCalculator *)hti->GetHypoTestCalculator();
          w->factory("PROD::priorbkg(constrb, constre)");
@@ -1688,8 +1745,8 @@ public:
       tmcs->SetMaxToys(300);
       tmcs->SetNEventsPerToy(1);
       tmcs->SetTestStatistic(profll);
-//      tmcs->SetUseMultiGen(kTRUE); // make ToyMCSampler faster   
-  
+//      tmcs->SetUseMultiGen(kTRUE); // make ToyMCSampler faster
+
       // calculate interval and extract observed upper limit and expected upper limit (+- sigma)
       HypoTestInverterResult *interval = hti->GetInterval();
       regValue(interval->UpperLimit(), TString::Format("hti2_upper_limit_sig1_calc_%d", fCalculatorType));
@@ -1698,16 +1755,14 @@ public:
       regValue(interval->GetExpectedUpperLimit(1), TString::Format("hti2_exp_upper_limit+sigma_sig_calc_%d", fCalculatorType));
 
 
-      if(_verb >= 1) {
-         cout << "[" << interval->LowerLimit() << "," << interval->UpperLimit() << "]" << endl;
+      if (_verb >= 1) {
          HypoTestInverterPlot *plot = new HypoTestInverterPlot("HTI_Result_Plot", "HTI Upper Limit Scan", interval);
          TCanvas *c1 = new TCanvas("HypoTestInverter Scan");
          c1->SetLogy(false);
          plot->Draw("2CL CLb");
          c1->SaveAs(TString::Format("hti2 Upper Limit Scan - Calc %d.pdf", fCalculatorType));
 
- 
-         if(_verb == 2) {
+         if (_verb == 2) {
             const int n = interval->ArraySize();
             if (n > 0 && interval->GetResult(0)->GetNullDistribution()) {
                TCanvas *c2 = new TCanvas("Test Statistic Distributions", "", 2);
@@ -1719,7 +1774,7 @@ public:
                for (int i = 0; i < n; i++) {
                   if (n > 1) c2->cd(i + 1);
                   SamplingDistPlot *pl = plot->MakeTestStatPlot(i);
-                  if(pl == NULL) return kTRUE;
+                  if (pl == NULL) return kTRUE;
                   pl->SetLogYaxis(kTRUE);
                   pl->Draw();
                }
@@ -1741,33 +1796,34 @@ public:
 #include "RooStats/MaxLikelihoodEstimateTestStat.h"
 #include "RooStats/NumEventsTestStat.h"
 
-static TestStatistic *buildTestStatistic(const ETestStatType testStatType, const ModelConfig &sbModel, const ModelConfig &bModel) {
+static TestStatistic *buildTestStatistic(const ETestStatType testStatType, const ModelConfig &sbModel, const ModelConfig &bModel)
+{
 
    TestStatistic *testStat = NULL;
- 
-   if(testStatType == kSimpleLR) {
+
+   if (testStatType == kSimpleLR) {
       SimpleLikelihoodRatioTestStat *slrts = new SimpleLikelihoodRatioTestStat(*sbModel.GetPdf(), *bModel.GetPdf());
       slrts->SetNullParameters(*sbModel.GetSnapshot());
       slrts->SetAltParameters(*bModel.GetSnapshot());
-      slrts->SetReuseNLL(kTRUE);
+      slrts->SetAlwaysReuseNLL(kTRUE);
       testStat = slrts;
-   } else if(testStatType == kRatioLR)  {
-      RatioOfProfiledLikelihoodsTestStat *roplts = 
+   } else if (testStatType == kRatioLR)  {
+      RatioOfProfiledLikelihoodsTestStat *roplts =
          new RatioOfProfiledLikelihoodsTestStat(*sbModel.GetPdf(), *bModel.GetPdf(), bModel.GetSnapshot());
-      roplts->SetReuseNLL(kTRUE);
+      roplts->SetAlwaysReuseNLL(kTRUE);
       testStat = roplts;
-   } else if(testStatType == kMLE) {
-      MaxLikelihoodEstimateTestStat *mlets = 
+   } else if (testStatType == kMLE) {
+      MaxLikelihoodEstimateTestStat *mlets =
          new MaxLikelihoodEstimateTestStat(*sbModel.GetPdf(), *((RooRealVar *)sbModel.GetParametersOfInterest()->first()));
       testStat = mlets;
-   } else if(testStatType == kNObs) {
+   } else if (testStatType == kNObs) {
       NumEventsTestStat *nevtts = new NumEventsTestStat(*sbModel.GetPdf());
       testStat = nevtts;
    } else { // kProfileLR, kProfileLROneSided and kProfileLRSigned
       ProfileLikelihoodTestStat *plts = new ProfileLikelihoodTestStat(*sbModel.GetPdf());
-      if(testStatType == kProfileLROneSided) plts->SetOneSided(kTRUE);
-      if(testStatType == kProfileLRSigned) plts->SetSigned(kTRUE);      
-      plts->SetReuseNLL(kTRUE);
+      if (testStatType == kProfileLROneSided) plts->SetOneSided(kTRUE);
+      if (testStatType == kProfileLRSigned) plts->SetSigned(kTRUE);
+      plts->SetAlwaysReuseNLL(kTRUE);
       testStat = plts;
    }
 
diff --git a/tree/doc/v534/index.html b/tree/doc/v534/index.html
index da3815a..edcebf2 100644
--- a/tree/doc/v534/index.html
+++ b/tree/doc/v534/index.html
@@ -10,5 +10,81 @@ Multiple <tt>TTreeCache</tt> per <tt>TFile</tt> for reading are supported by usi
 In addition, a <tt>TTreeCache</tt> for a <tt>TTree</tt> can be added using <tt>TFile::SetCacheRead(TFileCacheRead*, TObject*)</tt>, where the second (optional) argument is a pointer to the <tt>TTree</tt>. The cache can be removed by setting the pointer to 0.  In that case the user will have to take ownership for the cache.<p/>
 Similarily, a pointer to the <tt>TTreeCache</tt> for a <tt>TTree</tt> can be obtained using <tt>TFile::GetCacheRead(TObject*)</tt>.
 </li>
+<li>In <tt>TBuffer::Expand</tt>, when shrinking the buffer do not shrink below the size of the
+data already accumulated in the buffer (i. no less than the value of <tt>TBuffer::Length</tt>).
+<p/>
+In <tt>TBranch::SetBasketSize</tt>, instead of using the hard minimum of 100, use
+100 + the length of the branch name (as 100 is too small to hold the 
+basket's key information for any branch name larger than 30 characters).</li>
+
+</ul>
+
+<h4>Reading form text file</h4>
+
+Reworked <tt>TTree::ReadStream</tt> and <tt>TTree::ReadFile</tt> mainly to fix delimited reading of string columns:
+<ul>
+<li><tt>TLeaf::ReadValue</tt> now takes an optional delimiter argument that is ignored for all but TLeafC. Here, input stops when reading this character, instead of at the first whitespace.
+Use that in TTree::ReadStream() to delimit reading of TLeafC.</li>
+<li><tt>TTree::ReadStream</tt> now tokenizes the row itself, and passes a stringstream containing nothing but the current column to <tt>TLeaf::ReadValue</tt>.</li>
+<li>Separate concepts of number of input line (for communication with user) and number of good lines (as returned).</li>
+<li>Fix windows files leaving '\n' in branch names when reading them from the file.</li>
+<li>Add error message for TLeaf::ReadValue(), i.e. if ReadValue() is called on a derived class that doesn't implement it.</li>
+<li>Updated and clarified the documentation</li>
+</ul>
+
+<h4>TEntryList</h4>
+<ul>
+<li>Add new methods to find the base location of files and to modify it.
+  This allows to relocate the entry-lists to be able to use them of a
+  system where the files have a different absolute path.
+  The most relevant new methods are:
+<ul>
+    <li><tt>TEntryList::Scan(const char *fn)</tt>
+      Shows the root common paths for the files of the TEntryLists in 'fn'</li>
+    <li><pre lang="cxx">TEntryList::Relocate(const char *fn, const char *newroot,
+                           const char *oldroot = 0, const char *enlnm = 0)</pre>
+      Relocates all paths starting with 'oldroot' to 'newroot' for the
+      entry-list 'enlnm' in file 'fn'.</li>
 </ul>
+</li>
+<li>Remove 'protocol+server' from file tagging and matching, i.e. use
+  only filepath+anchor; in this way a list is valid even after re-staging
+  of the dataset files, which typically changes the end-point data servers.</li>
+<li>Entry-lists created with the full path should still be matched correctly.</li>
+</ul>
+
+<h4>Miscellaneous</h4>
+<ul>
+<li>Repaired the behavior of <tt>TTreeCache</tt> when the TTree has a dramatic dynamic range with a lots of very small entriesat the beginning and very large entries at the end, the size in bytes of the cluster for the later entries will be very large (because of the cluster size in entries is large!).  TTreeCache::FillBuffer was always attempting to load complete clusters not matter the
+size (even with the size was larger than 2GB!).
+
+This patch resolves the issue by limiting the amount of memory used to:
+<ol>
+<li>The requested size if more than one cluster fits in the cache.</li>
+<li>Twice the requested size if at least one basket per branch fits in the cache.</li>
+<li>Four time the requested size in the case where the cache can not even hold one basket per branch.</li>
+</ol>
+The filling will restart at the next cluster boundary in the case a) and will
+restart at the maximum of entry number read in the cache in the case b) and c).
+Baskets that are below this boundary and did not fit in the cache will be read
+individually.</li>
+<li>Repaired the basket flushing frequency when the <tt>TTree</tt> has already more than one cluster size.</li>
+<li>Repaired binning of string histogram generated by  <tt>TTree::Draw.</tt></li>
+<li>Many bug fixes and fix for issues discovery by Coverity, see change log for more details.</li>
+<li>In <tt>TTree::MakeProxy</tt> add proper support for top level stl collection of objects and for stl collection of objects that are 'empty' in the file (and thus we know nothing about its content).</li>
+<li>Avoid deficiency in <tt>hadd</tt>  when the resulting <tt>TTree</tt> is longer than the <tt>AutoSave</tt> length *and* the <tt>TFileMerger</tt> needs to handle the input files in more than one pass for example when there is more than 1000 input files or the -n option is passed to <tt>hadd</tt>.</li>
+<li>Fix support for emulated class that derived from an abstract class.
+This can happen when reading a file containing an ancient
+class layout where the derived class is no longer provided in the
+compiled code but the abstract base class is still provided.
+
+It also happens when using schema evolution rules on a class derived
+from an abstract base class (in which case the system introduce 
+implicitly an emulated class deriving from the same base classes
+as the evolved from class).  To fix the issue, we introduce the <tt>TClass::GetStreamerInfoAbstractEmulated</tt>
+which will return a StreamerInfo representing an emulated version of the
+class even if it is loaded.</li>
+
+</ul>
+
 
diff --git a/tree/tree/inc/TTree.h b/tree/tree/inc/TTree.h
index ecbec55..783423e 100644
--- a/tree/tree/inc/TTree.h
+++ b/tree/tree/inc/TTree.h
@@ -1,4 +1,4 @@
-// @(#)root/tree:$Id: TTree.h 43700 2012-04-11 17:03:45Z pcanal $
+// @(#)root/tree:$Id: TTree.h 44280 2012-05-18 06:05:10Z pcanal $
 // Author: Rene Brun   12/01/96
 
 /*************************************************************************
@@ -483,7 +483,7 @@ public:
    virtual Long64_t        Scan(const char* varexp = "", const char* selection = "", Option_t* option = "", Long64_t nentries = 1000000000, Long64_t firstentry = 0); // *MENU*
    virtual Bool_t          SetAlias(const char* aliasName, const char* aliasFormula);
    virtual void            SetAutoSave(Long64_t autos = 300000000);
-   virtual void            SetAutoFlush(Long64_t autof = 30000000);
+   virtual void            SetAutoFlush(Long64_t autof = -30000000);
    virtual void            SetBasketSize(const char* bname, Int_t buffsize = 16000);
 #if !defined(__CINT__)
    virtual Int_t           SetBranchAddress(const char *bname,void *add, TBranch **ptr = 0);
diff --git a/tree/tree/src/TTree.cxx b/tree/tree/src/TTree.cxx
index 8847a1e..89cebe9 100644
--- a/tree/tree/src/TTree.cxx
+++ b/tree/tree/src/TTree.cxx
@@ -1,4 +1,4 @@
-// @(#)root/tree:$Id: TTree.cxx 44005 2012-04-28 21:28:58Z pcanal $
+// @(#)root/tree:$Id: TTree.cxx 44280 2012-05-18 06:05:10Z pcanal $
 // Author: Rene Brun   12/01/96
 
 /*************************************************************************
@@ -4093,7 +4093,7 @@ Int_t TTree::Fill()
             if (fAutoSave!=0 && fEntries >= fAutoSave) AutoSave();    // FlushBaskets not called in AutoSave
             if (gDebug > 0) Info("TTree::Fill","First AutoFlush.  fAutoFlush = %lld, fAutoSave = %lld\n", fAutoFlush, fAutoSave);
          }
-      } else if (fNClusterRange && fAutoFlush && (fEntries-fClusterRangeEnd[fNClusterRange-1]) % fAutoFlush) {
+      } else if (fNClusterRange && fAutoFlush && ( (fEntries-fClusterRangeEnd[fNClusterRange-1]) % fAutoFlush == 0)  ) {
          if (fAutoSave != 0 && fEntries%fAutoSave == 0) {
             //We are at an AutoSave point. AutoSave flushes baskets and saves the Tree header
             AutoSave("flushbaskets");
@@ -6687,15 +6687,16 @@ void TTree::Reset(Option_t* option)
 {
    // Reset baskets, buffers and entries count in all branches and leaves.
 
-   fNotify = 0;
-   fEntries = 0;
+   fNotify        = 0;
+   fEntries       = 0;
    fNClusterRange = 0;
-   fTotBytes = 0;
-   fZipBytes = 0;
-   fSavedBytes = 0;
-   fTotalBuffers = 0;
-   fChainOffset = 0;
-   fReadEntry = -1;
+   fTotBytes      = 0;
+   fZipBytes      = 0;
+   fFlushedBytes  = 0;
+   fSavedBytes    = 0;
+   fTotalBuffers  = 0;
+   fChainOffset   = 0;
+   fReadEntry     = -1;
 
    delete fTreeIndex;
    fTreeIndex = 0;
@@ -6721,6 +6722,7 @@ void TTree::ResetAfterMerge(TFileMergeInfo *info)
    fTotBytes      = 0;
    fZipBytes      = 0;
    fSavedBytes    = 0;
+   fFlushedBytes  = 0;
    fTotalBuffers  = 0;
    fChainOffset   = 0;
    fReadEntry     = -1;
@@ -6835,7 +6837,7 @@ Bool_t TTree::SetAlias(const char* aliasName, const char* aliasFormula)
 }
 
 //_______________________________________________________________________
-void TTree::SetAutoFlush(Long64_t autof)
+void TTree::SetAutoFlush(Long64_t autof /* = -30000000 */ )
 {
    // This function may be called at the start of a program to change
    // the default value for fAutoFlush.
diff --git a/tree/treeplayer/src/TTreeFormula.cxx b/tree/treeplayer/src/TTreeFormula.cxx
index cbaa9e5..f5c1d2b 100644
--- a/tree/treeplayer/src/TTreeFormula.cxx
+++ b/tree/treeplayer/src/TTreeFormula.cxx
@@ -1,4 +1,4 @@
-// @(#)root/treeplayer:$Id: TTreeFormula.cxx 43993 2012-04-27 16:23:16Z pcanal $
+// @(#)root/treeplayer:$Id: TTreeFormula.cxx 44313 2012-05-26 03:24:37Z pcanal $
 // Author: Rene Brun   19/01/96
 
 /*************************************************************************
@@ -4884,6 +4884,9 @@ void TTreeFormula::SetAxis(TAxis *axis)
          R__ASSERT(subform);
          subform->SetAxis(axis);
       }
+      // Since the bin are corresponding to 'string', we currently must also set
+      // the axis to align the bins exactly on integer boundaries.
+      axis->SetBit(TAxis::kIsInteger);
    } else if (IsInteger()) {
       axis->SetBit(TAxis::kIsInteger);
    }
diff --git a/tutorials/roostats/OneSidedFrequentistUpperLimitWithBands.C b/tutorials/roostats/OneSidedFrequentistUpperLimitWithBands.C
index d268163..c1f961e 100644
--- a/tutorials/roostats/OneSidedFrequentistUpperLimitWithBands.C
+++ b/tutorials/roostats/OneSidedFrequentistUpperLimitWithBands.C
@@ -116,6 +116,7 @@ This version does not deal with this issue, but it will be addressed in a future
 #include "RooStats/PointSetInterval.h"
 #include "RooStats/ConfidenceBelt.h"
 
+#include "RooStats/RooStatsUtils.h"
 #include "RooStats/ProfileLikelihoodTestStat.h"
 
 using namespace RooFit;
diff --git a/tutorials/roostats/StandardFrequentistDiscovery.C b/tutorials/roostats/StandardFrequentistDiscovery.C
new file mode 100644
index 0000000..0254cac
--- /dev/null
+++ b/tutorials/roostats/StandardFrequentistDiscovery.C
@@ -0,0 +1,212 @@
+// StandardFrequentistDiscovery
+
+/*
+ StandardFrequentistDiscovery
+
+ Author: Sven Kreiss, Kyle Cranmer
+ date: May 2012
+
+ This is a standard demo that can be used with any ROOT file
+ prepared in the standard way.  You specify:
+ - name for input ROOT file
+ - name of workspace inside ROOT file that holds model and data
+ - name of ModelConfig that specifies details for calculator tools
+ - name of dataset
+
+ With default parameters the macro will attempt to run the
+ standard hist2workspace example and read the ROOT file
+ that it produces.
+ */
+
+#include "TFile.h"
+#include "TROOT.h"
+#include "TH1F.h"
+#include "TF1.h"
+#include "TCanvas.h"
+#include "TStopwatch.h"
+
+#include "RooWorkspace.h"
+#include "RooAbsData.h"
+#include "RooRandom.h"
+#include "RooRealSumPdf.h"
+#include "RooNumIntConfig.h"
+
+#include "RooStats/ModelConfig.h"
+#include "RooStats/ToyMCImportanceSampler.h"
+#include "RooStats/HypoTestResult.h"
+#include "RooStats/HypoTestPlot.h"
+#include "RooStats/SamplingDistribution.h"
+#include "RooStats/ProfileLikelihoodTestStat.h"
+#include "RooStats/SimpleLikelihoodRatioTestStat.h"
+#include "RooStats/ProfileLikelihoodCalculator.h"
+#include "RooStats/LikelihoodInterval.h"
+#include "RooStats/LikelihoodIntervalPlot.h"
+
+#include "RooStats/FrequentistCalculator.h"
+
+#include <vector>
+
+using namespace RooFit;
+using namespace RooStats;
+
+
+
+
+double StandardFrequentistDiscovery(
+   const char* infile = "",
+   const char* workspaceName = "channel1",
+   const char* modelConfigNameSB = "ModelConfig",
+   const char* dataName = "obsData",
+   int toys = 1000,
+   double poiValueForBackground = 0.0,
+   double poiValueForSignal = 1.0
+) {
+
+   // The workspace contains the model for s+b. The b model is "autogenerated"
+   // by copying s+b and setting the one parameter of interest to zero.
+   // To keep the script simple, multiple parameters of interest or different
+   // functional forms of the b model are not supported.
+
+   // for now, assume there is only one parameter of interest, and these are
+   // its values:
+
+   /////////////////////////////////////////////////////////////
+   // First part is just to access a user-defined file
+   // or create the standard example file if it doesn't exist
+   ////////////////////////////////////////////////////////////
+   const char* filename = "";
+   if (!strcmp(infile, "")) filename = "results/example_channel1_GammaExample_model.root";
+   else filename = infile;
+   // Check if example input file exists
+   TFile *file = TFile::Open(filename);
+
+   // if input file was specified but not found, quit
+   if (!file && strcmp(infile, "")) {
+      cout << "file not found" << endl;
+   }
+
+   // if default file not found, try to create it
+   if (!file) {
+      // Normally this would be run on the command line
+      cout << "will run standard hist2workspace example" << endl;
+      gROOT->ProcessLine(".! prepareHistFactory .");
+      gROOT->ProcessLine(".! hist2workspace config/example.xml");
+      cout << "\n\n---------------------" << endl;
+      cout << "Done creating example input" << endl;
+      cout << "---------------------\n\n" << endl;
+   }
+
+   // now try to access the file again
+   file = TFile::Open(filename);
+   if (!file) {
+      // if it is still not there, then we can't continue
+      cout << "Not able to run hist2workspace to create example input" << endl;
+      return -1.0;
+   }
+
+   /////////////////////////////////////////////////////////////
+   // Tutorial starts here
+   ////////////////////////////////////////////////////////////
+
+   TStopwatch *mn_t = new TStopwatch;
+   mn_t->Start();
+
+   // get the workspace out of the file
+   RooWorkspace* w = (RooWorkspace*) file->Get(workspaceName);
+   if (!w) {
+      cout << "workspace not found" << endl;
+      return -1.0;
+   }
+
+   // get the modelConfig out of the file
+   ModelConfig* mc = (ModelConfig*) w->obj(modelConfigNameSB);
+
+   // get the data out of the file
+   RooAbsData* data = w->data(dataName);
+
+   // make sure ingredients are found
+   if (!data || !mc) {
+      w->Print();
+      cout << "data or ModelConfig was not found" << endl;
+      return -1.0;
+   }
+
+
+   RooRealVar* firstPOI = (RooRealVar*) mc->GetParametersOfInterest()->first();
+   firstPOI->setVal(poiValueForSignal);
+   mc->SetSnapshot(*mc->GetParametersOfInterest());
+   // create null model
+   ModelConfig *mcNull = mc->Clone("ModelConfigNull");
+   firstPOI->setVal(poiValueForBackground);
+   mcNull->SetSnapshot(*(RooArgSet*)mcNull->GetParametersOfInterest()->snapshot());
+
+
+
+   // ----------------------------------------------------
+   // Configure a ProfileLikelihoodTestStat and a SimpleLikelihoodRatioTestStat
+   // to use simultaneously with ToyMCSampler
+   ProfileLikelihoodTestStat* plts =  new ProfileLikelihoodTestStat(*mc->GetPdf());
+   plts->SetOneSidedDiscovery(true);
+   plts->SetVarName( "q_{0}/2" );
+   
+   // ----------------------------------------------------
+   // configure the ToyMCImportanceSampler with two test statistics
+   ToyMCSampler toymcs(*plts, 50);
+
+
+
+   // Since this tool needs to throw toy MC the PDF needs to be
+   // extended or the tool needs to know how many entries in a dataset
+   // per pseudo experiment.
+   // In the 'number counting form' where the entries in the dataset
+   // are counts, and not values of discriminating variables, the
+   // datasets typically only have one entry and the PDF is not
+   // extended.
+   if (!mc->GetPdf()->canBeExtended()) {
+      if (data->numEntries() == 1) {
+         toymcs.SetNEventsPerToy(1);
+      } else cout << "Not sure what to do about this model" << endl;
+   }
+
+   // We can use PROOF to speed things along in parallel
+   // ProofConfig pc(*w, 2, "user at yourfavoriteproofcluster", false);
+   ProofConfig pc(*w, 2, "", false);
+   //toymcs.SetProofConfig(&pc);    // enable proof
+
+
+   // instantiate the calculator
+   FrequentistCalculator freqCalc(*data, *mc, *mcNull, &toymcs);
+   freqCalc.SetToys( toys,toys ); // null toys, alt toys
+
+   // Run the calculator and print result
+   HypoTestResult* freqCalcResult = freqCalc.GetHypoTest();
+   freqCalcResult->GetNullDistribution()->SetTitle( "b only" );
+   freqCalcResult->GetAltDistribution()->SetTitle( "s+b" );
+   freqCalcResult->Print();
+   double pvalue = freqCalcResult->NullPValue();
+
+   // stop timing
+   mn_t->Stop();
+   cout << "total CPU time: " << mn_t->CpuTime() << endl;
+   cout << "total real time: " << mn_t->RealTime() << endl;
+
+   // plot
+   TCanvas* c1 = new TCanvas();
+   HypoTestPlot *plot = new HypoTestPlot(*freqCalcResult, 100, -0.49, 9.51 );
+   plot->SetLogYaxis(true);
+   
+   // add chi2 to plot
+   int nPOI = 1;
+   TF1* f = new TF1("f", TString::Format("1*ROOT::Math::chisquared_pdf(2*x,%d,0)",nPOI), 0,20);
+   f->SetLineColor( kBlack );
+   f->SetLineStyle( 7 );
+   plot->AddTF1( f, TString::Format("#chi^{2}(2x,%d)",nPOI) );
+   
+   plot->Draw();
+   c1->SaveAs("standard_discovery_output.pdf");
+   
+
+   return pvalue;
+}
+
+
diff --git a/tutorials/roostats/StandardHypoTestDemo.C b/tutorials/roostats/StandardHypoTestDemo.C
index b268ff5..d5497de 100644
--- a/tutorials/roostats/StandardHypoTestDemo.C
+++ b/tutorials/roostats/StandardHypoTestDemo.C
@@ -237,9 +237,6 @@ void StandardHypoTestDemo(const char* infile = "",
    RooArgSet nullParams(*bModel->GetSnapshot());
    if (bModel->GetNuisanceParameters()) nullParams.add(*bModel->GetNuisanceParameters());
    
-   cout << "MODEL PARAMETERS ! " << endl;
-   nullParams.Print("v");
-
    slrts->SetNullParameters(nullParams);
    RooArgSet altParams(*sbModel->GetSnapshot());
    if (sbModel->GetNuisanceParameters()) altParams.add(*sbModel->GetNuisanceParameters());
@@ -273,9 +270,11 @@ void StandardHypoTestDemo(const char* infile = "",
    if (calcType == 1) 
        ((HybridCalculator*)hypoCalc)->SetToys(ntoys, ntoys/nToysRatio);
    if (calcType == 2 ) { 
-      //if (testStatType == 3) ((AsymptoticCalculator*) hypoCalc)->SetOneSided(true);  
+      if (testStatType == 3) ((AsymptoticCalculator*) hypoCalc)->SetOneSidedDiscovery(true);  
       if (testStatType != 2 && testStatType != 3)  
          Warning("StandardHypoTestDemo","Only the PL test statistic can be used with AsymptoticCalculator - use by default a two-sided PL");
+      
+
    }
 
 
diff --git a/tutorials/roostats/StandardHypoTestInvDemo.C b/tutorials/roostats/StandardHypoTestInvDemo.C
index 194aa0d..02e0b68 100644
--- a/tutorials/roostats/StandardHypoTestInvDemo.C
+++ b/tutorials/roostats/StandardHypoTestInvDemo.C
@@ -404,8 +404,6 @@ RooStats::HypoTestInvTool::AnalyzeResult( HypoTestInverterResult * r,
    // analyze result produced by the inverter, optionally save it in a file 
    
   
-   double upperLimit = r->UpperLimit();
-   double ulError = r->UpperLimitEstimatedError();
    double lowerLimit = 0;
    double llError = 0;
 #if defined ROOT_SVN_VERSION &&  ROOT_SVN_VERSION >= 44126
@@ -414,14 +412,20 @@ RooStats::HypoTestInvTool::AnalyzeResult( HypoTestInverterResult * r,
       llError = r->LowerLimitEstimatedError();
    }
 #else
-      lowerLimit = r->LowerLimit();
-      llError = r->LowerLimitEstimatedError();
+   lowerLimit = r->LowerLimit();
+   llError = r->LowerLimitEstimatedError();
 #endif
+
+   double upperLimit = r->UpperLimit();
+   double ulError = r->UpperLimitEstimatedError();
+
+   //std::cout << "DEBUG : [ " << lowerLimit << " , " << upperLimit << "  ] " << std::endl;
       
    if (lowerLimit < upperLimit*(1.- 1.E-4) && lowerLimit != 0) 
       std::cout << "The computed lower limit is: " << lowerLimit << " +/- " << llError << std::endl;
    std::cout << "The computed upper limit is: " << upperLimit << " +/- " << ulError << std::endl;
   
+
    // compute expected limit
    std::cout << "Expected upper limits, using the B (alternate) model : " << std::endl;
    std::cout << " expected limit (median) " << r->GetExpectedUpperLimit(0) << std::endl;
@@ -756,15 +760,21 @@ RooStats::HypoTestInvTool::RunInverter(RooWorkspace * w,
   
    ToyMCSampler *toymcs = (ToyMCSampler*)hc->GetTestStatSampler();
    if (toymcs && (type == 0 || type == 1) ) { 
-      // for not extended pdf
-      if (!useNumberCounting)  { 
-         int nEvents = data->numEntries();
-         Info("StandardHypoTestInvDemo","Pdf is not extended: number of events to generate taken  from observed data set is %d",nEvents);
-         toymcs->SetNEventsPerToy(nEvents);
+      // look if pdf is number counting or extended
+      if (sbModel->GetPdf()->canBeExtended() ) { 
+         if (useNumberCounting)   Warning("StandardHypoTestInvDemo","Pdf is extended: but number counting flag is set: ignore it ");
       }
-      else {
-         Info("StandardHypoTestInvDemo","using a number counting pdf");
-         toymcs->SetNEventsPerToy(1);
+      else { 
+         // for not extended pdf
+         if (!useNumberCounting  )  { 
+            int nEvents = data->numEntries();
+            Info("StandardHypoTestInvDemo","Pdf is not extended: number of events to generate taken  from observed data set is %d",nEvents);
+            toymcs->SetNEventsPerToy(nEvents);
+         }
+         else {
+            Info("StandardHypoTestInvDemo","using a number counting pdf");
+            toymcs->SetNEventsPerToy(1);
+         }
       }
 
       toymcs->SetTestStatistic(testStat);
diff --git a/tutorials/roostats/StandardProfileInspectorDemo.C b/tutorials/roostats/StandardProfileInspectorDemo.C
index d6f036d..216ff6b 100644
--- a/tutorials/roostats/StandardProfileInspectorDemo.C
+++ b/tutorials/roostats/StandardProfileInspectorDemo.C
@@ -29,6 +29,7 @@ of each nuisance parameter in the model vs. the parameter of interest.
 #include "TROOT.h"
 #include "TCanvas.h"
 #include "TList.h"
+#include "TMath.h"
 #include "RooWorkspace.h"
 #include "RooAbsData.h"
 
@@ -112,14 +113,6 @@ void StandardProfileInspectorDemo(const char* infile = "",
   
   // now make plots
   TCanvas* c1 = new TCanvas("c1","ProfileInspectorDemo",800,200);
-  c1->Divide(list->GetSize());
-  for(int i=0; i<list->GetSize(); ++i){
-    c1->cd(i+1);
-    list->At(i)->Draw("al");
-  }
-
-  // now make plots
-  TCanvas* c1 = new TCanvas("c1","ProfileInspectorDemo",800,200);
   if(list->GetSize()>4){
     double n = list->GetSize();
     int nx = (int)sqrt(n) ;
@@ -133,5 +126,5 @@ void StandardProfileInspectorDemo(const char* infile = "",
     list->At(i)->Draw("al");
   }
   
-  
+  cout << endl;
 }
diff --git a/tutorials/roostats/TwoSidedFrequentistUpperLimitWithBands.C b/tutorials/roostats/TwoSidedFrequentistUpperLimitWithBands.C
index 3803634..79ee489 100644
--- a/tutorials/roostats/TwoSidedFrequentistUpperLimitWithBands.C
+++ b/tutorials/roostats/TwoSidedFrequentistUpperLimitWithBands.C
@@ -112,6 +112,7 @@ This results in thresholds that become very large.
 #include "RooStats/PointSetInterval.h"
 #include "RooStats/ConfidenceBelt.h"
 
+#include "RooStats/RooStatsUtils.h"
 #include "RooStats/ProfileLikelihoodTestStat.h"
 
 using namespace RooFit;

-- 
root-system: CERN's ROOT Data Analysis Framework



More information about the debian-science-commits mailing list