diff --git a/CMakeLists.txt b/CMakeLists.txt
index 848c2f6a051a940675b0c700e11e45482e02431a..dde52f766b5cbdd41817fa8088e8687e501159f0 100644
--- a/CMakeLists.txt
+++ b/CMakeLists.txt
@@ -1,12 +1,15 @@
 CMAKE_MINIMUM_REQUIRED (VERSION 2.8.10)
 PROJECT (OPAL)
 SET (OPAL_VERSION_MAJOR 1)
-SET (OPAL_VERSION_MINOR 5.00.2)
+SET (OPAL_VERSION_MINOR 9.00)
 set (PACKAGE \"opal\")
 set (PACKAGE_BUGREPORT \"opal@lists.psi.ch\")
 set (PACKAGE_NAME \"OPAL\")
 set (PACKAGE_TARNAME \"opal\")
-set (PACKAGE_VERSION "\"${OPAL_VERSION_MAJOR}.${OPAL_VERSION_MINOR}\"")
+set (OPAL_VERSION "${OPAL_VERSION_MAJOR}.${OPAL_VERSION_MINOR}")
+STRING (REGEX REPLACE "\\.([0-9])\\." ".0\\1." PACKAGE_VERSION ${OPAL_VERSION})
+set (PACKAGE_VERSION_STR "\"${PACKAGE_VERSION}\"")
+STRING (REGEX REPLACE "\\." "" PACKAGE_VERSION ${PACKAGE_VERSION})
 
 IF (NOT CMAKE_CONFIGURATION_TYPES AND NOT CMAKE_BUILD_TYPE)
     SET (CMAKE_BUILD_TYPE RelWithDebInfo CACHE STRING
@@ -61,7 +64,7 @@ set (BOOSTROOT $ENV{BOOST_DIR})
 set(Boost_USE_STATIC_LIBS ON)
 set(Boost_USE_MULTITHREADED OFF)
 set(Boost_USE_STATIC_RUNTIME OFF)
-find_package (Boost 1.55.0 REQUIRED COMPONENTS  regex filesystem system)
+find_package (Boost 1.54.0 REQUIRED COMPONENTS  regex filesystem system iostreams)
 if (Boost_INCLUDE_DIRS)
     message (STATUS "Found boost include dir: ${Boost_INCLUDE_DIR}")
     message (STATUS "Found boost library dir: ${Boost_LIBRARY_DIR}")
@@ -85,7 +88,7 @@ IF (ENABLE_DKS)
 
    ### CUDA compiler flags ###
    SET (CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -lcudart -lcufft -lcublas -lnvToolsExt -DDKS_CUDA")
-   
+
    ### if any accelerator enabled set flag to use DKS ###
    SET (CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -DIPPL_DKS -DIPPL_DKS_CUDA -DOPAL_DKS")
 ENDIF (ENABLE_DKS)
@@ -105,6 +108,11 @@ OPTION (NOCPLUSPLUS11_NULLPTR "Disable C++11 nullptr support" OFF)
 
 OPTION (NO_FIELD_ASSIGN_OPTIMIZATION "Disable compiler optimization of IPPL field assignment" OFF)
 
+IF (BUILD_OPAL_UNIT_TESTS)
+    FIND_PACKAGE (GTest REQUIRED)
+    SET (CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -DWITH_UNIT_TESTS")
+ENDIF (BUILD_OPAL_UNIT_TESTS)
+
 IF (USE_H5HUT2)
 	SET (CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -DUSE_H5HUT2")
 ENDIF (USE_H5HUT2)
@@ -161,8 +169,8 @@ STRING(REGEX MATCH "[^0-9]*" HOSTNAME_BASE "${HOSTNAME}")
 # cray-tpsl/16.06.1 libraries -> Linker error.
 # We can avoid this issue by not going into the if-statement
 if (NOT ${HOSTNAME_BASE} MATCHES "edison" AND NOT ${HOSTNAME_BASE} MATCHES "cori" AND (ENABLE_SAAMG_SOLVER OR ENABLE_AMR_SOLVER) )
-    MESSAGE ("Enable SAAMG_SOLVER  " ${ENABLE_SAAMG_SOLVER})
-    MESSAGE ("Enable AMR_SOLVER    " ${ENABLE_AMR_SOLVER})
+    MESSAGE (STATUS "Enable SAAMG_SOLVER  " ${ENABLE_SAAMG_SOLVER})
+    MESSAGE (STATUS "Enable AMR_SOLVER    " ${ENABLE_AMR_SOLVER})
     find_package (Trilinos REQUIRED HINTS $ENV{TRILINOS_PREFIX} $ENV{TRILINOS_DIR} $ENV{TRILINOS})
 
     message (STATUS "Found Trilinos: ${Trilinos_DIR}")
@@ -237,6 +245,8 @@ ENDIF()
 SET (IPPL_USED_FROM_OPAL "TRUE")
 ADD_SUBDIRECTORY (ippl)
 ADD_SUBDIRECTORY (src)
+ADD_SUBDIRECTORY (tools)
+ADD_SUBDIRECTORY (doc/user_guide)
 
 IF (BUILD_OPAL_UNIT_TESTS)
      ADD_SUBDIRECTORY(tests)
@@ -249,4 +259,4 @@ set(OPAL_CXX_FLAGS ${OPAL_CXX_FLAGS}
 
 set(OPAL_LIBS ${OPAL_LIBS}
          CACHE INTERNAL "" FORCE
-)
+)
\ No newline at end of file
diff --git a/CMakeModules/CCSEOptions.cmake b/CMakeModules/CCSEOptions.cmake
index 000edd083e875bfbd96491eab5422c2bf2b175ba..13f5917ae49b18e64f74532cf36aa963c1046aa1 100644
--- a/CMakeModules/CCSEOptions.cmake
+++ b/CMakeModules/CCSEOptions.cmake
@@ -21,7 +21,7 @@ elseif(FortranCInterface_GLOBAL_SUFFIX STREQUAL "_" AND FortranCInterface_GLOBAL
 #    message(STATUS "   Fortran name mangling scheme to UNDERSCORE (lower case, append underscore)")
     set(BL_FORTLINK "UNDERSCORE")
 #else()
-#    message(AUTHOR_WARNING "Fortran to C mangling not backward compatible with older style BoxLib code") 
+#    message(AUTHOR_WARNING "Fortran to C mangling not backward compatible with older style BoxLib code")
 endif()
 
 set(BL_MACHINE ${CMAKE_SYSTEM_NAME})
diff --git a/CMakeModules/FindCCSE.cmake b/CMakeModules/FindCCSE.cmake
index 45aaeae22007b03e7961d7e3b4cc8e0b29dcb81b..4575f4b936f0ba30911d61c13fd1ee00946e2636 100644
--- a/CMakeModules/FindCCSE.cmake
+++ b/CMakeModules/FindCCSE.cmake
@@ -6,7 +6,7 @@
 #    Control the search through CCSE_DIR or setting environment variable
 #    CCSE_ROOT to the ccse installation prefix.
 #
-#    This module does not search default paths! 
+#    This module does not search default paths!
 #
 #    Following variables are set:
 #    CCSE_FOUND            (BOOL)       Flag indicating if CCSE was found
@@ -46,12 +46,12 @@ else(CCSE_LIBRARIES AND CCSE_INCLUDE_DIRS AND CCSE_PERL_DIR)
     if(CCSE_LIBRARY_DIR)
         set(CCSE_LIBRARY_DIR "${CCSE_LIBRARY_DIR}" CACHE PATH "Path to search for CCSE library files")
     endif()
-    
+
     if(CCSE_PERL_DIR)
         set(CCSE_PERL_DIR "${CCSE_PERL_DIR}" CACHE PATH "Path to search for CCSE perl scripts")
     endif()
 
-    
+
     # Search for include files
     # Search order preference:
     #  (1) CCSE_INCLUDE_DIR - check existence of path AND if the include files exist
@@ -77,7 +77,7 @@ else(CCSE_LIBRARIES AND CCSE_INCLUDE_DIRS AND CCSE_PERL_DIR)
             set(CCSE_INCLUDE_DIR "CCSE_INCLUDE_DIR-NOTFOUND")
         endif()
 
-    else() 
+    else()
 
         set(ccse_inc_suffixes "include")
         if(CCSE_DIR)
@@ -93,7 +93,7 @@ else(CCSE_LIBRARIES AND CCSE_INCLUDE_DIRS AND CCSE_PERL_DIR)
             else()
                  message(SEND_ERROR "CCSE_DIR=${CCSE_DIR} does not exist")
                  set(CCSE_INCLUDE_DIR "CCSE_INCLUDE_DIR-NOTFOUND")
-            endif()    
+            endif()
 
 
         else()
@@ -112,7 +112,7 @@ else(CCSE_LIBRARIES AND CCSE_INCLUDE_DIRS AND CCSE_PERL_DIR)
         set(CCSE_INCLUDE_DIRS ${CCSE_INCLUDE_DIR})
     endif()
 
-    # Search for libraries 
+    # Search for libraries
     # Search order preference:
     #  (1) CCSE_LIBRARY_DIR - check existence of path AND if the include files exist
     #  (2) CCSE_DIR/<lib,Lib>
@@ -132,7 +132,7 @@ else(CCSE_LIBRARIES AND CCSE_INCLUDE_DIRS AND CCSE_PERL_DIR)
             set(CCSE_LIBRARY "CCSE_LIBRARY-NOTFOUND")
         endif()
 
-    else() 
+    else()
 
         if(CCSE_DIR)
 
@@ -148,7 +148,7 @@ else(CCSE_LIBRARIES AND CCSE_INCLUDE_DIRS AND CCSE_PERL_DIR)
             else()
                  message(SEND_ERROR "CCSE libs not found in CCSE_DIR/lib${CCSE_LIBDIR_MPI_SUFFIX}${CCSE_LIBDIR_OMP_SUFFIX}, (CCSE_DIR=${CCSE_DIR})")
                  set(CCSE_LIBRARY "CCSE_LIBRARY-NOTFOUND")
-            endif()    
+            endif()
 
         else()
 
@@ -156,7 +156,7 @@ else(CCSE_LIBRARIES AND CCSE_INCLUDE_DIRS AND CCSE_PERL_DIR)
                          NAMES ${ccse_lib_name})
 
             get_filename_component(CCSE_LIBRARY_DIR "${CCSE_LIBRARY}" PATH)
-            
+
         endif()
 
     endif()
@@ -199,7 +199,7 @@ else(CCSE_LIBRARIES AND CCSE_INCLUDE_DIRS AND CCSE_PERL_DIR)
             set(CCSE_PERL "CCSE_PERL-NOTFOUND")
         endif()
 
-    else() 
+    else()
 
         if(CCSE_DIR)
 
@@ -214,7 +214,7 @@ else(CCSE_LIBRARIES AND CCSE_INCLUDE_DIRS AND CCSE_PERL_DIR)
                     message(SEND_ERROR "CCSE Perl scripts not in CCSE_DIR/perl=${CCSE_DIR}/perl")
                 else()
                     set(CCSE_PERL_DIR ${CCSE_PERL})
-                endif()    
+                endif()
 
             else()
 
@@ -230,7 +230,7 @@ else(CCSE_LIBRARIES AND CCSE_INCLUDE_DIRS AND CCSE_PERL_DIR)
     set(CCSE_EXT_LIBRARIES "")
 
 
-endif(CCSE_LIBRARIES AND CCSE_INCLUDE_DIRS AND CCSE_PERL_DIR)    
+endif(CCSE_LIBRARIES AND CCSE_INCLUDE_DIRS AND CCSE_PERL_DIR)
 
 # Send useful message if everything is found
 find_package_handle_standard_args(CCSE DEFAULT_MSG
diff --git a/Doxyfile b/Doxyfile
index 8a95bed6b22201f788ca2b7a18fd1b1151c548ee..f43a8c101fa003e800bd4471bb8dadd5a7d16bf0 100644
--- a/Doxyfile
+++ b/Doxyfile
@@ -765,7 +765,8 @@ WARN_LOGFILE           =
 # Note: If this tag is empty the current directory is searched.
 
 INPUT                  = ./src \
-                         ./ippl
+                         ./src/Classic \
+                         ./ippl/src
 
 # This tag can be used to specify the character encoding of the source files
 # that doxygen parses. Internally doxygen uses the UTF-8 encoding. Doxygen uses
@@ -994,7 +995,6 @@ USE_HTAGS              = NO
 # The default value is: YES.
 
 VERBATIM_HEADERS       = YES
-
 #---------------------------------------------------------------------------
 # Configuration options related to the alphabetical class index
 #---------------------------------------------------------------------------
@@ -1772,7 +1772,6 @@ RTF_EXTENSIONS_FILE    =
 # classes and files.
 # The default value is: NO.
 
-GENERATE_MAN           = NO
 
 # The MAN_OUTPUT tag is used to specify where the man pages will be put. If a
 # relative path is entered the value of OUTPUT_DIRECTORY will be put in front of
@@ -1836,7 +1835,7 @@ XML_OUTPUT             = xml
 XML_PROGRAMLISTING     = YES
 
 #---------------------------------------------------------------------------
-# Configuration options related to the DOCBOOK output
+# Configuration options for the AutoGen Definitions output
 #---------------------------------------------------------------------------
 
 # If the GENERATE_DOCBOOK tag is set to YES doxygen will generate Docbook files
@@ -1983,7 +1982,7 @@ EXPAND_AS_DEFINED      =
 SKIP_FUNCTION_MACROS   = YES
 
 #---------------------------------------------------------------------------
-# Configuration options related to external references
+# Configuration additions related to external references
 #---------------------------------------------------------------------------
 
 # The TAGFILES tag can be used to specify one or more tag files. For each tag
@@ -2326,4 +2325,4 @@ GENERATE_LEGEND        = YES
 # The default value is: YES.
 # This tag requires that the tag HAVE_DOT is set to YES.
 
-DOT_CLEANUP            = YES
+DOT_CLEANUP            = YES
\ No newline at end of file
diff --git a/README.md b/README.md
index c7aaffa0cb1d85ed4c7de42d0a2ceed2a25565b0..4f2e7197bbecf02dd4c78f2d92019c6b3ab6daba 100644
--- a/README.md
+++ b/README.md
@@ -1 +1 @@
-OPAL 
\ No newline at end of file
+OPAL
\ No newline at end of file
diff --git a/hooks/post-applypatch b/hooks/post-applypatch
index 93a860979d1a1672ff7d6a4d833a3d1ed68f447e..625935049b7a5eb57a0fadd49a3f9b270163b5b0 100755
--- a/hooks/post-applypatch
+++ b/hooks/post-applypatch
@@ -6,8 +6,7 @@ echo "#define GIT_VERSION \"$REV\"" > revision.tmp
 diff revision.tmp src/revision.h 2>&1 > /dev/null
 
 if [ $? -eq 1 ];then
-   cp revision.tmp src/revision.h
-   mv revision.tmp classic/5.0/src/revision.h
+   mv revision.tmp src/revision.h
 else
    rm revision.tmp
 fi
\ No newline at end of file
diff --git a/hooks/post-checkout b/hooks/post-checkout
index 93a860979d1a1672ff7d6a4d833a3d1ed68f447e..625935049b7a5eb57a0fadd49a3f9b270163b5b0 100755
--- a/hooks/post-checkout
+++ b/hooks/post-checkout
@@ -6,8 +6,7 @@ echo "#define GIT_VERSION \"$REV\"" > revision.tmp
 diff revision.tmp src/revision.h 2>&1 > /dev/null
 
 if [ $? -eq 1 ];then
-   cp revision.tmp src/revision.h
-   mv revision.tmp classic/5.0/src/revision.h
+   mv revision.tmp src/revision.h
 else
    rm revision.tmp
 fi
\ No newline at end of file
diff --git a/hooks/post-commit b/hooks/post-commit
index 93a860979d1a1672ff7d6a4d833a3d1ed68f447e..625935049b7a5eb57a0fadd49a3f9b270163b5b0 100755
--- a/hooks/post-commit
+++ b/hooks/post-commit
@@ -6,8 +6,7 @@ echo "#define GIT_VERSION \"$REV\"" > revision.tmp
 diff revision.tmp src/revision.h 2>&1 > /dev/null
 
 if [ $? -eq 1 ];then
-   cp revision.tmp src/revision.h
-   mv revision.tmp classic/5.0/src/revision.h
+   mv revision.tmp src/revision.h
 else
    rm revision.tmp
 fi
\ No newline at end of file
diff --git a/hooks/post-merge b/hooks/post-merge
index 93a860979d1a1672ff7d6a4d833a3d1ed68f447e..625935049b7a5eb57a0fadd49a3f9b270163b5b0 100755
--- a/hooks/post-merge
+++ b/hooks/post-merge
@@ -6,8 +6,7 @@ echo "#define GIT_VERSION \"$REV\"" > revision.tmp
 diff revision.tmp src/revision.h 2>&1 > /dev/null
 
 if [ $? -eq 1 ];then
-   cp revision.tmp src/revision.h
-   mv revision.tmp classic/5.0/src/revision.h
+   mv revision.tmp src/revision.h
 else
    rm revision.tmp
 fi
\ No newline at end of file
diff --git a/ippl/CMakeLists.txt b/ippl/CMakeLists.txt
index f86819af20be4d39e9654e3062e2c8f86f088e81..90b9e96f33926f85ddedf45237c2831e42090696 100644
--- a/ippl/CMakeLists.txt
+++ b/ippl/CMakeLists.txt
@@ -76,7 +76,7 @@ IF (ENABLE_DKS)
 
    ### CUDA compiler flags ###
    SET (CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -lcudart -lcufft -lcublas -lnvToolsExt -DDKS_CUDA")
-   
+
    ### if any accelerator enabled set flag to use DKS ###
    SET (CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -DIPPL_DKS -DIPPL_DKS_CUDA -DOPAL_DKS")
 ENDIF (ENABLE_DKS)
@@ -99,19 +99,19 @@ OPTION (NO_FIELD_ASSIGN_OPTIMIZATION "Disable compiler optimization of IPPL fiel
 IF (ENABLE_AMR_SOLVER)
     # set specific parameters for BoxLib used in OPAL
     ENABLE_LANGUAGE (Fortran)
-    
+
     SET ( CCSE_DIR $ENV{BOXLIB_PREFIX} )
     SET ( CCSE_LIBRARY_DIR $ENV{BOXLIB_LIBRARY_DIR} )
-    
+
     FIND_PACKAGE (CCSE REQUIRED)
-    
+
     IF (CCSE_FOUND)
         MESSAGE (STATUS "Found BoxLib include dir: ${CCSE_INCLUDE_DIR}")
         MESSAGE (STATUS "Found BoxLib library dir: ${CCSE_LIBRARY_DIR}")
         MESSAGE (STATUS "Found BoxLib perl dir: ${CCSE_PERL_DIR}")
         INCLUDE_DIRECTORIES (${CCSE_INCLUDE_DIR})
     ENDIF (CCSE_FOUND)
-    
+
     SET (BL_SPACEDIM 3 CACHE INT "Dimension of BoxLib build")
     SET (ENABLE_MPI 1 CACHE INT "Enable build with MPI")
     SET (ENABLE_OpenMP 0 CACHE INT "Enable build with OpenMP")
@@ -119,10 +119,10 @@ IF (ENABLE_AMR_SOLVER)
     SET (BL_USE_PARTICLES 1 CACHE INT "Include Particles classes in BoxLib build")
     SET (ENABLE_PROFILING 0 CACHE INT "Include profiling information in BoxLib build")
     SET (ENABLE_BACKTRACE 0 CACHE INT "Include backtrace information in BoxLib build")
-    
+
     # disable due to BoxLib
     SET (CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -Wno-unused-variable")
-    
+
     SET (CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -DBL_PRECISION=${BL_PRECISION}")
     SET (CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -DENABLE_MPI=${ENABLE_MPI}")
     SET (CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -DENABLE_OpenMP=${ENABLE_OpenMP}")
@@ -130,7 +130,7 @@ IF (ENABLE_AMR_SOLVER)
     SET (CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -DBL_DEBUG=${BL_DEBUG}")
     SET (CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -DENABLE_BACKTRACE=${ENABLE_BACKTRACE}")
     SET (CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -DENABLE_PROFILING=${ENABLE_PROFILING}")
-    
+
     MESSAGE (STATUS "Use following BoxLib settings:")
     MESSAGE (STATUS "  BL_SPACEDIM = ${BL_SPACEDIM} (INT: 1, 2, 3)")
     MESSAGE (STATUS "  BL_MACHINE = ${BL_MACHINE} (STRING: <ARCH>)")
@@ -217,8 +217,8 @@ ENDIF()
 
 SET (IPPL_USED_FROM_OPAL "TRUE")
 ADD_SUBDIRECTORY (ippl)
-ADD_SUBDIRECTORY (classic/5.0/src)
-ADD_SUBDIRECTORY (src)
+#ADD_SUBDIRECTORY (classic/5.0/src)
+#ADD_SUBDIRECTORY (src)
 
 IF (BUILD_OPAL_UNIT_TESTS)
      ADD_SUBDIRECTORY(tests)
@@ -279,45 +279,6 @@ SET (IPPL_CXX_FLAGS
     "-DIPPL_MPI -DMPICH_SKIP_MPICXX -DIPPL_DONT_POOL -DIPPL_USE_XDIV_RNG -DPETE_BITWISE_COPY -DIPPL_HAS_TEMPLATED_COMPLEX -DIPPL_USE_PARTIAL_SPECIALIZATION -Drestrict=__restrict__ -DNOCTAssert ${IPPL_CXX_FLAGS}"
     )
 
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
 ### CXX_FLAGS common to all compilers and platforms which ###
 ### may *not* be written to the configure file            ###
 SET (OTHER_CXX_FLAGS
@@ -443,4 +404,4 @@ IF (LINUXGCC)
      RENAME ${PROJECT_NAME}Config.cmake
      )
 
-ENDIF (NOT IPPL_USED_FROM_OPAL)
+ENDIF (NOT IPPL_USED_FROM_OPAL)
\ No newline at end of file
diff --git a/ippl/doc/tex/introduction.tex b/ippl/doc/tex/introduction.tex
index 8b1768340d7e8b007017428be7cc0a97f8ea3801..87f8f4e8c921e556af6faf44c19232a097190d93 100644
--- a/ippl/doc/tex/introduction.tex
+++ b/ippl/doc/tex/introduction.tex
@@ -1,6 +1,6 @@
 \chapter{Introduction}
 \label{sec:Introduction}
-One of \ippl 's most attractive features is its high performance on both single-processor and distributed-memory multiprocessor machines. As future releases of the library will also support shared-memory machines. 
+One of \ippl 's most attractive features is its high performance on both single-processor and distributed-memory multiprocessor machines. As future releases of the library will also support shared-memory machines.
 
 The heart of the problem \ippl 's authors face is that while data-parallel programming is a natural way to express many scientific and numerical algorithms, straightforward implementations of it do exactly the wrong thing on modern architectures, whose performance depends critically on the re-use of data loaded into cache. If a program evaluates A+B+C for three arrays A, B, and C by adding A to B, then adding C to that calculation's result, performance suffers both because of the overhead of executing two loops instead of one, but also (and more importantly) because every value in the temporary array that stores the result of A+B has to be accessed twice: once to write it, and once to read it back in. As soon as this array is too large to fit into cache, the program's performance will drop dramatically.
 
@@ -27,8 +27,8 @@ int main(int argc, char *argv[])
     const unsigned N=8;
     const unsigned Dim=2;
 
-    Index IGLOBAL(N);  // Specify the global domain 
-    Index JGLOBAL(N); 
+    Index IGLOBAL(N);  // Specify the global domain
+    Index JGLOBAL(N);
 
     Index I(1, N-1); // Specify the interior domain
     Index J(1, N-1);
@@ -41,7 +41,7 @@ int main(int argc, char *argv[])
     assign(A,0.0);  // Assign initial conditions
     assign(b,0.0);
 
-    b[N/2][N/2] = -1.0;  // put a spike on the RHS 
+    b[N/2][N/2] = -1.0;  // put a spike on the RHS
     double fact = 0.25;
 
     // Iterate 200 times
@@ -50,50 +50,50 @@ int main(int argc, char *argv[])
                              A[I-1][J] +
                              A[I][J+1] +
                              A[I][J-1] - b[I][J]));
-    }                                                                                                                                            
+    }
     msg << A << endl;
     return 0;
 }
 \end{code}
 The syntax is very similar to that of Fortran 90: a single assignment fills an entire array with a scalar value, subscripts express ranges as well as single points, and so on. In fact, the combination of C++ and \ippl provides so many of the features of Fortran 90 that one might well ask whether it wouldn't better to just use the latter language straight up. One answer comes down to economics. While the various flavors of Fortran are still used in scientific computing, Fortran's user base is shrinking, particularly in comparison to C++. Networking, graphics, database access, and operating system interfaces are available in C++ programmers long before they're available in Fortran (if they become available at all). What's more, support tools such as debuggers and memory inspectors are primarily targeted at C++ developers, as are hundreds of books, journal articles, and web sites.
 
-Another answer is that the abstraction facilities of C++ are much more powerful that those in Fortran. While Fortran 90 supports an attractive array syntax for floating point arrays one could not, for example, efficiently extend this high level syntax to arrays of vectors or tensors. Until recently, Fortran has had two powerful arguments in its favor: legacy applications, and performance. However, the importance of the former is diminishing as the invention of new algorithms force programmers to rewrite old codes, while the invention of techniques such as {\it expression templates} has made it possible for C++ programs to match, or exceed, the performance of highly-optimized Fortran 77. 
+Another answer is that the abstraction facilities of C++ are much more powerful that those in Fortran. While Fortran 90 supports an attractive array syntax for floating point arrays one could not, for example, efficiently extend this high level syntax to arrays of vectors or tensors. Until recently, Fortran has had two powerful arguments in its favor: legacy applications, and performance. However, the importance of the former is diminishing as the invention of new algorithms force programmers to rewrite old codes, while the invention of techniques such as {\it expression templates} has made it possible for C++ programs to match, or exceed, the performance of highly-optimized Fortran 77.
 %!TEX encoding = UTF-8 Unicode
 
 \section{Example 2 Power Spectrum}
-A sinussoidal field  $\rho(i,j,k) = a_1sin(k_1 \frac{2\pi}{n_x} i) + a_5 sin(k_5 \frac{2\pi}{n_x} i)$, 
+A sinussoidal field  $\rho(i,j,k) = a_1sin(k_1 \frac{2\pi}{n_x} i) + a_5 sin(k_5 \frac{2\pi}{n_x} i)$,
 $i= 1 \dots n_x, ~ j= 1 \dots n_y, ~ k= 1 \dots n_z $ with $n_x,n_y$ and $n_z$ denoting the grid size is generated and
-the power spectrum calculated. This examples shows how to initialise fields, compute discrete complex-complex FFT and 
+the power spectrum calculated. This examples shows how to initialise fields, compute discrete complex-complex FFT and
 compute the resulting powerspectrum.
 
-Assume a real density field is defined like 
+Assume a real density field is defined like
 \begin{smallcode}
 typedef Field<double,Dim,Mesh_t,Center_t>  Field_t;
 Field_t rho;
 \end{smallcode}
-we then can immediately initialize the field according to the above formula 
+we then can immediately initialize the field according to the above formula
 \begin{smallcode}
-assign(rho[I][J][K], a1*sin(2.0*pi/nr_m[0]*k1*I) + 
+assign(rho[I][J][K], a1*sin(2.0*pi/nr_m[0]*k1*I) +
                      a5*sin(2.0*pi/nr_m[0]*k5*I));
 \end{smallcode}
 Normalizing to $\max(\rho) \le 1.0 $ with
 \begin{smallcode}
 rho /= max(rho)
-\end{smallcode} 
-we then assume to have defined a complex field "fC" and a complex-complex FFT. 
+\end{smallcode}
+we then assume to have defined a complex field "fC" and a complex-complex FFT.
 \begin{smallcode}
 fC = rho;
 fft->transform("forward" , fC);
  \end{smallcode}
 Here we used the in place version of the FFT to obtain $\rho $ in Fourier space. Now
-we can compute the power spectrum: 
-\begin{smallcode}  
+we can compute the power spectrum:
+\begin{smallcode}
 pwrSpec = real(fC*conj(fC));
 \end{smallcode}
 %\pagebreak
 and calculate the 1D pwr-spectrum (in x direction) by integrating over y and z: \\
-\begin{code}  
- NDIndex<3> elem;  
+\begin{code}
+ NDIndex<3> elem;
  for (int i=lDomain[0].min(); i<=(lDomain[0].max()-1)/2; ++i) {
   elem[0]=Index(i,i);
    for (int j=lDomain[1].min(); j<=(lDomain[1].max()-1)/2; ++j) {
@@ -107,24 +107,24 @@ and calculate the 1D pwr-spectrum (in x direction) by integrating over y and z:
 \end{code}
 The power spectra of the local domain is stored in $f1$. We have to update all other node
 so that each node has the full power spectrum by:
-\begin{smallcode} 
+\begin{smallcode}
 reduce(&(f1[0]),&(f1[0])+f1_lenght,OpAddAssign());
-\end{smallcode} 
+\end{smallcode}
 assuming the non local part of $f1$ is initialized with zero.
 
 %The full code pwrspec-1.cpp is located at $\ippl_ROOT/test/simple.
 
- 
+
  \section{Example 3 Particle in Cell Code (PIC)}
- This example discusses how to write a 3D Particle in Cell Code (PIC). The 
- complete source file can be found at {\em \$IPPL\_ROOT/test/particles}. The 
+ This example discusses how to write a 3D Particle in Cell Code (PIC). The
+ complete source file can be found at {\em \$IPPL\_ROOT/test/particles}. The
  this presentation details are omitted, only the structure and important issues are
- highlighted. 
+ highlighted.
  \subsection{The {\em ChargedParticles} Class}
  The base class {\tt IpplParticleBase} is augmented with attributes such as charge to mass ration
- {\tt qm}, the vector momenta {\tt P} and the vector holding the electric field {\tt E}. 
+ {\tt qm}, the vector momenta {\tt P} and the vector holding the electric field {\tt E}.
  \begin{code}
- ChargedParticles(PL* pl, Vector_t hr, Vector_t rmin, 
+ ChargedParticles(PL* pl, Vector_t hr, Vector_t rmin,
                   Vector_t rmax, e_dim_tag decomp[Dim]) :
                   IpplParticleBase<PL>(pl),
                   hr_m(hr),
@@ -173,7 +173,7 @@ int main(int argc, char *argv[]) {
         decomp[d] = (d == serialDim) ? SERIAL : PARALLEL;
     }
 \end{code}
-In the fist part of main, the discrete computational domain ({\tt domain}) and the 
+In the fist part of main, the discrete computational domain ({\tt domain}) and the
 domain decomposition ({\tt decomp}) is constructed. We have choose a 2D domain decomposition
 with $z$ serial i.e. not parallelized. \\
 \begin{code}
@@ -186,7 +186,7 @@ with $z$ serial i.e. not parallelized. \\
     Vector_t rmax(nr);
 
     partBunch=new ChargedParticles<playout_t>(PL,hr,rmin,rmax,decomp);
-\end{code} 
+\end{code}
  Here we construct the {\tt mesh} the field layout ({\tt FL}), describing how the fields are distributed
   and finally the particle layout {\tt PL}. The latter is the used as a template argument to construct the
   particle container. For this example the mesh size is set to unity and the computational domain is
@@ -201,10 +201,10 @@ with $z$ serial i.e. not parallelized. \\
     }
 
     partBunch->qm =  1.0/totalP;
-    partBunch->myUpdate(); 
+    partBunch->myUpdate();
     partBunch->initFields();
-\end{code} 
-  Now each node created {\tt nloc} particles and initialized the coordinates randomly in the 
+\end{code}
+  Now each node created {\tt nloc} particles and initialized the coordinates randomly in the
   computational domain.  A fixed charge to mass ration is assigned. The \texttt{myUpdate()} moves
   all particles to their node defined by the domain decomposition and initialized the fields. In the last
   call the fields gets initialized with the sinusoidal electric field.
@@ -222,11 +222,11 @@ with $z$ serial i.e. not parallelized. \\
 \end{code}
 The last part of main consists of a simple integration scheme to advance the particles. The call
 {\tt gather} interpolates the electric field at the particle position form the nearby grid points by a second
-order {\it cloud in cell} (CIC) interpolation scheme. 
- 
- 
+order {\it cloud in cell} (CIC) interpolation scheme.
+
+
 \subsection{{\em initFields}}
- 
+
 \begin{code}
 void initFields() {
 
@@ -237,13 +237,13 @@ void initFields() {
 
     int nx = nr_m[0]; int ny = nr_m[1]; int nz = nr_m[2];
 
-    double phi0 = 0.1*nx;            
+    double phi0 = 0.1*nx;
 
     Index I(nx), J(ny), K(nz);
 
-    assign(EFD_m[I][J][K](0), 
-            -2.0*pi*phi0/nx * 
-            cos(2.0*pi*(I+0.5)/nx) * 
+    assign(EFD_m[I][J][K](0),
+            -2.0*pi*phi0/nx *
+            cos(2.0*pi*(I+0.5)/nx) *
             cos(4.0*pi*(J+0.5)/ny) * cos(pi*(K+0.5)/nz));
 
     assign(EFD_m[I][J][K](1),  ..... ;
@@ -258,7 +258,7 @@ void initFields() {
 \end{code}
 
 \subsection{{\em myUpdate}}
- 
+
  \begin{code}
 void myUpdate() {
 
@@ -269,24 +269,24 @@ void myUpdate() {
          EFD_m.initialize(getMesh(), getFieldLayout(), GuardCellSizes<Dim>(1), vbc_m);
          EFDMag_m.initialize(getMesh(), getFieldLayout(), GuardCellSizes<Dim>(1), bc_m);
     }
-    this->update();  
+    this->update();
 }
 \end{code}
- 
+
   \subsection{{\em gather}}
- 
+
 \begin{code}
-void gather() {	
+void gather() {
     IntCIC myinterp;
     E.gather(EFD_m, this->R, myinterp);
 }
 \end{code}
- 
+
  \section{Example 4 A Particle Particle - Particle Mesh (P$^3$M) Solver}
  Particle Particle - Particle Mesh solvers take the close range interaction of particles
 into account by combining a mesh solver as seen in the previous section with a quadratic
 Particle Particle computation for particles that are closer than a given interaction
-radius $r_i$ (see \url{http://en.wikipedia.org/wiki/P3M}, 
+radius $r_i$ (see \url{http://en.wikipedia.org/wiki/P3M},
 \url{http://arxiv.org/abs/astro-ph/9805096} and \url{http://arxiv.org/abs/astro-ph/0512030}).
 To be able to combine these two solutions the Greens functions of the PIC solver and the
 particle-particle interaction have to be modified such that they add up to the desired
@@ -334,7 +334,7 @@ struct SpecializedGreensFunction<3> {
     grn = where(lt(R*R, grn), 1./sqrt(grn),
 		((grn*sqrt(grn))/R-2*grn)/(R*R*R) + 2/R);
     grn[0][0][0] = grn[0][0][1];
-  }   
+  }
 };
 \end{code}
 \vspace{5mm}
@@ -350,7 +350,7 @@ function:
   {
     HashPairBuilder< ChargedParticles<playout_t> > HPB(*this);
     //apply the field to each pair, the -1 is the field constant
-    HPB.for_each(RadiusCondition<double, Dim>(interaction_radius), 
+    HPB.for_each(RadiusCondition<double, Dim>(interaction_radius),
     			   ApplyField<double>(-1,interaction_radius));
   }
 \end{code}
@@ -369,11 +369,11 @@ struct ApplyField {
     double sqr = 0;
     for(int d = 0;d<Dim;++d)
       sqr += diff[d]*diff[d];
-		
+
      if(sqr!=0)
       {
 	double r = std::sqrt(sqr);
-	
+
 	Vector_t Fij = C*(diff/r)*(1/sqr - (-3/(R*R*R*R)*r*r + 4/(R*R*R)*r));
 
 	P.EF[i] -= P.Q[j]*Fij;
@@ -389,7 +389,7 @@ struct ApplyField {
  \ippl uses the {\em cmake } build philosophy.  The following environment variables must be set
 \begin{verbatim}
 IPPL_ROOT
-\end{verbatim} 
+\end{verbatim}
 defining where \ippl is installed.
 
 \subsection{Building \ippl}
@@ -408,14 +408,14 @@ $DKS_PREFIX
 \end{verbatim}
 defining where DKS library is installed.\\
 To use DKS in \ippl it must be eneabled in CMakeLists.txt file. There are six options than can be set to
-enable DKS for \ippl. Options ENABLE\_OPENCL, ENABLE\_CUDA and ENABLE\_OPENMP set which framework the 
-DKS  was compiled with, at least one of these options needs to be set for \ippl to be able 
-to use DKS. USE\_OPENCL, USE\_CUDA and USE\_MIC specifies which framework \ippl should use for DKS, only one 
-option can be enabled at a time.\\ 
-If Intel compiler is used to compile \ippl than DKS should also be compiled 
-with intel compiler and OpenCL and OpenMP framworks can be enabled and used. If GNU compiler is used to compile 
-\ippl DKS should also be compiled with GNU compiler and OpenCL and CUDA frameworks can be enabled and used. 
-If \ippl is compiled with MPI compiler then DKS should also be compiled with MPI compiler to enable full MPI 
+enable DKS for \ippl. Options ENABLE\_OPENCL, ENABLE\_CUDA and ENABLE\_OPENMP set which framework the
+DKS  was compiled with, at least one of these options needs to be set for \ippl to be able
+to use DKS. USE\_OPENCL, USE\_CUDA and USE\_MIC specifies which framework \ippl should use for DKS, only one
+option can be enabled at a time.\\
+If Intel compiler is used to compile \ippl than DKS should also be compiled
+with intel compiler and OpenCL and OpenMP framworks can be enabled and used. If GNU compiler is used to compile
+\ippl DKS should also be compiled with GNU compiler and OpenCL and CUDA frameworks can be enabled and used.
+If \ippl is compiled with MPI compiler then DKS should also be compiled with MPI compiler to enable full MPI
 support in DKS.
 
 
@@ -442,8 +442,8 @@ The supported operating systems and libraries are listed in Table \ref{tab:archl
 
 \clearpage
 \section{Acknowledgements}
-The contributions of various individuals and groups are acknowledged in the relevant chapters, 
-however a few individuals have or had considerable influence on the 
+The contributions of various individuals and groups are acknowledged in the relevant chapters,
+however a few individuals have or had considerable influence on the
 development, Julian Cummings, Yves Ineichen and Jakob Progsch.
 Misprints and obscurity are almost inevitable in a document of this size.
 Comments and {\em active contributions}  from readers are therefore most welcome.
@@ -452,7 +452,7 @@ They may also be sent to \htmladdnormallink{\texttt{andreas.adelmann@psi.ch}}{ma
 \subsection{Citation}
 Please cite \ippl in the following way:
 \begin{small}
-\begin{verbatim} 
+\begin{verbatim}
 @techreport{ippl-User-Guide,
 title = "{The IPPL (Independent Parallel Particle Layer)
               Framework }",
@@ -465,6 +465,4 @@ year = 2009}
 
 
 %& OPAL \\
-% & V 1.0
-
-
+% & V 1.0
\ No newline at end of file
diff --git a/ippl/doc/tex/ippl_particles.tex b/ippl/doc/tex/ippl_particles.tex
index 4664aa71f25ee6f2ae3fb64916c70dda5f9cebc7..715fc96fc12ec8cec46bf01ed4134470948f01dd 100644
--- a/ippl/doc/tex/ippl_particles.tex
+++ b/ippl/doc/tex/ippl_particles.tex
@@ -13,7 +13,7 @@ The data type of each attribute, the number of attributes, and the names for the
     \item Operations involving all the particles within a \texttt{Particle} object may be specified using simple expressions, in a manner very similar to that used for \texttt{Field} objects. These expressions may involve any of the attributes of the particles as well as other scalar data, and they may use not only the standard mathematical operators +, -, *, /, etc., but also standard mathematical functions such a s cos ( ) , exp ( ) , mod ( ) , etc.
     \item Alternatively, you may set up explicit loops that perform operations involving the attributes of a single particle or a subset of all the particles.
     \item \texttt{Particle}s may be created or destroyed during a simulation.
-    \item \texttt{Particle}-to-\texttt{Field} and \texttt{Field}-to-\texttt{Particle} operations may be performed (e.g., a particular \texttt{Particle} attribute may be deposited onto a specified \texttt{Field} using a chosen interpolation method). 
+    \item \texttt{Particle}-to-\texttt{Field} and \texttt{Field}-to-\texttt{Particle} operations may be performed (e.g., a particular \texttt{Particle} attribute may be deposited onto a specified \texttt{Field} using a chosen interpolation method).
 \end{itemize}
 
 \section{Defining a User-Specified \texttt{Particle} Class}
@@ -23,7 +23,7 @@ There is no specific class within the \ippl framework called \texttt{Particle}.
     \item Based on the type of interactions which the particles have with each other and with external objects such as a \texttt{Field}, select a method of distributing the particles among the nodes in a parallel machine.
     \item Next, decide what attributes each particle should possess.
     \item Third, create a subclass of \texttt{IpplParticleBase} which includes these attributes (specified as instances of the \texttt{ParticleAttrib} class template).
-    \item Finally, instantiate this user-defined subclass of \texttt{IpplParticleBase} and create and initialize storage for the particles which are to be maintained by this object. 
+    \item Finally, instantiate this user-defined subclass of \texttt{IpplParticleBase} and create and initialize storage for the particles which are to be maintained by this object.
 \end{itemize}
 
 The following sections describe in more detail how to accomplish these steps.
@@ -46,18 +46,18 @@ ParticleUniformLayout<double,3> uniformlayout();
 
 \texttt{ParticleSpatialLayout}, in contrast to \texttt{ParticleUniformLayout}, assigns particles to nodes based upon their spatial location relative to a \texttt{FieldLayout}. It is useful when the particles will be interacting with other particles in their neighborhood or with a \texttt{Field} object. \texttt{ParticleSpatialLayout} will keep a particle on the same node as that which contains the section of the \texttt{Field} in which the particle is located. If the particle moves to a new position, this layout will reassign it to a new node when necessary. This will maintain locality between the particles and any \texttt{Field} distributed using this \texttt{FieldLayout}. Further more it will help keep particles which are spatially close to each other local to the same processor as well. As with all the layout classes, \texttt{ParticleSpatialLayout} requires the type and dimensionality of the particle position attribute as template parameters. The constructor for \texttt{ParticleSpatialLayout} takes one argument: a pointer to a \texttt{FieldLayout} object that tells the \texttt{ParticleSpatialLayout} how the \texttt{Field} is allocated among the parallel processors, so that the particles may be maintained local to this \texttt{Field}. Note that you do not, need to create a \texttt{Field} instance itself, you only need to give \texttt{ParticleSpatialLayout} a \texttt{FieldLayout} object. An example of creating an instance of this class is as follows:
 \begin{smallcode}
-FieldLayout<3> myfieldlayout(Index(l6), Index(16), Index(32)); 
+FieldLayout<3> myfieldlayout(Index(l6), Index(16), Index(32));
 ParticleSpatialLayout<double,3> myparticlelayout(&myfieldlayout);
 \end{smallcode}
 
 
 Note that the dimensionality of the \texttt{FieldLayout} and the \texttt{ParticleSpatialLayout} (in this example, 3) must be the same. You may also create a \texttt{ParticleSpatialLayout} instance without providing a \texttt{FieldLayout}. In this case, particles will remain on the node on which they were created. If at some future time you wish to provide a \texttt{FieldLayout} object to tell the \texttt{ParticleSpatialLayout} where to place the particles, you may do so using the \texttt{setFieldLayout} (\texttt{FieldLayout<Dim>*}) method of \texttt{ParticleSpatialLayout}. This is useful when reading particles in from an external source and the size of the spatial domain containing the particles is not known until all the particles have been read. The following example demonstrates the use of the capability:
 \begin{smallcode}
-ParticleSpatiaILayout<double,3> myparticleLayout; 
-// calculate the size of the domain required to contain all the particles 
-// create a new FieldLayout object based on these calculations 
-FieldLayout<3> myfieldlayout(Index(minx, maxx), Index (miny, maxy), 
-                             Index(minz,maxz);   
+ParticleSpatiaILayout<double,3> myparticleLayout;
+// calculate the size of the domain required to contain all the particles
+// create a new FieldLayout object based on these calculations
+FieldLayout<3> myfieldlayout(Index(minx, maxx), Index (miny, maxy),
+                             Index(minz,maxz);
 myparticlelayout.setFieldLayout(&myfieldlayout);
 \end{smallcode}
 
@@ -76,7 +76,7 @@ The caching can be enabled or disabled by calling the \texttt{enableCaching()} o
 
 \texttt{ParticleAttrib} is a class template that represents a single attribute of the particles in a \texttt{Particle} object. Each \texttt{ParticleAttrib} contains the data for that attribute for all the particles. Within a user-defined \texttt{Particle} class, you declare an instance of \texttt{ParticleAttrib} for each attribute the particles will possess and assigns to it an arbitrary name. \texttt{ParticleAttrib} requires one template parameter, the type of the data for the attribute. As an example, the statement:
 \begin{smallcode}
-ParticleAttrib<double> density; 
+ParticleAttrib<double> density;
 \end{smallcode}
 
 declares an instance of \texttt{ParticleAttrib} named 'density', which will store a quantity of type double for all the particles of the \texttt{Particle} class that contains this data member.
@@ -85,7 +85,7 @@ declares an instance of \texttt{ParticleAttrib} named 'density', which will stor
 
 \texttt{IpplParticleBase} is the class that all user-defined \texttt{Particle} classes must specify as their base class. It stores the list of attributes for the particles (which are maintained as instances of \texttt{ParticleAttrib}) and a selected parallel layout mechanism. In addition to providing all the capabilities for performing operations on the particles and their attributes, \texttt{IpplParticleBase} also defines two specific attributes which all user-defined \texttt{Particle} classes inherit:
 \begin{smallcode}
-ParticleAttrib<Vektor<T,Dim>>  R; 
+ParticleAttrib<Vektor<T,Dim>>  R;
 ParticleAttrib<unsigned>      ID;
 \end{smallcode}
 
@@ -97,29 +97,29 @@ layout class. The second version of the \texttt{IpplParticleBase} constructor is
 Using \texttt{IpplParticleBase}, \texttt{ParticleAttrib}, and a selected class derived from \texttt{ParticleLayout,} you can create a user-defined \texttt{Particle} class using the following code template: \\
 \clearpage
 \begin{codeln}
-class Bunch : public IpplParticleBase< ParticleSpatiaILayout<double,3> > 
-{ 
-public: 
-    // Attributes for this particle class (besides position and ID). 
-    ParticleAttrib<double>             qm;      // q/m ratio 
-    ParticleAttribs Vektor<double,2> > vel; 	// velocity 
-
-    // constructor 
-    Bunch(Layout\_t *L) : IpplParticleBase<Layout\_t>(L) { 
-        addAttribute(qm); 
-        addAttribute(vel); 
-    } 
-}; 
+class Bunch : public IpplParticleBase< ParticleSpatiaILayout<double,3> >
+{
+public:
+    // Attributes for this particle class (besides position and ID).
+    ParticleAttrib<double>             qm;      // q/m ratio
+    ParticleAttribs Vektor<double,2> > vel; 	// velocity
+
+    // constructor
+    Bunch(Layout\_t *L) : IpplParticleBase<Layout\_t>(L) {
+        addAttribute(qm);
+        addAttribute(vel);
+    }
+};
 \end{codeln}
 
 Let us describe this example in detail by discussing the important lines in the order of use.
 
-Line 1: You may select whatever name is appropriate for the specialized \texttt{Particle} class, but it must be derived from \texttt{IpplParticleBase}. 
+Line 1: You may select whatever name is appropriate for the specialized \texttt{Particle} class, but it must be derived from \texttt{IpplParticleBase}.
 
 In this case, we explicitly specify the type of layout to use (\texttt{ParticleSpatialLayout}), with particle position attribute type and dimensionality template parameters of double and 3, respectively. Alternatively, \texttt{Bunch} may have been declared as a class template itself and may have passed on the layout template parameters to \texttt{IpplParticleBase}. In that case, the first line would instead look like
 \begin{smallcode}
-template <class PLayout> 
-class Bunch : public IpplParticleBase<PLayout> 
+template <class PLayout>
+class Bunch : public IpplParticleBase<PLayout>
 \end{smallcode}
 
 Lines 5-6: Here is where the attributes for the particles in the \texttt{Particle} object are declared. They may be given any name other than \texttt{R} or \texttt{ID}. Instead of stating the type and dimensionality of this attribute specifically, you may also use one of the following typedefs and constants defined in \texttt{IpplParticleBase}:
@@ -131,29 +131,29 @@ Lines 5-6: Here is where the attributes for the particles in the \texttt{Particl
 \end{itemize}
 and could have been used to specify the attribute \texttt{vel} in the above example as \texttt{ParticlePos\_t vel};
 \begin{itemize}
-\item \texttt{ParticleIndex\_t} - a typedef for the particle global \texttt{ID} attribute; it is short for \texttt{ParticleAttrib<unsigned>} 
+\item \texttt{ParticleIndex\_t} - a typedef for the particle global \texttt{ID} attribute; it is short for \texttt{ParticleAttrib<unsigned>}
 \end{itemize}
-The constructor for this user-defined class must initialize \texttt{IpplParticleBase} with a pointer to an instance of the selected layout class. 
+The constructor for this user-defined class must initialize \texttt{IpplParticleBase} with a pointer to an instance of the selected layout class.
 
 In this example, the layout class is \texttt{ParticleSpatialLayout}, but using one of the typedefs listed above, we can abbreviate this as \texttt{Layout\_t}. Note that we only define one constructor here, omitting the default constructor. This is done because \texttt{ParticleSpatialLayout} (which we have hard-coded as the layout for this user-defined \texttt{Particle} class) requires an argument to its constructor, and this can only be provided if we use a constructor for our \texttt{Particle} class as shown here. A new instance of this class would be declared in an application as follows:
 \begin{smallcode}
-Bunch myBunch (new ParticleSpatialLayout<double,3>(myFieldLayout)); 
+Bunch myBunch (new ParticleSpatialLayout<double,3>(myFieldLayout));
 \end{smallcode}
-where my\texttt{FieldLayout} was a \texttt{FieldLayout} object created previously. The only action that is required in the constructor for the derived class is to inform the base class of the declared attributes, 
+where my\texttt{FieldLayout} was a \texttt{FieldLayout} object created previously. The only action that is required in the constructor for the derived class is to inform the base class of the declared attributes,
 using the \texttt{addAttribute(.)} method of \texttt{IpplParticleBase}, which registers the specified \texttt{ParticleAttrib} instance with the parent class \texttt{IpplParticleBase}. The order in which attributes are registered is not important.
 
 \subsection{Example \texttt{Particle} Classes: The \texttt{Genparticle} and \texttt{GenArrayParticle} Classes}
 The \ippl framework provides two classes which are examples of \texttt{Particle} classes derived from \texttt{IpplParticleBase}: \texttt{Genparticle} and \texttt{GenArrayParticle}. They may be used as samples from which to build new classes, or they may be used to quickly include particle capabilities in an application. \texttt{Genparticle} is a \texttt{Particle} class with three attributes: \texttt{R} and \texttt{ID} inherited from \texttt{IpplParticleBase}, and an attribute named data with elements
 of an arbitrary type. \texttt{Genparticle} has two template parameters: the type of particle layout to use and the type \texttt{T} of attribute data. It has two constructors just as \texttt{IpplParticleBase} does: the default and one taking a layout pointer. An example of instantiating a \texttt{GenParticle}object is shown below.
 \begin{smallcode}
-GenParticle<ParticleUniforrnLayout<float,3>,UserDefinedType> GP(); 
+GenParticle<ParticleUniforrnLayout<float,3>,UserDefinedType> GP();
 \end{smallcode}
 
 
 \texttt{GenArrayParticle} is almost identical to \texttt{GenParticle}, the difference being that \texttt{GenArrayparticle} contains not just one but an array of attributes data \texttt{[0 ... N-l]} of a specified type. The number of elements in the attribute array, \texttt{N}, is given as a third template parameter. The following example shows a \texttt{GenArrayParticle} being created with 5 floats stored in the data array for each particle:
 \begin{smallcode}
 GenArrayParticle<ParticleSpatialLayout<doulble,3>,float,5> GAP(
-        new ParticleSpatialLayout<double,3>(myFieldLayout)); 
+        new ParticleSpatialLayout<double,3>(myFieldLayout));
 \end{smallcode}
 
 It is important to note that the array data in \texttt{GenArrayParticle} contains a set of particle attributes of the same type. In situations where it is necessary to have a variety of particle attribute types, you may use the \texttt{Genparticle} class with the type of data being specified as a user-defined struct containing the various attributes needed.
@@ -166,7 +166,7 @@ After a specific \texttt{Particle} class has been defined and created in a \ippl
 
 When a \texttt{Particle} object is created, it is initially empty. Storage for new particles is allocated using the create (unsigned) method of \texttt{IpplParticleBase}. For example, if a \texttt{Particle} object bunch has been created already, the statement
 \begin{smallcode}
-bunch.create(100); 
+bunch.create(100);
 \end{smallcode}
 
 
@@ -180,15 +180,15 @@ local count (and will not tell any other processors it has created these new par
 After calling create to allocate new storage, you must initialize the data. This should be done after calling create and before calling \texttt{update} for the \texttt{Particle} object. After the data is initialized, the \texttt{update} routine will properly distribute the particles to their correct node based on the layout mechanism chosen for that \texttt{Particle} object and possibly the positions of the particles as set during their initialization. The following example shows one way to initialize the data for newly
 created particles when running on a single-processor machine. (This example will be modified in the following section for the case of running in parallel.) \\
 \begin{code}
-// create and'initialize data for an instance of Bunch 
-Bunch myBunch(new Bunch::Layout\_t(myFieldLayout)); 
-int currLocalPtcls = myPtcls.getLocalNum(); 
-myBunch.create(100); 
-for (int i = 0; i < 100; i++) { 
-    myBunch.R[currLocalPtcls + i] = Vektor<double,3>(0.0, 1.0, 0.0); 
-    myBunch.vel[currLocalPtcls + i] Vektor<double,3>(1.0, 1.0, 1.0); 
-} 
-myBunch.update(); 
+// create and'initialize data for an instance of Bunch
+Bunch myBunch(new Bunch::Layout\_t(myFieldLayout));
+int currLocalPtcls = myPtcls.getLocalNum();
+myBunch.create(100);
+for (int i = 0; i < 100; i++) {
+    myBunch.R[currLocalPtcls + i] = Vektor<double,3>(0.0, 1.0, 0.0);
+    myBunch.vel[currLocalPtcls + i] Vektor<double,3>(1.0, 1.0, 1.0);
+}
+myBunch.update();
 \end{code}
 
 
@@ -200,17 +200,17 @@ In this example, 100 new particles are created, and the \texttt{R} and \texttt{v
 The code shown in the previous example has one problem when used on parallel architectures: the call to create is performed on each processor, so if there were P processors a total of 100*P particles would be created. This may be the desired behavior, if so, the previous example is sufficient. However, if you are reading data on particle positions and other attributes from a file or some other source, you may wish to create particles on a single processor, and then distribute the
 data to the proper nodes. To do this, you need to call create and assign initial data on only one node but call update on all the processors. The \texttt{singlelnitNode()} method of \texttt{IpplParticleBase} will return a boolean value indicating whether the local processor should be used to create and initialize new particles in this way. The following example demonstrates how to use this method for initializing particles: \\
 \begin{code}
-// create and'initialize data for an instance of Bunch 
-Bunch myBunch(new Bunch::Layout\_t(myFieldLayout)); 
+// create and'initialize data for an instance of Bunch
+Bunch myBunch(new Bunch::Layout\_t(myFieldLayout));
 int currLocalPtcls = myPtcls.getLocalNum();
-if (myBunch.singleInitNode()) { 
-    myBunch.create(100);  
-    for (int i = 0; i < 100; i++) { 
-        myBunch.R[currLocalPtcls + i] = Vektor<double,3>(0.0, 1.0, 0.0); 
-        myBunch.vel[currLocalPtcls + i] Vektor<double,3>(1.0, 1.0, 1.0); 
+if (myBunch.singleInitNode()) {
+    myBunch.create(100);
+    for (int i = 0; i < 100; i++) {
+        myBunch.R[currLocalPtcls + i] = Vektor<double,3>(0.0, 1.0, 0.0);
+        myBunch.vel[currLocalPtcls + i] Vektor<double,3>(1.0, 1.0, 1.0);
     }
-} 
-myBunch.update(); 
+}
+myBunch.update();
 \end{code}
 
 
@@ -228,12 +228,12 @@ The \texttt{update()} method of \texttt{IpplParticleBase} is responsible for mak
 \texttt{IpplParticleBase} object. Typically, this layout mechanism depends on the position of particles, so when particles change their position, they may need to be reassigned to a new processor to maintain the proper layout. In this case, the \texttt{update} method should be called whenever a computation is complete which alters the attributes (e.g. position) that a layout depends upon. The following short example demonstrates using \texttt{update} in conjunction with some operation that alters the x-coordinate of a
 set of particles. \\
 \begin{code}
-// do some computation involving myBunch for several time steps 
-while (computation_done == false) { 
-    // for each particle, add some constant to the x coordinate 
-    myBunch.R(0) += 0.li 
-    // update the Particle object; this may move particles between nodes 
-    myBunch.update(); 
+// do some computation involving myBunch for several time steps
+while (computation_done == false) {
+    // for each particle, add some constant to the x coordinate
+    myBunch.R(0) += 0.li
+    // update the Particle object; this may move particles between nodes
+    myBunch.update();
     // determine if the computation is done, etc.
 }
 \end{code}
@@ -247,16 +247,16 @@ Computations involving particle attributes may be performed in many ways. Data-p
 Just as with the \texttt{Field} class, you may perform data-parallel operations on particle attributes using a simple expression syntax, which the \ippl framework will translate into efficient inlined code. These operations will be performed for every particle. The expressions may include any of the attributes in a \texttt{Particle} object as well as scalar values, may use mathematical operators such as +, -, *, / etc., and may call standard mathematical functions such as \texttt{cos(
 )}, \texttt{exp( )}, \texttt{mod( )} , etc. for an attribute value of each particle. Some examples are shown below.
 \begin{smallcode}
-double dt = 2.0; 
-myBunch.R += myBunch.vel* dt; 
-myBunch. vel = 1. ¡ - log (1. ¡ + myBunch. R * myBunch. R) ; 
-myBunch.update(); 
+double dt = 2.0;
+myBunch.R += myBunch.vel* dt;
+myBunch. vel = 1. ¡ - log (1. ¡ + myBunch. R * myBunch. R) ;
+myBunch.update();
 \end{smallcode}
 
 
 Attribute expressions will perform their operations on all the particles in the \texttt{Particle} object, including any new particles allocated via a call to create, even before update has been called. This fact is useful when initializing the attributes for newly created particles (e.g., to set the init value for some scalar quantity to zero). Generally, however, unless you are performing an initialization of new particles, you should avoid using particle expressions of this type after calls to create or destroy and before a call to update.
 
-Some attributes, such as \texttt{Vektor}s or \texttt{Tenzor}s, have multiple components, and you may wish to involve only the \texttt{N}th component of the attribute in an expression. To do so, use the \texttt{()} operator to select the \texttt{N}th component of that attribute. For instance, using \texttt{myBunch} from the previous example, you can change just the x-coordinate of the particle position attribute \texttt{R} as follows: 
+Some attributes, such as \texttt{Vektor}s or \texttt{Tenzor}s, have multiple components, and you may wish to involve only the \texttt{N}th component of the attribute in an expression. To do so, use the \texttt{()} operator to select the \texttt{N}th component of that attribute. For instance, using \texttt{myBunch} from the previous example, you can change just the x-coordinate of the particle position attribute \texttt{R} as follows:
 \begin{smallcode}
 myBunch.R(0) = myBunch.R(l) - cos(myBunch.R(2));
 \end{smallcode}
@@ -264,12 +264,12 @@ myBunch.R(0) = myBunch.R(l) - cos(myBunch.R(2));
 
 For 2D or 3D quantities, use two or three indices. For example, if rho is a 3x3 \texttt{Tenzor} attribute of myBunch, you can do the following:
 \begin{smallcode}
-myBunch.rho(0,0) = -(myBunch.rho(0,l) + myBunch.rho(0,2)); 
+myBunch.rho(0,0) = -(myBunch.rho(0,l) + myBunch.rho(0,2));
 \end{smallcode}
 
 Attribute expressions may also use the where operator in much the same way as for \texttt{Field} expressions. The first argument to where is some expression that results in a \texttt{boolean} value for each particle. The second and third arguments are expressions that will be evaluated for a particle if the first argument is \texttt{true} or \texttt{false}, respectively, for that particle. For example,
 \begin{smallcode}
-myBunch.vel = where(myBunch.R(0) > 0.0, -2.0 * myBunch.vel, myBunch.vel) 
+myBunch.vel = where(myBunch.R(0) > 0.0, -2.0 * myBunch.vel, myBunch.vel)
 \end{smallcode}
 
 changes the value of the \texttt{vel} attribute in \texttt{myBunch} when the x-coordinate of the particle position is positive.
@@ -278,17 +278,17 @@ changes the value of the \texttt{vel} attribute in \texttt{myBunch} when the x-c
 
 You also have the capability of performing operations on specific particles using iterators or standard indexing operations. The \texttt{ParticleAttrib} containers in a \texttt{Particle} class may be used just as regular \texttt{STL} containers. The \texttt{begin()} and \texttt{end()} methods of the \texttt{ParticleAttrib} class will return an iterator pointing to the first element and just past the last element, respectively, of the attribute. These iterators may be used in an explicit loop just as if they were pointers into the attribute array.
 \begin{smallcode}
-ParticleAttrib<unsigned>::iterator idptr, idend = myBunch.ID.end(); 
-for (idptr = myBunch.ID.begin(); idptr != idend; ++idptr) 
-    cout << "Particle ID value: " << *idptr << endl; 
+ParticleAttrib<unsigned>::iterator idptr, idend = myBunch.ID.end();
+for (idptr = myBunch.ID.begin(); idptr != idend; ++idptr)
+    cout << "Particle ID value: " << *idptr << endl;
 \end{smallcode}
 
 
 Iterators are available for all \texttt{ParticleAttribs}. As an alternative, you may simply use the \texttt{[]} operator to access the attribute data of the \texttt{N}th particle on a node, treating \texttt{ParticleAttrib} as a regular array of data.
 \begin{smallcode}
-int nptcls = myBunch.getLocalNum(); 
-for(int i=0; i < nptcls ++i) { 
-    cout << "Particle ID value: " << myPtcls.ID[i] << endl; 
+int nptcls = myBunch.getLocalNum();
+for(int i=0; i < nptcls ++i) {
+    cout << "Particle ID value: " << myPtcls.ID[i] << endl;
 }
 \end{smallcode}
 
@@ -302,7 +302,7 @@ for(int i=0; i < nptcls ++i) {
 %nearest-neighbor pairlists. After changing the interaction radius, you should as always perform an \texttt{update()} to make sure all nodes have correct information on how to find neighboring particles. You may, for example, update the \texttt{ParticleAttrib} used to store the individual particle interaction radii as the last step of some calculation, and then call \texttt{update()}. You can retrieve the interaction radius for any local particle by calling the method
 %\texttt{getlnteractionRadius(unsigned)} of the \texttt{Particle} object containing that particle.
 
-%The second step in this process is to retrieve a list of nearest-neighborparticles for a given local particle, and then to perform the desired calculation using those nearby particles. This is done using the 
+%The second step in this process is to retrieve a list of nearest-neighborparticles for a given local particle, and then to perform the desired calculation using those nearby particles. This is done using the
 %\begin{smallcode}
 %getpairlist(unsigned, pair_iterator&, pair_iterator&)
 %\end{smallcode}
@@ -312,15 +312,15 @@ for(int i=0; i < nptcls ++i) {
 %Here is an example of how to use this mechanism: \\
 %\clearpage
 %\begin{codeln}
-%myBunch.setlnteractionRadius(4.0); //determines interaction region 
+%myBunch.setlnteractionRadius(4.0); //determines interaction region
 %Bunch::pair_iterator neighbor, neighbor_end;
-%for(int i=0; i < myBunch.getLocalNum(); ++i;) { 
+%for(int i=0; i < myBunch.getLocalNum(); ++i;) {
 %    myBunch.getPairlist(i, neighbor, neighbor_end);
-%    for ( ; neighbor != neighbor_end; ++neighbor) { 
-%        User\texttt{Particle}::pair\_t pairdata = *neighbor; 
-%        int n = pairdata.first; 	           // local index of next neighbor 
-%        double sep2 = pairdata.second;         // distance^2 between particles 
-%        myBunch.R[i] += myBunch.vel[n] * 2.0;  // any calculation c<;>uld be here 
+%    for ( ; neighbor != neighbor_end; ++neighbor) {
+%        User\texttt{Particle}::pair\_t pairdata = *neighbor;
+%        int n = pairdata.first; 	           // local index of next neighbor
+%        double sep2 = pairdata.second;         // distance^2 between particles
+%        myBunch.R[i] += myBunch.vel[n] * 2.0;  // any calculation c<;>uld be here
 %    }
 %}
 %myPtcls.update();
@@ -352,7 +352,7 @@ HashPairBuilder< Bunch<ParticleLayout_t> > HPB(myBunch);
 HPB.for_each(RadiusCondition<double, Dim>(interaction_radius), PairFunctor());
 \end{smallcode}
 
-To correctly generate all pairs in a multi process simulation a caching strategy has to be chosen so each process also has the required ghost particles. To achieve this for the example given one would call 
+To correctly generate all pairs in a multi process simulation a caching strategy has to be chosen so each process also has the required ghost particles. To achieve this for the example given one would call
 
 \begin{smallcode}
 PL->setAllCacheDimensions(interaction_radius);
@@ -370,10 +370,10 @@ Many particle-based simulation methods, including "particle-in-cell" (PIC) simul
 
 \ippl provides a hierarchy of interpolation classes, each derived from the base class \texttt{Interpolate} and each containing the basic \texttt{gather} and \texttt{scatter} functions. The \texttt{gather} method allows you to gather one or more specified \texttt{Field}s into an equal number of \texttt{ParticleAttribs}. Similarly, \texttt{scatter} will accumulate one or more \texttt{ParticleAttribs} on to an equal number of \texttt{Field} objects. An example of how to scatter the particle density to a \texttt{Field} is shown below.
 \begin{smallcode}
-InterpolateNGP<Dim> mylnterpolater(myBunch);           // create NGP interpolater 
-Field<double,Dim> ptcl_density(myfieldlayout);         // create density field 
-myInterpolator.scatter(myBunch.density,ptcl_density);  // do scattet 
+InterpolateNGP<Dim> mylnterpolater(myBunch);           // create NGP interpolater
+Field<double,Dim> ptcl_density(myfieldlayout);         // create density field
+myInterpolator.scatter(myBunch.density,ptcl_density);  // do scattet
 \end{smallcode}
 The various classes derived from \texttt{Interpolate} implement these \texttt{gather} and \texttt{scatter} methods using different well-known interpolation schemes, such as nearest grid point (NGP), linear interpolation, and the subtracted-dipole scheme (SUDS). You may use these provided classes as a template for deriving new classes from \texttt{Interpolate} that implement other interpolation schemes of interest.
 
-In case of the CIC Interpolation and non-cyclic boundary condition, care has to be taken to not place particles in the outer half of boundary cells. Otherwise values will be scattered out of the grid and be irretrivable.
+In case of the CIC Interpolation and non-cyclic boundary condition, care has to be taken to not place particles in the outer half of boundary cells. Otherwise values will be scattered out of the grid and be irretrivable.
\ No newline at end of file
diff --git a/ippl/doc/tex/ippl_setup.tex b/ippl/doc/tex/ippl_setup.tex
index b4f23f0b9119d103e26c60961a659fa096b819f1..47190ebccfa5a236cf286021ad3bf1f6b89b7266 100644
--- a/ippl/doc/tex/ippl_setup.tex
+++ b/ippl/doc/tex/ippl_setup.tex
@@ -61,7 +61,7 @@ The argument to the macro is then given to the associated \texttt{Inform} object
 
 \subsection{Timer Class}
 Timer is used to perform simple timings within a program for use in, e.g., benchmarking. It tracks real (clock) time elapsed, user time, and system time. It acts essentially as a stopwatch: 
-initially it is stopped, and YOU tell it to stop and start with method calls. The Timer constructor takes no arguments; you create a new Timer object, and use the following methods:
+initially it is stopped, and YOU tell it to stop and start with method calls. The Timer constructor takes no arguments; you create a new Timer object, and use the following methods:
 \begin{smallcode}
 //Start the clock running. Time only accumulates in the Timer when it is running. 
 void start()
diff --git a/ippl/src/AppTypes/CMakeLists.txt b/ippl/src/AppTypes/CMakeLists.txt
index 5bd654a66f1bfec7640f68416d18d93ba50d4d7c..9f9290452943381ac6092969e6727d9826f30f6b 100644
--- a/ippl/src/AppTypes/CMakeLists.txt
+++ b/ippl/src/AppTypes/CMakeLists.txt
@@ -23,7 +23,7 @@ INCLUDE_DIRECTORIES (
   ${CMAKE_CURRENT_SOURCE_DIR}
 )
 
-ADD_SOURCES (${_SRCS})
-ADD_HEADERS (${_HDRS})
+ADD_IPPL_SOURCES (${_SRCS})
+ADD_IPPL_HEADERS (${_HDRS})
 
 INSTALL (FILES ${_HDRS} DESTINATION include/AppTypes)
diff --git a/ippl/src/AppTypes/Vektor.h b/ippl/src/AppTypes/Vektor.h
index 11a0e2194b4cf9a7860afa5372879a0f8d5a4604..92f1fcd9a6f314db9f85d655d93c87c4f337fd6a 100644
--- a/ippl/src/AppTypes/Vektor.h
+++ b/ippl/src/AppTypes/Vektor.h
@@ -195,41 +195,29 @@ private:
 template<class T, unsigned D>
 typename Vektor<T,D>::Element_t& Vektor<T,D>::operator[](unsigned int i)
 {
-#pragma GCC diagnostic push
-#pragma GCC diagnostic ignored "-Warray-bounds"
   PAssert (i<D);
   return X[i];
-#pragma GCC diagnostic pop
 }
 
 template<class T, unsigned D>
 typename Vektor<T,D>::Element_t Vektor<T,D>::operator[](unsigned int i) const
 {
-#pragma GCC diagnostic push
-#pragma GCC diagnostic ignored "-Warray-bounds"
   PAssert (i<D);
   return X[i];
-#pragma GCC diagnostic pop
 }
 
 template<class T, unsigned D>
 typename Vektor<T,D>::Element_t& Vektor<T,D>::operator()(unsigned int i)
 {
-#pragma GCC diagnostic push
-#pragma GCC diagnostic ignored "-Warray-bounds"
   PAssert (i<D);
   return X[i];
-#pragma GCC diagnostic pop
 }
 
 template<class T, unsigned D>
 typename Vektor<T,D>::Element_t Vektor<T,D>::operator()( unsigned int i) const
 {
-#pragma GCC diagnostic push
-#pragma GCC diagnostic ignored "-Warray-bounds"
   PAssert (i<D);
   return X[i];
-#pragma GCC diagnostic pop
 }
 
 //////////////////////////////////////////////////////////////////////
@@ -318,4 +306,4 @@ inline std::ostream& operator<<(std::ostream& out, const Vektor<T,D>& rhs)
  * $RCSfile: Vektor.h,v $   $Author: adelmann $
  * $Revision: 1.1.1.1 $   $Date: 2003/01/23 07:40:24 $
  * IPPL_VERSION_ID: $Id: Vektor.h,v 1.1.1.1 2003/01/23 07:40:24 adelmann Exp $
- ***************************************************************************/
+ ***************************************************************************/
\ No newline at end of file
diff --git a/ippl/src/CMakeLists.txt b/ippl/src/CMakeLists.txt
index 1df8073f702757eb1c5cc07e9c145d9fb1c667f9..123bca6fc415bd394dba2170323ec3c3050a9e31 100644
--- a/ippl/src/CMakeLists.txt
+++ b/ippl/src/CMakeLists.txt
@@ -35,11 +35,7 @@ SET (IPPL_COMPILE_DATE \"${DATE_OUT}\")
 SET (IPPL_COMPILE_MACHINE \"${UNAME_OUT}\")
 SET (IPPL_COMPILE_OPTIONS \"${CXXDEFINES}\")
 SET (IPPL_COMPILE_USER \"${WHOAMI_OUT}\")
-EXECUTE_PROCESS (
-    WORKING_DIRECTORY ${CMAKE_SOURCE_DIR}
-    COMMAND bin/findFiles.sh
-    OUTPUT_VARIABLE IPPL_VERSION_LOG
-    )
+
 CONFIGURE_FILE (IpplVersions.h.in ${CMAKE_CURRENT_SOURCE_DIR}/IpplVersions.h)
 
 ### print the compiler flags #############################
@@ -87,7 +83,7 @@ SET (IPPL_SRCS_FORT
     )
 
 SET (IPPL_SRC_DIR ${CMAKE_CURRENT_SOURCE_DIR})
-MACRO (ADD_SOURCES )
+MACRO (ADD_IPPL_SOURCES )
     FILE (RELATIVE_PATH _relPath "${IPPL_SRC_DIR}" "${CMAKE_CURRENT_SOURCE_DIR}")
     FOREACH (_src ${ARGN})
         IF (_relPath)
@@ -102,7 +98,7 @@ MACRO (ADD_SOURCES )
     ENDIF ()
 ENDMACRO ()
 
-MACRO (ADD_HEADERS )
+MACRO (ADD_IPPL_HEADERS )
     FILE (RELATIVE_PATH _relPath "${IPPL_SRC_DIR}" "${CMAKE_CURRENT_SOURCE_DIR}")
     FOREACH (_hdr ${ARGN})
         IF (_relPath)
@@ -121,7 +117,7 @@ SET (IPPL_BASEDIR_HDRS
     Ippl.h
     IpplVersions.h
     )
-ADD_HEADERS (${IPPL_BASEDIR_HDRS})
+ADD_IPPL_HEADERS (${IPPL_BASEDIR_HDRS})
 
 ADD_SUBDIRECTORY (AppTypes)
 ADD_SUBDIRECTORY (DataSource)
@@ -160,7 +156,7 @@ ADD_LIBRARY ( ippl ${IPPL_SRCS} ${IPPL_SRCS_FORT} )
 
 IF (ENABLE_DKS)
     #TARGET_LINK_LIBRARIES(ippl dks)
-    TARGET_LINK_LIBRARIES(ippl ${DKS_LIBRARY_DIR}/libdks.a  -lgfortran)
+    TARGET_LINK_LIBRARIES(ippl ${DKS_LIBRARY_DIR}/libdks.a -lgfortran)
 ELSE ()
     TARGET_LINK_LIBRARIES(ippl -lgfortran)
 ENDIF (ENABLE_DKS)
diff --git a/ippl/src/DataSource/CMakeLists.txt b/ippl/src/DataSource/CMakeLists.txt
index 73098ffff0554e767f3d853d0579bf8e385918fc..5cffbf956447dfc315103a333a02e8fe20955f31 100644
--- a/ippl/src/DataSource/CMakeLists.txt
+++ b/ippl/src/DataSource/CMakeLists.txt
@@ -35,7 +35,7 @@ INCLUDE_DIRECTORIES (
   ${CMAKE_CURRENT_SOURCE_DIR}
 )
 
-ADD_SOURCES (${_SRCS})
-ADD_HEADERS (${_HDRS})
+ADD_IPPL_SOURCES (${_SRCS})
+ADD_IPPL_HEADERS (${_HDRS})
 
 INSTALL (FILES ${_HDRS} DESTINATION include/DataSource)
diff --git a/ippl/src/DataSource/FilePtclBaseDataSource.h b/ippl/src/DataSource/FilePtclBaseDataSource.h
index 69d35e6078aed45ac7592702000e2119614c1776..2aae95811d92e2416b7d022334fb33b3a73cc8c9 100644
--- a/ippl/src/DataSource/FilePtclBaseDataSource.h
+++ b/ippl/src/DataSource/FilePtclBaseDataSource.h
@@ -2,7 +2,7 @@
 /***************************************************************************
  *
  * The IPPL Framework
- * 
+ *
  *
  * Visit http://people.web.psi.ch/adelmann/ for more details
  *
@@ -12,7 +12,7 @@
 #define FILE_PARTICLE_BASE_DATA_SOURCE_H
 
 /***********************************************************************
- * 
+ *
  * class FileIpplParticleBaseDataSource
  *
  * A specific version of DataSourceObject which takes the data for
@@ -34,7 +34,7 @@ public:
   // constructor: the name, the connection, the transfer method,
   // the IpplParticleBase to connect
   FileIpplParticleBaseDataSource(const char *, DataConnect *, int,
-			     IpplParticleBase<T> &);
+                                 IpplParticleBase<T> &);
 
   // destructor
   virtual ~FileIpplParticleBaseDataSource();
@@ -70,5 +70,5 @@ private:
 /***************************************************************************
  * $RCSfile: FilePtclBaseDataSource.h,v $   $Author: adelmann $
  * $Revision: 1.1.1.1 $   $Date: 2003/01/23 07:40:25 $
- * IPPL_VERSION_ID: $Id: FilePtclBaseDataSource.h,v 1.1.1.1 2003/01/23 07:40:25 adelmann Exp $ 
- ***************************************************************************/
+ * IPPL_VERSION_ID: $Id: FilePtclBaseDataSource.h,v 1.1.1.1 2003/01/23 07:40:25 adelmann Exp $
+ ***************************************************************************/
\ No newline at end of file
diff --git a/ippl/src/DataSource/PtclBaseDataSource.cpp b/ippl/src/DataSource/PtclBaseDataSource.cpp
index cabfcb99eebd27e1966fa6d4e35fe3bdd5dee3ea..96ae603d4c4014dc9200bc7a62638295824b75fd 100644
--- a/ippl/src/DataSource/PtclBaseDataSource.cpp
+++ b/ippl/src/DataSource/PtclBaseDataSource.cpp
@@ -2,8 +2,8 @@
 /***************************************************************************
  *
  * The IPPL Framework
- * 
- * This program was prepared by PSI. 
+ *
+ * This program was prepared by PSI.
  * All rights in the program are reserved by PSI.
  * Neither PSI nor the author(s)
  * makes any warranty, express or implied, or assumes any liability or
@@ -17,7 +17,7 @@
 /***************************************************************************
  *
  * The IPPL Framework
- * 
+ *
  *
  * Visit http://people.web.psi.ch/adelmann/ for more details
  *
@@ -87,7 +87,7 @@ IpplParticleBaseDataSource::find_particle_base(ParticleAttribDataSource *pa,
 // should be called by the constructors of subclasses after a successful
 // connect.  Argument = name of this particle base
 void IpplParticleBaseDataSource::checkin() {
-  
+
 
   // first see if we're already here ...
   BaseList_t::iterator currbase = IpplParticleBaseDataSource::begin_base();
@@ -104,7 +104,7 @@ void IpplParticleBaseDataSource::checkin() {
 ///////////////////////////////////////////////////////////////////////////
 // unregister ourselves ... generally called by subclass destructors.
 void IpplParticleBaseDataSource::checkout() {
-  
+
 
   for (unsigned i=0; i < BaseList.size(); ++i) {
     if (BaseList[i] == this) {
@@ -123,7 +123,7 @@ bool IpplParticleBaseDataSource::connect_attrib(ParticleAttribDataSource *pa) {
   return true;
 }
 
-  
+
 ////////////////////////////////////////////////////////////////////////////
 // disconnect from the external agency the connection involving this
 // particle base and the given attribute.  Return success.
@@ -148,5 +148,5 @@ bool IpplParticleBaseDataSource::disconnect_attrib(ParticleAttribDataSource *pa)
 /***************************************************************************
  * $RCSfile: PtclBaseDataSource.cpp,v $   $Author: adelmann $
  * $Revision: 1.1.1.1 $   $Date: 2003/01/23 07:40:25 $
- * IPPL_VERSION_ID: $Id: PtclBaseDataSource.cpp,v 1.1.1.1 2003/01/23 07:40:25 adelmann Exp $ 
- ***************************************************************************/
+ * IPPL_VERSION_ID: $Id: PtclBaseDataSource.cpp,v 1.1.1.1 2003/01/23 07:40:25 adelmann Exp $
+ ***************************************************************************/
\ No newline at end of file
diff --git a/ippl/src/DomainMap/CMakeLists.txt b/ippl/src/DomainMap/CMakeLists.txt
index 74e95485fc36ec6819c526c8e9638b0ae7ceee63..39e8d05213588247c23d8e4886777bda01f58cf2 100644
--- a/ippl/src/DomainMap/CMakeLists.txt
+++ b/ippl/src/DomainMap/CMakeLists.txt
@@ -10,7 +10,7 @@ INCLUDE_DIRECTORIES (
   ${CMAKE_CURRENT_SOURCE_DIR}
 )
 
-ADD_SOURCES (${_SRCS})
-ADD_HEADERS (${_HDRS})
+ADD_IPPL_SOURCES (${_SRCS})
+ADD_IPPL_HEADERS (${_HDRS})
 
 INSTALL (FILES ${_HDRS} DESTINATION include/DomainMap)
diff --git a/ippl/src/FFT/CMakeLists.txt b/ippl/src/FFT/CMakeLists.txt
index b292a6a2f9b26817c5f027bdc4a1893c4f41c5fd..f29f1f740d05b3a77dceb70e0e1e2c3ffad970cc 100644
--- a/ippl/src/FFT/CMakeLists.txt
+++ b/ippl/src/FFT/CMakeLists.txt
@@ -15,7 +15,7 @@ INCLUDE_DIRECTORIES (
   ${CMAKE_CURRENT_SOURCE_DIR}
 )
 
-ADD_SOURCES (${_SRCS})
-ADD_HEADERS (${_HDRS})
+ADD_IPPL_SOURCES (${_SRCS})
+ADD_IPPL_HEADERS (${_HDRS})
 
 INSTALL (FILES ${_HDRS} DESTINATION include/FFT)
diff --git a/ippl/src/FFT/FFT.hpp b/ippl/src/FFT/FFT.hpp
index b85e6ee1633454d40a502b49cad48b20bab08023..aad82a131269547f89a30383c3c8c8284bac7c55 100644
--- a/ippl/src/FFT/FFT.hpp
+++ b/ippl/src/FFT/FFT.hpp
@@ -1159,7 +1159,7 @@ FFT<RCTransform,Dim,T>::transformDKSRC(
   //check the domain of incoming field
   const Layout_t& in_layout = f.getLayout();
   const Domain_t& in_dom = in_layout.getDomain();
-   
+
   PAssert( this->checkDomain(this->getDomain(), in_dom) );
 
   unsigned nTransformDims = this->numTransformDims();
@@ -1167,7 +1167,7 @@ FFT<RCTransform,Dim,T>::transformDKSRC(
   //*** using tempRField_m and transposing f field ***//
   /*
   RealField_t* tempR = tempRField_m;
-    
+
   if (!constInput) {
     // see if we can use input field f as a temporary
     bool skipTemp = true;
@@ -1197,7 +1197,7 @@ FFT<RCTransform,Dim,T>::transformDKSRC(
     if (skipTemp)
       tempR = &f;
   }
-  
+
   // if we're not using input as a temporary ...
   if (tempR != &f) {
     // transpose and permute to real field with transform dim first
@@ -1225,7 +1225,7 @@ FFT<RCTransform,Dim,T>::transformDKSRC(
     NR_g[d] = (int)tempR->getDomain()[d].length();
     NC_g[d] = NR_g[d];
   }
-  NC_g[0] = (NC_g[0] / 2) + 1;	
+  NC_g[0] = (NC_g[0] / 2) + 1;
 	
   //get global and local domain sizes	
   int sizereal = NR_l[0]*NR_l[1]*NR_l[2];
@@ -1279,8 +1279,8 @@ FFT<RCTransform,Dim,T>::transformDKSRC(
       //dksbase.writeData<T>(real_ptr, localreal, totalreal);
     }
     
-    //call real to complex fft   
-    dksbase.callR2CFFT(real_ptr, comp_ptr, nTransformDims, (int*)NR_g, streamId); 
+    //call real to complex fft
+    dksbase.callR2CFFT(real_ptr, comp_ptr, nTransformDims, (int*)NR_g, streamId);
 
     //normalize fft
     if (direction == +1)
@@ -1478,7 +1478,7 @@ FFT<RCTransform,Dim,T>::transform(
   }
 
   //int id[3] = {idx[Ippl::myNode()], idy[Ippl::myNode()], idz[Ippl::myNode()]};
-  //int cid[3] = {cidx[Ippl::myNode()], cidy[Ippl::myNode()], cidz[Ippl::myNode()]};	
+  //int cid[3] = {cidx[Ippl::myNode()], cidy[Ippl::myNode()], cidz[Ippl::myNode()]};
 
   int ierr;
   void *real_ptr, *comp_ptr;
@@ -1494,7 +1494,7 @@ FFT<RCTransform,Dim,T>::transform(
       //gather data from different mpi processes directly into gpu buffer
       base.gather3DData( real_ptr, localreal, sizereal, MPI_DOUBLE, NR_g, NR_l, idx, idy, idz, 
 			 Ippl::getNodes(), Ippl::myNode(), 0, Ippl::getComm() );
-      
+
     } else {
       //write real data to device
       ierr = base.writeData<T>(real_ptr, localreal, totalreal);
@@ -1508,9 +1508,9 @@ FFT<RCTransform,Dim,T>::transform(
       //scatter data to different mpi processes directly from gpu buffer
       MPI_Barrier( Ippl::getComm() );
       
-      base.scatter3DData(comp_ptr, localcomp, sizecomp, MPI_DOUBLE_COMPLEX, NC_g, NC_l, cidx, cidy, 
+      base.scatter3DData(comp_ptr, localcomp, sizecomp, MPI_DOUBLE_COMPLEX, NC_g, NC_l, cidx, cidy,
 			 cidz, Ippl::getNodes(), Ippl::myNode(), 0, Ippl::getComm() );
-      
+
     } else {
       //read complex data from device
       base.readData<Complex_t>(comp_ptr, localcomp, totalcomp);
@@ -1521,7 +1521,7 @@ FFT<RCTransform,Dim,T>::transform(
     base.freeMemory<Complex_t>(comp_ptr, totalcomp);
     
   } else {
-    
+
     //send data via gatherv to gpu controled by root process
     base.gather3DData( NULL, localreal, sizereal, MPI_DOUBLE, NR_g, NR_l, idx, idy, idz, 
 		       Ippl::getNodes(), Ippl::myNode(), 0, Ippl::getComm() );
@@ -1529,7 +1529,7 @@ FFT<RCTransform,Dim,T>::transform(
     MPI_Barrier(Ippl::getComm());
     base.scatter3DData(NULL, localcomp, sizecomp, MPI_DOUBLE_COMPLEX, NC_g, NC_l, cidx, cidy, cidz, 
 		       Ippl::getNodes(), Ippl::myNode(), 0, Ippl::getComm() );
-    		
+
   }
 	
   //assign complex field
@@ -1890,7 +1890,7 @@ FFT<RCTransform,Dim,T>::transformDKSCR(
   /*** using tempRField_m and transposing to g field in the end ***/
   /*
   bool skipTemp = true;
-  
+
   // more rigorous match required here; check that layouts are identical
   if (!(out_layout == *tempRLayout_m)) {
     skipTemp = false;
@@ -1963,12 +1963,12 @@ FFT<RCTransform,Dim,T>::transformDKSCR(
   }
     
   int id[3] = {idx[Ippl::myNode()], idy[Ippl::myNode()], idz[Ippl::myNode()]};
- 
+
   /* DKS part */
   if (Ippl::myNode() == 0) {
     
     //call real to complex fft
-    dksbase.callC2RFFT(real_ptr, comp_ptr, nTransformDims, (int*)NR_g, streamId);   
+    dksbase.callC2RFFT(real_ptr, comp_ptr, nTransformDims, (int*)NR_g, streamId);
 
     //normalize
     if (direction == +1)
@@ -2099,11 +2099,11 @@ FFT<RCTransform,Dim,T>::transform(
   else 
     tempR = tempRField_m;
 	
-  
+
     //unsigned nTransformDims = this->numTransformDims();
     //RealField_t* tempR = &g;
     //ComplexField_t* temp = &f;
-  
+
 	
   typename RealField_t::const_iterator_if rl_i, rl_end = tempR->end_if();
   rl_i = tempR->begin_if();
@@ -2141,7 +2141,7 @@ FFT<RCTransform,Dim,T>::transform(
   int *cidx = new int[Ippl::getNodes()];
   int *cidy = new int[Ippl::getNodes()];
   int *cidz = new int[Ippl::getNodes()];
-  
+
   for (typename Layout_t::const_iterator_iv i_s = temp->getLayout().begin_iv(); i_s != temp->getLayout().end_iv(); ++i_s) {
     Domain_t tmp = (*i_s).second->getDomain();
     int node = (*i_s).second->getNode();
@@ -2158,12 +2158,12 @@ FFT<RCTransform,Dim,T>::transform(
     cidy[node] = tmp[1].min();
     cidz[node] = tmp[2].min();
   }
-  
+
   //local vnodes get starting position for real field subdomains
   int *idx = new int[Ippl::getNodes()];
   int *idy = new int[Ippl::getNodes()];
   int *idz = new int[Ippl::getNodes()];
-  
+
   for (typename Layout_t::const_iterator_iv i_s = tempR->getLayout().begin_iv(); i_s != tempR->getLayout().end_iv(); ++i_s) {
     Domain_t tmp = (*i_s).second->getDomain();
     int node = (*i_s).second->getNode();
@@ -2180,9 +2180,9 @@ FFT<RCTransform,Dim,T>::transform(
     idy[node] = tmp[1].min();
     idz[node] = tmp[2].min();
   }
-  
+
   //int id[3] = {idx[Ippl::myNode()], idy[Ippl::myNode()], idz[Ippl::myNode()]};
-  //int cid[3] = {cidx[Ippl::myNode()], cidy[Ippl::myNode()], cidz[Ippl::myNode()]};	
+  //int cid[3] = {cidx[Ippl::myNode()], cidy[Ippl::myNode()], cidz[Ippl::myNode()]};
 
   //do the FFT on GPU    
   int ierr;
@@ -2196,7 +2196,7 @@ FFT<RCTransform,Dim,T>::transform(
     comp_ptr = base.allocateMemory<Complex_t>(totalcomp, ierr);
     
     if (Ippl::getNodes() > 1) {
-      base.gather3DData( comp_ptr, localcomp, sizecomp, MPI_DOUBLE_COMPLEX, NC_g, NC_l, 
+      base.gather3DData( comp_ptr, localcomp, sizecomp, MPI_DOUBLE_COMPLEX, NC_g, NC_l,
 			 cidx, cidy, cidz, Ippl::getNodes(), Ippl::myNode(), 0, Ippl::getComm() );
 
     } else {
@@ -2213,7 +2213,7 @@ FFT<RCTransform,Dim,T>::transform(
       MPI_Barrier(Ippl::getComm());
       base.scatter3DData(real_ptr, localreal, sizereal, MPI_DOUBLE, NR_g, NR_l, idx, idy, idz, 
 			 Ippl::getNodes(), Ippl::myNode(), 0, Ippl::getComm() );
-      
+
     } else {
       //read real data from device
       base.readData<T>(real_ptr, localreal, totalreal);
diff --git a/ippl/src/Field/BCond.h b/ippl/src/Field/BCond.h
index 809c14a0f18eea197d5b1d7567613d6c1f6b7a99..9315fead27c6c8b04103bbccba7302697016ff3e 100644
--- a/ippl/src/Field/BCond.h
+++ b/ippl/src/Field/BCond.h
@@ -308,19 +308,19 @@ public:
 //BENI adds Periodic Boundary Conditions for Interpolations///////////
 //////////////////////////////////////////////////////////////////////
 template<class T,
-         unsigned D, 
-         class M=UniformCartesian<D,double>, 
+         unsigned D,
+         class M=UniformCartesian<D,double>,
          class C=typename M::DefaultCentering>
 class InterpolationFace : public BCondBase<T,D,M,C>
 {
 public:
-  // Constructor takes zero, one, or two int's specifying components of 
+  // Constructor takes zero, one, or two int's specifying components of
   // multicomponent types like Vektor/Tenzor/Anti/SymTenzor this BC applies to.
   // Zero int's specified means apply to all components; one means apply to
   // component (i), and two means apply to component (i,j),
   typedef BCondBase<T,D,M,C> BCondBaseTDMC;
 
-  InterpolationFace(unsigned f, 
+  InterpolationFace(unsigned f,
 	       int i = BCondBaseTDMC::allComponents,
 	       int j = BCondBaseTDMC::allComponents);
 
@@ -383,8 +383,8 @@ public:
 // BENI adds parallel Interpolation Face
 //////////////////////////////////////////////////////////////////////
 
-template<class T, unsigned D, 
-         class M=UniformCartesian<D,double>, 
+template<class T, unsigned D,
+         class M=UniformCartesian<D,double>,
          class C=typename M::DefaultCentering>
 class ParallelInterpolationFace : public InterpolationFace<T,D,M,C>
 {
@@ -398,10 +398,10 @@ public:
 
   typedef BCondBase<T,D,M,C> Base_t;
 
-  ParallelInterpolationFace(unsigned f, 
+  ParallelInterpolationFace(unsigned f,
 		       int i = Base_t::allComponents,
 		       int j = Base_t::allComponents)
-    : InterpolationFace<T,D,M,C>(f,i,j) 
+    : InterpolationFace<T,D,M,C>(f,i,j)
   { }
 
   // Apply the boundary condition to a particular Field.
diff --git a/ippl/src/Field/BCond.hpp b/ippl/src/Field/BCond.hpp
index 14fb64fcff1f8c963048ca3363cc9cc938b00ad5..365746df6a2196a4986ad9454e7ca17aef8cf33b 100644
--- a/ippl/src/Field/BCond.hpp
+++ b/ippl/src/Field/BCond.hpp
@@ -51,7 +51,7 @@ int BCondBase<T,D,M,C>::allComponents = -9999;
 
 // Use this macro to specialize PETE_apply functions for component-wise
 // operators and built-in types and print an error message.
- 
+
 #define COMPONENT_APPLY_BUILTIN(OP,T)                                       \
 inline void PETE_apply(const OP<T>&, T&, const T&)                          \
 {                                                                           \
@@ -2129,7 +2129,7 @@ void ParallelInterpolationFace<T,D,M,C>::apply( Field<T,D,M,C>& A )
 	  const Domain_t dest_domain = dest_lf_alloc.intersect(dest_slab);
 
 	  Domain_t src_domain = dest_domain;
-	  //BENI:sign change for offset occurs when we iterate over destination first and calulate 
+	  //BENI:sign change for offset occurs when we iterate over destination first and calulate
 	  // src domain from dest domain
 	  src_domain[d] = src_domain[d] - offset;
 
@@ -2393,7 +2393,7 @@ void ParallelInterpolationFace<T,D,M,C>::apply( Field<T,D,M,C>& A )
       const Domain_t dest_domain = dest_lf_alloc.intersect(dest_slab);
 
       Domain_t src_domain = dest_domain;
-	  //BENI:sign change for offset occurs when we iterate over destination first and calulate 
+	  //BENI:sign change for offset occurs when we iterate over destination first and calulate
 	  // src domain from dest domain
       src_domain[d] = src_domain[d] - offset;
 
@@ -2702,9 +2702,10 @@ ExtrapolateFaceBCApply2(const NDIndex<D> &dest, const NDIndex<D> &src,
 	}
       else
 	{
-	  OpExtrapolateComponent<T>
-	    op(ef.getOffset(),ef.getSlope(),ef.getComponent());
-	  PETE_apply(op, a, b);
+          int d = (ef.getComponent() % D + D) % D;
+          OpExtrapolateComponent<T>
+            op(ef.getOffset(),ef.getSlope(),d);
+          PETE_apply(op, a, b);
 	}
       if (a == aref)
 	{
@@ -5662,4 +5663,4 @@ void PatchBC<T,D,M,C>::apply( Field<T,D,M,C>& A )
  * $RCSfile: BCond.cpp,v $   $Author: adelmann $
  * $Revision: 1.1.1.1 $   $Date: 2003/01/23 07:40:26 $
  * IPPL_VERSION_ID: $Id: BCond.cpp,v 1.1.1.1 2003/01/23 07:40:26 adelmann Exp $
- ***************************************************************************/
+ ***************************************************************************/
\ No newline at end of file
diff --git a/ippl/src/Field/CMakeLists.txt b/ippl/src/Field/CMakeLists.txt
index 8ca25cf24e78831499fb3043cc591fe2b8bf7d3a..c652050d9b45e75da9642f88910a4ed1b047587c 100644
--- a/ippl/src/Field/CMakeLists.txt
+++ b/ippl/src/Field/CMakeLists.txt
@@ -38,7 +38,7 @@ INCLUDE_DIRECTORIES (
   ${CMAKE_CURRENT_SOURCE_DIR}
 )
 
-ADD_SOURCES (${_SRCS})
-ADD_HEADERS (${_HDRS})
+ADD_IPPL_SOURCES (${_SRCS})
+ADD_IPPL_HEADERS (${_HDRS})
 
 INSTALL (FILES ${_HDRS} DESTINATION include/Field)
diff --git a/ippl/src/FieldLayout/CMakeLists.txt b/ippl/src/FieldLayout/CMakeLists.txt
index 223a59e628641b6c45c2fecfaf85d8600940b7ec..3579ab5a306794975882b4c67f9d9e3ee0faa8e2 100644
--- a/ippl/src/FieldLayout/CMakeLists.txt
+++ b/ippl/src/FieldLayout/CMakeLists.txt
@@ -25,7 +25,7 @@ INCLUDE_DIRECTORIES (
   ${CMAKE_CURRENT_SOURCE_DIR}
 )
 
-ADD_SOURCES (${_SRCS})
-ADD_HEADERS (${_HDRS})
+ADD_IPPL_SOURCES (${_SRCS})
+ADD_IPPL_HEADERS (${_HDRS})
 
 INSTALL (FILES ${_HDRS} DESTINATION include/FieldLayout)
diff --git a/ippl/src/Index/CMakeLists.txt b/ippl/src/Index/CMakeLists.txt
index e6c5e483bd7abc7493fa76020471c1b1c9cb6605..b878276d67947975d1dbddb4873e703111014ee9 100644
--- a/ippl/src/Index/CMakeLists.txt
+++ b/ippl/src/Index/CMakeLists.txt
@@ -20,7 +20,7 @@ INCLUDE_DIRECTORIES (
   ${CMAKE_CURRENT_SOURCE_DIR}
 )
 
-ADD_SOURCES (${_SRCS})
-ADD_HEADERS (${_HDRS})
+ADD_IPPL_SOURCES (${_SRCS})
+ADD_IPPL_HEADERS (${_HDRS})
 
 INSTALL (FILES ${_HDRS} DESTINATION include/Index)
diff --git a/ippl/src/Meshes/CMakeLists.txt b/ippl/src/Meshes/CMakeLists.txt
index 67ca96ce690a1dd2bd8e5c96e313ede3c77758ab..cccc91e1d5dc82593dc6738ec3e29ffae2466aa7 100644
--- a/ippl/src/Meshes/CMakeLists.txt
+++ b/ippl/src/Meshes/CMakeLists.txt
@@ -19,7 +19,7 @@ INCLUDE_DIRECTORIES (
   ${CMAKE_CURRENT_SOURCE_DIR}
 )
 
-ADD_SOURCES (${_SRCS})
-ADD_HEADERS (${_HDRS})
+ADD_IPPL_SOURCES (${_SRCS})
+ADD_IPPL_HEADERS (${_HDRS})
 
 INSTALL (FILES ${_HDRS} DESTINATION include/Meshes)
diff --git a/ippl/src/Meshes/UniformCartesian.hpp b/ippl/src/Meshes/UniformCartesian.hpp
index 026376b01f7d17abaaa13191ce36de7e722da630..eb54dece339fe5477c0bf474236242cc34daaf63 100644
--- a/ippl/src/Meshes/UniformCartesian.hpp
+++ b/ippl/src/Meshes/UniformCartesian.hpp
@@ -480,10 +480,7 @@ MFLOAT UniformCartesian<Dim,MFLOAT>::
 get_meshSpacing(unsigned d) const
 {
   PAssert(d<Dim);
-#pragma GCC diagnostic push
-#pragma GCC diagnostic ignored "-Warray-bounds"
   MFLOAT ms = meshSpacing[d];
-#pragma GCC diagnostic pop
   return ms;
 }
 
diff --git a/ippl/src/Message/CMakeLists.txt b/ippl/src/Message/CMakeLists.txt
index b799250d91fa5463b85e3867f0b8bc9ff247ab89..7e1725e4389e478454f955cbee708549ebf095a5 100644
--- a/ippl/src/Message/CMakeLists.txt
+++ b/ippl/src/Message/CMakeLists.txt
@@ -27,7 +27,7 @@ INCLUDE_DIRECTORIES (
   ${CMAKE_CURRENT_SOURCE_DIR}
 )
 
-ADD_SOURCES (${_SRCS})
-ADD_HEADERS (${_HDRS})
+ADD_IPPL_SOURCES (${_SRCS})
+ADD_IPPL_HEADERS (${_HDRS})
 
 INSTALL (FILES ${_HDRS} DESTINATION include/Message)
diff --git a/ippl/src/Message/GlobalComm.hpp b/ippl/src/Message/GlobalComm.hpp
index f864200591e227122daeae8c4cf898824e78bd45..8619dab560f9f549504af94ccbc6f158d0658b3a 100644
--- a/ippl/src/Message/GlobalComm.hpp
+++ b/ippl/src/Message/GlobalComm.hpp
@@ -53,7 +53,7 @@ template <class InputIterator, class OutputIterator, class ReduceOp>
 bool reduce(Communicate& comm, InputIterator s1, InputIterator s2,
             OutputIterator t1, const ReduceOp& op, bool *IncludeVal)
 {
-   
+
 
     // Inform dbgmsg("reduce-vector", INFORM_ALL_NODES);
 
@@ -188,26 +188,12 @@ bool reduce(Communicate& comm, InputIterator s1, InputIterator s2,
 
 ////////////////////////////////////////////////////////////////////////////
 // same as above, but this uses the default Communicate object
-#if (defined(__GNUG__) && !defined(__ICC))
-#if (__GNUC_MAJOR__ >= 4 && __GNUC_MINOR__ >= 6)
-#pragma GCC diagnostic push
-#endif
-#pragma GCC diagnostic ignored "-Warray-bounds"
-#endif
 template <class InputIterator, class OutputIterator, class ReduceOp>
 bool reduce(InputIterator s1, InputIterator s2,
             OutputIterator t1, const ReduceOp& op, bool *IncludeVal)
-{   
-
+{
     return reduce(*Ippl::Comm, s1, s2, t1, op, IncludeVal);
 }
-#if (defined(__GNUG__) && !defined(__ICC))
-#if (__GNUC_MAJOR__ >= 4 && __GNUC_MINOR__ >= 6)
-#pragma GCC diagnostic pop
-#else
-#pragma GCC diagnostic error "-Warray-bounds"
-#endif
-#endif
 
 
 ////////////////////////////////////////////////////////////////////////////
@@ -219,7 +205,7 @@ bool reduce(InputIterator s1, InputIterator s2,
 template <class T, class ReduceOp>
 bool reduce_masked(Communicate& comm, T& input, T& output,
                    const ReduceOp& op, bool IncludeVal)
-{    
+{
 
     // Inform dbgmsg("reduce_masked", INFORM_ALL_NODES);
 
@@ -453,4 +439,4 @@ bool scatter(InputIterator s1, InputIterator s2,
 {
 
     return scatter(*Ippl::Comm, s1, s2, t1, target_node, target_position, op);
-}
+}
\ No newline at end of file
diff --git a/ippl/src/PETE/CMakeLists.txt b/ippl/src/PETE/CMakeLists.txt
index 90ba3d1cd61b084c1a46378213672a66f3c81dbd..eb2279047bba29cb46d089fe9427e0eb549219b3 100644
--- a/ippl/src/PETE/CMakeLists.txt
+++ b/ippl/src/PETE/CMakeLists.txt
@@ -12,7 +12,7 @@ INCLUDE_DIRECTORIES (
   ${CMAKE_CURRENT_SOURCE_DIR}
 )
 
-ADD_SOURCES (${_SRCS})
-ADD_HEADERS (${_HDRS})
+ADD_IPPL_SOURCES (${_SRCS})
+ADD_IPPL_HEADERS (${_HDRS})
 
 INSTALL (FILES ${_HDRS} DESTINATION include/PETE)
diff --git a/ippl/src/PETE/IpplTypeComputations.h b/ippl/src/PETE/IpplTypeComputations.h
index 241a7d031d4aaf1fc94d734c961a4092e97f18d9..177f344e344486a7a0ed3648a8a2571e5b8a9951 100644
--- a/ippl/src/PETE/IpplTypeComputations.h
+++ b/ippl/src/PETE/IpplTypeComputations.h
@@ -840,30 +840,30 @@ struct PETEUnaryReturn<AntiSymTenzor<T,Dim>, FnCofactors> {
 // Life is pitiful and barely worth living without partial specialization.
 // Sigh, I guess we'll limp along...
 
-#define _UNARY_TENSOR_RETURNS_(T, D) 
-template<> struct PETEUnaryReturn<Tenzor<T,D>, FnTrace>                     
-{ typedef T type; };                                                        
-template<> struct PETEUnaryReturn<SymTenzor<T,D>, FnTrace>                  
-{ typedef T type; };                                                        
-template<> struct PETEUnaryReturn<AntiSymTenzor<T,D>, FnTrace>              
-{ typedef T type; };                                                        
-template<> struct PETEUnaryReturn<Tenzor<T,D>, FnDet>                       
-{ typedef T type; };                                                        
-template<> struct PETEUnaryReturn<SymTenzor<T,D>, FnDet>                    
-{ typedef T type; };                                                        
-template<> struct PETEUnaryReturn<AntiSymTenzor<T,D>, FnDet>                
-{ typedef T type; };                                                        
-template<> struct PETEUnaryReturn<Tenzor<T,D>, FnTranspose>                 
-{ typedef Tenzor<T,D> type; };                                              
-template<> struct PETEUnaryReturn<SymTenzor<T,D>, FnTranspose>              
-{ typedef SymTenzor<T,D> type; };					
-template<> struct PETEUnaryReturn<AntiSymTenzor<T,D>, FnTranspose>      
-{ typedef AntiSymTenzor<T,D> type; };					
-template<> struct PETEUnaryReturn<Tenzor<T,D>, FnCofactors>             
-{ typedef Tenzor<T,D> type; };                                          
-template<> struct PETEUnaryReturn<SymTenzor<T,D>, FnCofactors>          
-{ typedef Tenzor<T,D> type; };						
-template<> struct PETEUnaryReturn<AntiSymTenzor<T,D>, FnCofactors>      
+#define _UNARY_TENSOR_RETURNS_(T, D)
+template<> struct PETEUnaryReturn<Tenzor<T,D>, FnTrace>
+{ typedef T type; };
+template<> struct PETEUnaryReturn<SymTenzor<T,D>, FnTrace>
+{ typedef T type; };
+template<> struct PETEUnaryReturn<AntiSymTenzor<T,D>, FnTrace>
+{ typedef T type; };
+template<> struct PETEUnaryReturn<Tenzor<T,D>, FnDet>
+{ typedef T type; };
+template<> struct PETEUnaryReturn<SymTenzor<T,D>, FnDet>
+{ typedef T type; };
+template<> struct PETEUnaryReturn<AntiSymTenzor<T,D>, FnDet>
+{ typedef T type; };
+template<> struct PETEUnaryReturn<Tenzor<T,D>, FnTranspose>
+{ typedef Tenzor<T,D> type; };
+template<> struct PETEUnaryReturn<SymTenzor<T,D>, FnTranspose>
+{ typedef SymTenzor<T,D> type; };
+template<> struct PETEUnaryReturn<AntiSymTenzor<T,D>, FnTranspose>
+{ typedef AntiSymTenzor<T,D> type; };
+template<> struct PETEUnaryReturn<Tenzor<T,D>, FnCofactors>
+{ typedef Tenzor<T,D> type; };
+template<> struct PETEUnaryReturn<SymTenzor<T,D>, FnCofactors>
+{ typedef Tenzor<T,D> type; };
+template<> struct PETEUnaryReturn<AntiSymTenzor<T,D>, FnCofactors>
 { typedef SymTenzor<T,D> type; };
 
 _UNARY_TENSOR_RETURNS_(short,1U)
diff --git a/ippl/src/Particle/BoxParticleCachingPolicy.h b/ippl/src/Particle/BoxParticleCachingPolicy.h
index 1a6d74fc2c1ceb3fe033d66067f9c097d8809b74..c5066c3b42f7befaee30182e3506a84b0937c19a 100644
--- a/ippl/src/Particle/BoxParticleCachingPolicy.h
+++ b/ippl/src/Particle/BoxParticleCachingPolicy.h
@@ -2,10 +2,10 @@
 #define BOX_PARTICLE_CACHING_POLICY
 
 /*
- * 
+ *
  * The Box caching layout ensures that each node has all ghost particles
  * for each external particle that is inside an extended bounding box
- * 
+ *
  */
 
 
@@ -25,12 +25,12 @@ public:
 	{
 		std::fill(boxDimension, boxDimension+Dim, T());
 	}
-	
+
 	void setCacheDimension(int d, T length)
 	{
 		boxDimension[d] = length;
 	}
-	
+
 	void setAllCacheDimensions(T length)
 	{
 		std::fill(boxDimension, boxDimension+Dim, length);
@@ -45,13 +45,13 @@ template<class C>
 
 		typename RegionLayout<T,Dim,Mesh>::iterator_iv  localVN = RLayout.begin_iv();
 		typename RegionLayout<T,Dim,Mesh>::iterator_iv localVNend = RLayout.end_iv();
-		
+
 		regions.clear();
-	
-	
+
+
 		//fill in boundary conditions
 		std::fill(periodic, periodic+2*Dim, false);
-		
+
 		if (PLayout.getUpdateFlag(ParticleLayout<T,Dim>::BCONDS))
 		{
 			ParticleBConds<T,Dim>& pBConds = PLayout.getBConds();
@@ -65,13 +65,13 @@ template<class C>
 				}
 			}
 		}
-				
-		
+
+
 		for (;localVN!=localVNend;++localVN)
 		{
 			//get local domain
 			NDRegion<T,Dim> ldom = (*localVN).second->getDomain();
-		
+
 			//extrude local domain
 			NDRegion<T,Dim> exdom;
 			for(unsigned int d = 0;d<Dim;++d)
@@ -100,38 +100,38 @@ template<class C>
 				std::fill(onoff, onoff+Dim, 0);
 				while(true)
 				{
-					
+
 					NDRegion<T,Dim> chckdom;
 					for(unsigned int d = 0;d<Dim;++d)
 					{
 						chckdom[d] = PRegion<T>(ldom[d].first()- boxDimension[d]+onoff[d]*offset[d],
 												ldom[d].last() + boxDimension[d]+onoff[d]*offset[d]);
 					}
-					
+
 					//get touched external domains
 					typename RegionLayout<T,Dim,Mesh>::touch_range_dv touchRange = RLayout.touch_range_rdv(chckdom);
 
-				
+
 					typename RegionLayout<T,Dim,Mesh>::touch_iterator_dv i;
 
-				
+
 					for(i = touchRange.first; i != touchRange.second; ++i)
 					{
 						int node = (*i).second->getNode();
 						if(node == Ippl::myNode())//don't add local node
 							continue;
 						NDRegion<T,Dim> dom = (*i).second->getDomain();
-						Offset_t tmpoffset;	
+						Offset_t tmpoffset;
 						for(unsigned int d = 0;d<Dim;++d)
-						{	
+						{
 							dom[d] = PRegion<T>(dom[d].first() - onoff[d]*offset[d],
 												dom[d].last()  - onoff[d]*offset[d]);
 							tmpoffset[d] = onoff[d]*offset[d];
 						}
-							
+
 						regions[node].push_back(std::make_pair(dom,tmpoffset));
 					}
-					
+
 					//generate next combinations. this is basically a binary incrementer
 					unsigned int j = 0;
 					for(;j<Dim;++j)
@@ -141,21 +141,21 @@ template<class C>
 						if((onoff[j] = !onoff[j]))
 							break;//flip and continue if there's a "carry"
 					}
-					
+
 					if(j==Dim)
-						break;					
+						break;
 				}
-	
+
 		}
 	}
-	
+
 template<class C>
 	void updateGhostParticles(
 		IpplParticleBase< ParticleSpatialLayout<T,Dim,Mesh,C > > &PData,
 		ParticleSpatialLayout<T, Dim, Mesh, C > &PLayout
 		)
 	{
-		
+
 		Ippl::Comm->barrier();
 		typedef typename std::map<unsigned, std::list<std::pair<NDRegion<T,Dim>, Offset_t> > >::iterator m_iterator;
 
@@ -163,40 +163,40 @@ template<class C>
 		PData.ghostDestroy(PData.getGhostNum(), 0);
 
 		//get tag
-		int tag = Ippl::Comm->next_tag(P_SPATIAL_GHOST_TAG, P_LAYOUT_CYCLE); 
-		
+		int tag = Ippl::Comm->next_tag(P_SPATIAL_GHOST_TAG, P_LAYOUT_CYCLE);
+
 		//these are needed to free data for nonblocking sends
 		std::vector<MPI_Request> requests;
 		std::vector<MsgBuffer*> buffers;
-		
+
 		//for each possible target node
 		for(m_iterator n = regions.begin();n!=regions.end();++n)
 		{
 			int node = n->first;
-			
+
 			//find particles that need to be sent
 			std::vector<size_t> sendlist;
-			std::vector<Offset_t> offsetlist;		
+			std::vector<Offset_t> offsetlist;
 			for(typename std::list<std::pair<NDRegion<T,Dim>, Offset_t> >::iterator li = n->second.begin();li!=n->second.end();++li)
 			{
 				NDRegion<T, Dim> region = (*li).first;
-							
+
 				for (unsigned int i = 0;i < PData.getLocalNum();++i)
 				{
 					NDRegion<T,Dim> ploc;
 					for (unsigned int d = 0;d < Dim;++d)
 						ploc[d] = PRegion<T>(PData.R[i][d] - boxDimension[d],
 											 PData.R[i][d] + boxDimension[d]);
-					
+
 					if(region.touches(ploc))
 					{
 						sendlist.push_back(i);
 						offsetlist.push_back((*li).second);
 					}
 				}
-			}	
-			
-			
+			}
+
+
 			//and send them
 			if(sendlist.empty())
 			{
@@ -209,17 +209,17 @@ template<class C>
 				MsgBuffer *msgbuf = 0;
 				PData.writeMsgBufferWithOffsets(msgbuf, sendlist,offsetlist);
 				MPI_Request request = Ippl::Comm->raw_isend(msgbuf->getBuffer(), msgbuf->getSize(), node, tag);
-				
+
 				requests.push_back(request);
 				buffers.push_back(msgbuf);
 			}
-			
+
 		}
-		
-		
+
+
 		//receive ghost particles
 		Format *format = PData.getFormat();
-		
+
 		for(unsigned int n = 0;n<regions.size();++n)
 		{
 			int node = Communicate::COMM_ANY_NODE;
@@ -231,7 +231,7 @@ template<class C>
 				PData.readGhostMsgBuffer(&recvbuf, node);
 			}
 		}
-		
+
 		//wait for communication to finish and clean up buffers
         MPI_Waitall(requests.size(), &(requests[0]), MPI_STATUSES_IGNORE);
         for (unsigned int j = 0; j<buffers.size(); ++j)
@@ -239,8 +239,8 @@ template<class C>
 			delete buffers[j]->getFormat();
             delete buffers[j];
         }
-		
-		delete format;	
+
+		delete format;
 	}
 protected:
 	~BoxParticleCachingPolicy() {}
@@ -259,4 +259,4 @@ private:
 	std::map<unsigned, std::list<std::pair<NDRegion<T,Dim>, Offset_t> > > regions;
 };
 
-#endif
+#endif
\ No newline at end of file
diff --git a/ippl/src/Particle/CMakeLists.txt b/ippl/src/Particle/CMakeLists.txt
index 76f463fb5e19030fea028986cb8bc80606655ab7..9c65e4c812a3a59d864d53bf645597f50911574a 100644
--- a/ippl/src/Particle/CMakeLists.txt
+++ b/ippl/src/Particle/CMakeLists.txt
@@ -48,8 +48,8 @@ INCLUDE_DIRECTORIES (
   ${CMAKE_CURRENT_SOURCE_DIR}
 )
 
-ADD_SOURCES (${_SRCS})
-ADD_HEADERS (${_HDRS})
+ADD_IPPL_SOURCES (${_SRCS})
+ADD_IPPL_HEADERS (${_HDRS})
 
 INSTALL (FILES ${_HDRS} DESTINATION include/Particle)
 
diff --git a/ippl/src/Particle/CellParticleCachingPolicy.h b/ippl/src/Particle/CellParticleCachingPolicy.h
index 08ba75295f78c1cee50511f7f7ea9a250e505fc1..b626064ef29eeb57d530589c6fa743378d9b0d84 100644
--- a/ippl/src/Particle/CellParticleCachingPolicy.h
+++ b/ippl/src/Particle/CellParticleCachingPolicy.h
@@ -2,10 +2,10 @@
 #define CELL_PARTICLE_CACHING_POLICY
 
 /*
- * 
+ *
  * The Cell caching layout ensures that each node has all ghost particles
  * for each external particle that is inside a neighboring cell.
- * 
+ *
  */
 
 #include <Particle/BoxParticleCachingPolicy.h>
@@ -17,17 +17,17 @@ public:
 	{
 		std::fill(cells, cells+Dim, 0);
 	}
-	
+
 	void setCacheCellRange(int d, int length)
 	{
 		cells[d] = length;
 	}
-	
+
 	void setAllCacheCellRanges(int length)
 	{
 		std::fill(cells, cells+Dim, length);
 	}
-	
+
 	template<class C>
 	void updateCacheInformation(
 		ParticleSpatialLayout<T, Dim, Mesh, C > &PLayout
@@ -35,10 +35,10 @@ public:
 	{
 		for(int d = 0;d<Dim;++d)
 			BoxParticleCachingPolicy<T,Dim,Mesh>::setCacheDimension(d, cells[d]*PLayout.getLayout().getMesh().get_meshSpacing(d));
-		
+
 		BoxParticleCachingPolicy<T,Dim,Mesh>:: updateCacheInformation(PLayout);
 	}
-	
+
 	template<class C>
 	void updateGhostParticles(
 		IpplParticleBase< ParticleSpatialLayout<T,Dim,Mesh,C > > &PData,
@@ -47,7 +47,7 @@ public:
 	{
 		for(int d = 0;d<Dim;++d)
 			BoxParticleCachingPolicy<T,Dim,Mesh>::setCacheDimension(d, cells[d]*PLayout.getLayout().getMesh().get_meshSpacing(d));
-		
+
 		BoxParticleCachingPolicy<T,Dim,Mesh>::updateGhostParticles(PData, PLayout);
 	}
 protected:
@@ -56,4 +56,4 @@ private:
 	int cells[Dim];
 };
 
-#endif
+#endif
\ No newline at end of file
diff --git a/ippl/src/Particle/IntTSC.h b/ippl/src/Particle/IntTSC.h
index 282c54ddbbebacbeb0442f9dc318952a3476e21f..a5a9467e156fc1fcb1a0d557f0dbe5a6348b4225 100644
--- a/ippl/src/Particle/IntTSC.h
+++ b/ippl/src/Particle/IntTSC.h
@@ -2,7 +2,7 @@
 /***************************************************************************
  *
  * The IPPL Framework
- * 
+ *
  *
  * Visit http://people.web.psi.ch/adelmann/ for more details
  *
@@ -285,7 +285,7 @@ public:
     *fiter += .25*(3.-4.dpos(0)*dpos(0)) * pdata;
     fiter.offset(-1) += .125*(1.-4.*dpos(0)+4.*dpos(0)*dpos(0)) * pdata;
     fiter.offset(+1) += .125*(1.+4.*dpos(0)+4.*dpos(0)*dpos(0)) * pdata;
- 	*/
+	*/
 	auto W = [dpos](unsigned p, unsigned i) {
 		if (p==-1) return .125*(1.-4.*dpos(i)+4.*dpos(i)*dpos(i));
 		else if (p==0) return .25*(3.-4.*dpos(i)*dpos(i));
@@ -396,7 +396,7 @@ public:
 			/*
 	pdata = .25*(3.-4.dpos(0)*dpos(0)) * (*fiter) +
 			.125*(1.-4.*dpos(0)+4.*dpos(0)*dpos(0)) * fiter.offset(-1) +
-			 .125*(1.+4.*dpos(0)+4.*dpos(0)*dpos(0)) * fiter.offset(+1); 
+			 .125*(1.+4.*dpos(0)+4.*dpos(0)*dpos(0)) * fiter.offset(+1);
 */
    auto W = [dpos](unsigned p, unsigned i) {
 		if (p==-1) return .125*(1.-4.*dpos(i)+4.*dpos(i)*dpos(i));
@@ -407,7 +407,7 @@ public:
 	for (int p0=-1; p0<=1; ++p0) {
 				 pdata += W(p0,0)*fiter.offset(p0);
 	}
- 
+
     return;
   }
 
@@ -438,9 +438,9 @@ public:
 	/*
 	pdata = .25*(3.-4.dpos(0)*dpos(0)) * (*fiter) +
 			.125*(1.-4.*dpos(0)+4.*dpos(0)*dpos(0)) * fiter.offset(-1) +
-			 .125*(1.+4.*dpos(0)+4.*dpos(0)*dpos(0)) * fiter.offset(+1); 
+			 .125*(1.+4.*dpos(0)+4.*dpos(0)*dpos(0)) * fiter.offset(+1);
 	 */
- 	auto W = [dpos](unsigned p, unsigned i) {
+	auto W = [dpos](unsigned p, unsigned i) {
 		if (p==-1) return .125*(1.-4.*dpos(i)+4.*dpos(i)*dpos(i));
 		else if (p==0) return .25*(3.-4.*dpos(i)*dpos(i));
 		else if (p==+1) return .125*(1.+4.*dpos(i)+4.*dpos(i)*dpos(i)); };
@@ -467,7 +467,7 @@ public:
 	/*
 	pdata = .25*(3.-4.dpos(0)*dpos(0)) * (*fiter) +
 			.125*(1.-4.*dpos(0)+4.*dpos(0)*dpos(0)) * fiter.offset(-1) +
-			 .125*(1.+4.*dpos(0)+4.*dpos(0)*dpos(0)) * fiter.offset(+1); 
+			 .125*(1.+4.*dpos(0)+4.*dpos(0)*dpos(0)) * fiter.offset(+1);
 	 */
 	 auto W = [dpos](unsigned p, unsigned i) {
 		if (p==-1) return .125*(1.-4.*dpos(i)+4.*dpos(i)*dpos(i));
@@ -521,7 +521,7 @@ public:
     // accumulate into local elements
 	/*
     *fiter += .25*(3.-4.dpos(0)*dpos(0)) * .25*(3.-4.dpos(1)*dpos(1)) * pdata;
-    fiter.offset(-1,-1) += .125*(1.-4.*dpos(0)+4.*dpos(0)*dpos(0)) *  .125*(1.-4.*dpos(1)+4.*dpos(1)*dpos(1)) * pdata;   
+    fiter.offset(-1,-1) += .125*(1.-4.*dpos(0)+4.*dpos(0)*dpos(0)) *  .125*(1.-4.*dpos(1)+4.*dpos(1)*dpos(1)) * pdata;
     fiter.offset(-1,0) += .125*(1.-4.*dpos(0)+4.*dpos(0)*dpos(0)) * .25*(3.-4.dpos(1)*dpos(1)) * pdata;
 	fiter.offset(-1,+1) += .125*(1.-4.*dpos(0)+4.*dpos(0)*dpos(0)) *  .125*(1.+4.*dpos(1)+4.*dpos(1)*dpos(1)) * pdata;
 	fiter.offset(0,-1) += .25*(3.-4.dpos(0)*dpos(0)) * .125*(1.-4.*dpos(1)+4.*dpos(1)*dpos(1)) * pdata;
@@ -569,7 +569,7 @@ public:
     // accumulate into local elements
 	/*
    *fiter += .25*(3.-4.dpos(0)*dpos(0)) * .25*(3.-4.dpos(1)*dpos(1)) * pdata;
-    fiter.offset(-1,-1) += .125*(1.-4.*dpos(0)+4.*dpos(0)*dpos(0)) *  .125*(1.-4.*dpos(1)+4.*dpos(1)*dpos(1)) * pdata;   
+    fiter.offset(-1,-1) += .125*(1.-4.*dpos(0)+4.*dpos(0)*dpos(0)) *  .125*(1.-4.*dpos(1)+4.*dpos(1)*dpos(1)) * pdata;
     fiter.offset(-1,0) += .125*(1.-4.*dpos(0)+4.*dpos(0)*dpos(0)) * .25*(3.-4.dpos(1)*dpos(1)) * pdata;
 	fiter.offset(-1,+1) += .125*(1.-4.*dpos(0)+4.*dpos(0)*dpos(0)) *  .125*(1.+4.*dpos(1)+4.*dpos(1)*dpos(1)) * pdata;
 	fiter.offset(0,-1) += .25*(3.-4.dpos(0)*dpos(0)) * .125*(1.-4.*dpos(1)+4.*dpos(1)*dpos(1)) * pdata;
@@ -607,7 +607,7 @@ public:
     // accumulate into local elements
 	/*
   *fiter += .25*(3.-4.dpos(0)*dpos(0)) * .25*(3.-4.dpos(1)*dpos(1)) * pdata;
-    fiter.offset(-1,-1) += .125*(1.-4.*dpos(0)+4.*dpos(0)*dpos(0)) *  .125*(1.-4.*dpos(1)+4.*dpos(1)*dpos(1)) * pdata;   
+    fiter.offset(-1,-1) += .125*(1.-4.*dpos(0)+4.*dpos(0)*dpos(0)) *  .125*(1.-4.*dpos(1)+4.*dpos(1)*dpos(1)) * pdata;
     fiter.offset(-1,0) += .125*(1.-4.*dpos(0)+4.*dpos(0)*dpos(0)) * .25*(3.-4.dpos(1)*dpos(1)) * pdata;
 	fiter.offset(-1,+1) += .125*(1.-4.*dpos(0)+4.*dpos(0)*dpos(0)) *  .125*(1.+4.*dpos(1)+4.*dpos(1)*dpos(1)) * pdata;
 	fiter.offset(0,-1) += .25*(3.-4.dpos(0)*dpos(0)) * .125*(1.-4.*dpos(1)+4.*dpos(1)*dpos(1)) * pdata;
@@ -657,9 +657,9 @@ public:
     // accumulate into particle attrib
 	/*
    pdata = 	.25*(3.-4.dpos(0)*dpos(0)) * .25*(3.-4.dpos(1)*dpos(1)) * (*fiter) +
- 			.125*(1.-4.*dpos(0)+4.*dpos(0)*dpos(0)) *  .125*(1.-4.*dpos(1)+4.*dpos(1)*dpos(1)) * fiter.offset(-1,-1) + 
-     		.125*(1.-4.*dpos(0)+4.*dpos(0)*dpos(0)) * .25*(3.-4.dpos(1)*dpos(1)) * fiter.offset(-1,0) +
-			.125*(1.-4.*dpos(0)+4.*dpos(0)*dpos(0)) *  .125*(1.+4.*dpos(1)+4.*dpos(1)*dpos(1)) * fiter.offset(-1,+1) +	
+			.125*(1.-4.*dpos(0)+4.*dpos(0)*dpos(0)) *  .125*(1.-4.*dpos(1)+4.*dpos(1)*dpos(1)) * fiter.offset(-1,-1) +
+		.125*(1.-4.*dpos(0)+4.*dpos(0)*dpos(0)) * .25*(3.-4.dpos(1)*dpos(1)) * fiter.offset(-1,0) +
+			.125*(1.-4.*dpos(0)+4.*dpos(0)*dpos(0)) *  .125*(1.+4.*dpos(1)+4.*dpos(1)*dpos(1)) * fiter.offset(-1,+1) +
 			.25*(3.-4.dpos(0)*dpos(0)) * .125*(1.-4.*dpos(1)+4.*dpos(1)*dpos(1)) * fiter.offset(0,-1) +
 			.25*(3.-4.dpos(0)*dpos(0)) * .125*(1.+4.*dpos(1)+4.*dpos(1)*dpos(1)) * 	fiter.offset(0,+1) +
 			.125*(1.+4.*dpos(0)+4.*dpos(0)*dpos(0)) *  .125*(1.-4.*dpos(1)+4.*dpos(1)*dpos(1)) *fiter.offset(+1,-1) +
@@ -707,15 +707,15 @@ public:
     // accumulate into particle attrib
 	/*
     pdata = 	.25*(3.-4.dpos(0)*dpos(0)) * .25*(3.-4.dpos(1)*dpos(1)) * (*fiter) +
- 			.125*(1.-4.*dpos(0)+4.*dpos(0)*dpos(0)) *  .125*(1.-4.*dpos(1)+4.*dpos(1)*dpos(1)) * fiter.offset(-1,-1) + 
-     		.125*(1.-4.*dpos(0)+4.*dpos(0)*dpos(0)) * .25*(3.-4.dpos(1)*dpos(1)) * fiter.offset(-1,0) +
-			.125*(1.-4.*dpos(0)+4.*dpos(0)*dpos(0)) *  .125*(1.+4.*dpos(1)+4.*dpos(1)*dpos(1)) * fiter.offset(-1,+1) +	
+			.125*(1.-4.*dpos(0)+4.*dpos(0)*dpos(0)) *  .125*(1.-4.*dpos(1)+4.*dpos(1)*dpos(1)) * fiter.offset(-1,-1) +
+		.125*(1.-4.*dpos(0)+4.*dpos(0)*dpos(0)) * .25*(3.-4.dpos(1)*dpos(1)) * fiter.offset(-1,0) +
+			.125*(1.-4.*dpos(0)+4.*dpos(0)*dpos(0)) *  .125*(1.+4.*dpos(1)+4.*dpos(1)*dpos(1)) * fiter.offset(-1,+1) +
 			.25*(3.-4.dpos(0)*dpos(0)) * .125*(1.-4.*dpos(1)+4.*dpos(1)*dpos(1)) * fiter.offset(0,-1) +
 			.25*(3.-4.dpos(0)*dpos(0)) * .125*(1.+4.*dpos(1)+4.*dpos(1)*dpos(1)) * 	fiter.offset(0,+1) +
 			.125*(1.+4.*dpos(0)+4.*dpos(0)*dpos(0)) *  .125*(1.-4.*dpos(1)+4.*dpos(1)*dpos(1)) *fiter.offset(+1,-1) +
 			.125*(1.+4.*dpos(0)+4.*dpos(0)*dpos(0)) * .25*(3.-4.dpos(1)*dpos(1)) * fiter.offset(+1,0) +
 			.125*(1.+4.*dpos(0)+4.*dpos(0)*dpos(0)) * .125*(1.+4.*dpos(1)+4.*dpos(1)*dpos(1)) * fiter.offset(+1,+1) ;
- 	*/
+	*/
 
 	pdata = 0;
 	auto W = [dpos](unsigned p, unsigned i) {
@@ -744,9 +744,9 @@ public:
     // accumulate into particle attrib
 	/*
     pdata = 	.25*(3.-4.dpos(0)*dpos(0)) * .25*(3.-4.dpos(1)*dpos(1)) * (*fiter) +
- 			.125*(1.-4.*dpos(0)+4.*dpos(0)*dpos(0)) *  .125*(1.-4.*dpos(1)+4.*dpos(1)*dpos(1)) * fiter.offset(-1,-1) + 
-     		.125*(1.-4.*dpos(0)+4.*dpos(0)*dpos(0)) * .25*(3.-4.dpos(1)*dpos(1)) * fiter.offset(-1,0) +
-			.125*(1.-4.*dpos(0)+4.*dpos(0)*dpos(0)) *  .125*(1.+4.*dpos(1)+4.*dpos(1)*dpos(1)) * fiter.offset(-1,+1) +	
+			.125*(1.-4.*dpos(0)+4.*dpos(0)*dpos(0)) *  .125*(1.-4.*dpos(1)+4.*dpos(1)*dpos(1)) * fiter.offset(-1,-1) +
+		.125*(1.-4.*dpos(0)+4.*dpos(0)*dpos(0)) * .25*(3.-4.dpos(1)*dpos(1)) * fiter.offset(-1,0) +
+			.125*(1.-4.*dpos(0)+4.*dpos(0)*dpos(0)) *  .125*(1.+4.*dpos(1)+4.*dpos(1)*dpos(1)) * fiter.offset(-1,+1) +
 			.25*(3.-4.dpos(0)*dpos(0)) * .125*(1.-4.*dpos(1)+4.*dpos(1)*dpos(1)) * fiter.offset(0,-1) +
 			.25*(3.-4.dpos(0)*dpos(0)) * .125*(1.+4.*dpos(1)+4.*dpos(1)*dpos(1)) * 	fiter.offset(0,+1) +
 			.125*(1.+4.*dpos(0)+4.*dpos(0)*dpos(0)) *  .125*(1.-4.*dpos(1)+4.*dpos(1)*dpos(1)) *fiter.offset(+1,-1) +
@@ -820,7 +820,7 @@ public:
 			}
 		}
 	}
-	//std::cout << "the total interpolation is = " << interpol_tot << std::endl;  
+	//std::cout << "the total interpolation is = " << interpol_tot << std::endl;
     return;
   }
 
@@ -863,7 +863,7 @@ public:
 		}
 	}
 
-//	std::cout << "the total interpolation is = " << interpol_tot << std::endl;  
+//	std::cout << "the total interpolation is = " << interpol_tot << std::endl;
     return;
   }
 
@@ -1085,6 +1085,5 @@ public:
 /***************************************************************************
  * $RCSfile: IntTSC.h,v $   $Author: adelmann $
  * $Revision: 1.1.1.1 $   $Date: 2003/01/23 07:40:28 $
- * IPPL_VERSION_ID: $Id: IntTSC.h,v 1.1.1.1 2003/01/23 07:40:28 adelmann Exp $ 
+ * IPPL_VERSION_ID: $Id: IntTSC.h,v 1.1.1.1 2003/01/23 07:40:28 adelmann Exp $
  ***************************************************************************/
-
diff --git a/ippl/src/Particle/IpplParticleBase.h b/ippl/src/Particle/IpplParticleBase.h
index 01ee38a2ade1a2f612cb4a8c4a7b3610be3a14b4..8184c9e49667a1f5f43d28d1066bb57a9852d812 100644
--- a/ippl/src/Particle/IpplParticleBase.h
+++ b/ippl/src/Particle/IpplParticleBase.h
@@ -200,7 +200,7 @@ public:
     void setLocalNum(size_t n) { LocalNum = n; }
 
     unsigned int getMinimumNumberOfParticlesPerCore() const { return MIN_NUM_PART_PER_CORE; };
-    void setMimumNumberOfParticlesPerCore(unsigned int n) { MIN_NUM_PART_PER_CORE=n; };
+    void setMinimumNumberOfParticlesPerCore(unsigned int n) { MIN_NUM_PART_PER_CORE=n; };
 
 
     // get the layout manager
@@ -396,4 +396,4 @@ private:
  * $RCSfile: IpplParticleBase.h,v $   $Author: adelmann $
  * $Revision: 1.1.1.1 $   $Date: 2003/01/23 07:40:28 $
  * IPPL_VERSION_ID: $Id: IpplParticleBase.h,v 1.1.1.1 2003/01/23 07:40:28 adelmann Exp $
- ***************************************************************************/
+ ***************************************************************************/
\ No newline at end of file
diff --git a/ippl/src/Particle/PairBuilder/CMakeLists.txt b/ippl/src/Particle/PairBuilder/CMakeLists.txt
index ff8456c57313ead92d1d5ab507495706937969dc..aef260fc332525b261a049b16656960f0ea41644 100644
--- a/ippl/src/Particle/PairBuilder/CMakeLists.txt
+++ b/ippl/src/Particle/PairBuilder/CMakeLists.txt
@@ -13,7 +13,7 @@ INCLUDE_DIRECTORIES (
   ${CMAKE_CURRENT_SOURCE_DIR}
 )
 
-ADD_SOURCES (${_SRCS})
-ADD_HEADERS (${_HDRS})
+ADD_IPPL_SOURCES (${_SRCS})
+ADD_IPPL_HEADERS (${_HDRS})
 
 INSTALL (FILES ${_HDRS} DESTINATION include/Particle/PairBuilder)
diff --git a/ippl/src/Particle/PairBuilder/HashPairBuilder.h b/ippl/src/Particle/PairBuilder/HashPairBuilder.h
index 7e62be486a47566b8de67bdc3328746903d880fa..09e8d2725cf40561d2a4e210c901fe33195e5685 100644
--- a/ippl/src/Particle/PairBuilder/HashPairBuilder.h
+++ b/ippl/src/Particle/PairBuilder/HashPairBuilder.h
@@ -12,19 +12,19 @@ class HashPairBuilder
 public:
     enum { Dim = PBase::Dim };
     typedef typename PBase::Position_t      Position_t;
-    
+
     HashPairBuilder(PBase &p) : particles(p) { }
-    
+
     template<class Pred, class OP>
     void for_each(const Pred& pred, const OP &op)
     {
         const std::size_t END = std::numeric_limits<std::size_t>::max();
         //	int f[3];
-        
+
         std::size_t size = particles.getLocalNum()+particles.getGhostNum();
         /*
          int edge = std::pow(size/8, 1./Dim);
-         
+
          std::size_t Nbucket = 1;
          for(int d = 0;d<Dim;++d)
          {
@@ -34,39 +34,39 @@ public:
          return;
          }
          */
-        
+
         bounds(particles.R, rmin_m, rmax_m);
         Inform dmsg("debug_msg:");
         dmsg << "R_min = " << rmin_m << " R_max = " << rmax_m << endl;
-        
+
         buckets_per_dim[0]=ceil((rmax_m[0]-rmin_m[0])/pred.getRange(0));
         buckets_per_dim[1]=ceil((rmax_m[1]-rmin_m[1])/pred.getRange(1));
         buckets_per_dim[2]=ceil((rmax_m[2]-rmin_m[2])/pred.getRange(2));
-        
+
         //dmsg << "buckets per dim = " << buckets_per_dim << endl;
         std::size_t Nbucket = buckets_per_dim[0]*buckets_per_dim[1]*buckets_per_dim[2];
-        
+
         std::size_t *buckets = new size_t[Nbucket];
         std::size_t *next = new size_t[size];
         std::fill(buckets, buckets+Nbucket, END);
         std::fill(next, next+size, END);
-        
+
         /*
          int neigh = 1;
          for(int d = 0;d<Dim;++d)
          neigh *= 3;
          neigh /= 2;
          */
-        
+
         //in 3D we interact with 14 neighboring cells (including self cell interaction)
         int neigh = 14;
-        
+
         int offset[14][3] = {{ 1, 1, 1}, { 0, 1, 1}, {-1, 1, 1},
             { 1, 0, 1}, { 0, 0, 1}, {-1, 0, 1},
             { 1,-1, 1}, { 0,-1, 1}, {-1,-1, 1},
             { 1, 1, 0}, { 0, 1, 0}, {-1, 1, 0},
             { 1, 0, 0}, { 0, 0, 0}};
-        
+
         //assign all particles to a bucket
         for(std::size_t i = 0;i<size;++i)
         {
@@ -75,7 +75,7 @@ public:
             next[i] = buckets[bucket_id];
             buckets[bucket_id] = i;
         }
-        
+
         for (int i=0; i< Nbucket; ++i) {
             //dmsg << "Bucket " << i << " stores particles " << endl;
             int j = buckets[i];
@@ -84,7 +84,7 @@ public:
                 j = next[j];
             }
         }
-        
+
         //loop over all buckets
         for (unsigned bx=0; bx<buckets_per_dim[0]; ++bx) {
             for (unsigned by=0; by<buckets_per_dim[1]; ++by) {
@@ -101,17 +101,17 @@ public:
                         if (bx_neigh >= 0 && bx_neigh<buckets_per_dim[0] &&
                             by_neigh >= 0 && by_neigh<buckets_per_dim[1] &&
                             bz_neigh >= 0 && bz_neigh<buckets_per_dim[2]) {
-                            
+
                             //compute bucket id of neighboring cell
                             unsigned bucket_id_neigh =
                             bz_neigh*buckets_per_dim[1]*buckets_per_dim[0]+by_neigh*buckets_per_dim[0]+bx_neigh;
                             //dmsg << "looking at buckets " << bucket_id_self << " and " << bucket_id_neigh << endl;
-                            
+
                             std::size_t i = buckets[bucket_id_self];
                             //dmsg << "head of chain is " << i << endl;
                             std::size_t j;
                             //loop over all particles in self cell
-                            
+
                             //self offset avoids double counting in self cell
                             int self_offset = 0;
                             while (i != END) {
@@ -142,13 +142,13 @@ public:
                         }
                         //dmsg << "proceed with next neighbor cell " << endl;
                     }
-                    
+
                 }
             }
         }
-        /*		
+        /*
          for(std::size_t i = 0;i<size;++i)
-         {	
+         {
          std::size_t j = next[i];
          while(j != END)
          {
@@ -156,11 +156,11 @@ public:
          op(i, j, particles);
          j = next[j];
          }
-         
+
          for(int k = 0;k<neigh;++k)
          {
          std::size_t tmppos = sum(i, pred, f, offset[k]);
-         
+
          j = buckets[tmppos];
          while(j != END)
          {
@@ -169,16 +169,16 @@ public:
          j = next[j];
          }
          }
-         
+
          }
          */
         delete[] buckets;
         delete[] next;
-        
+
         //dmsg << "particle particle interactions DONE" << endl;
     }
 private:
-    
+
     template<class Pred>
     int sum(int i, const Pred& pred, int f[], int offset[])
     {
@@ -193,22 +193,22 @@ private:
             sum += pos;
         }
         std::cout << "END SUM" << std::endl;
-        
+
         return sum;
     }
-    
+
     //returns the bucket id of particle i
     template<class Pred>
     int get_bucket_id(int i, const Pred& pred)
     {
         Vektor<int,3> loc;
-        for (unsigned d=0; d<3; ++d) 
+        for (unsigned d=0; d<3; ++d)
             loc[d] = (particles.R[i][d]-rmin_m[d])/pred.getRange(d);
         int bucket_id = loc[2]*buckets_per_dim[1]*buckets_per_dim[0]+loc[1]*buckets_per_dim[0]+loc[0];
         //std::cout << "bucket id of particle " << i << " = [" << loc[0] << "," << loc[1] << "," << loc[2] << "] => bucket id = "  << bucket_id << std::endl;
         return bucket_id;
     }
-    
+
     int mod(int x, int m)
     {
         if(x>=0)
@@ -216,10 +216,10 @@ private:
         else
             return (m - ((-x)%m))%m;
     }
-    
+
     PBase &particles;
     Vektor<int,3> buckets_per_dim;
-    
+
     Vektor<double,3> rmin_m;
     Vektor<double,3> rmax_m;
 };
diff --git a/ippl/src/Particle/PairBuilder/HashPairBuilderPeriodic.h b/ippl/src/Particle/PairBuilder/HashPairBuilderPeriodic.h
index 25a6b467e3a514653dc1234a32c84f8b2ceb9348..0d5cc4d612bc5f2cf91b8c037e702529fe3db9fa 100644
--- a/ippl/src/Particle/PairBuilder/HashPairBuilderPeriodic.h
+++ b/ippl/src/Particle/PairBuilder/HashPairBuilderPeriodic.h
@@ -12,58 +12,58 @@ class HashPairBuilderPeriodic
 public:
     enum { Dim = PBase::Dim };
     typedef typename PBase::Position_t      Position_t;
-    
+
     HashPairBuilderPeriodic(PBase &p) : particles(p) { }
-    
+
     template<class Pred, class OP>
     void for_each(const Pred& pred, const OP &op,Vektor<double,3> extend_l, Vektor<double,3> extend_r )
     {
         const std::size_t END = std::numeric_limits<std::size_t>::max();
         std::size_t size = particles.getLocalNum()+particles.getGhostNum();
-        
+
         rmin_m = extend_l;
         rmax_m = extend_r;
-        
+
         Vektor<double,3> period = extend_r-extend_l;
-        
+
         Inform dmsg("debug_msg:");
         dmsg << "R_min = " << rmin_m << " R_max = " << rmax_m << endl;
-        
+
         //make sure that the chaining mesh covers the whole domain and has a gridwidth>r_cut
         buckets_per_dim[0]=floor(period[0]/pred.getRange(0));
         buckets_per_dim[1]=floor(period[1]/pred.getRange(1));
         buckets_per_dim[2]=floor(period[2]/pred.getRange(2));
-        
+
         for (unsigned dim = 0; dim<3; ++dim)
             h_chaining[dim] = period[dim]/buckets_per_dim[dim];
-        
+
         dmsg << " period = " << period << endl;
         dmsg << "buckets per dim = " << buckets_per_dim << endl;
         dmsg << "h_chaining = " << h_chaining << endl;
-        
+
         std::size_t Nbucket = buckets_per_dim[0]*buckets_per_dim[1]*buckets_per_dim[2];
-        
+
         std::size_t *buckets = new size_t[Nbucket]; //index of first particle in this bucket
         std::size_t *next = new size_t[size]; //index of next particle in this bucket. END indicates last particle of bucket
         std::fill(buckets, buckets+Nbucket, END);
         std::fill(next, next+size, END);
-        
+
         //in 3D we interact with 14 neighboring cells (including self cell interaction)
         unsigned neigh = 14;
-        
+
         int offset[14][3] = {{ 1, 1, 1}, { 0, 1, 1}, {-1, 1, 1},
             { 1, 0, 1}, { 0, 0, 1}, {-1, 0, 1},
             { 1,-1, 1}, { 0,-1, 1}, {-1,-1, 1},
             { 1, 1, 0}, { 0, 1, 0}, {-1, 1, 0},
             { 1, 0, 0}, { 0, 0, 0}};
-        
+
         //assign all particles to a bucket
         for(std::size_t i = 0;i<size;++i) {
             unsigned bucket_id = get_bucket_id(i,pred);
             next[i] = buckets[bucket_id];
             buckets[bucket_id] = i;
         }
-        
+
         //loop over all buckets
         for (int bx=0; bx<buckets_per_dim[0]; ++bx) {
             for (int by=0; by<buckets_per_dim[1]; ++by) {
@@ -73,7 +73,7 @@ public:
                     for (unsigned n=0; n<neigh;++n){
                         int bx_neigh, by_neigh, bz_neigh;
                         Vektor<double,3> shift(0,0,0);
-                        
+
                         bx_neigh = bx+offset[n][0];
                         if (bx_neigh < 0) {
                             //bucket in -x direction exceed domain boundary
@@ -104,15 +104,15 @@ public:
                             bz_neigh -=buckets_per_dim[2];
                             shift[2] = period[2];
                         }
-                        
+
                         if (bx_neigh >= 0 && bx_neigh<buckets_per_dim[0] &&
                             by_neigh >= 0 && by_neigh<buckets_per_dim[1] &&
                             bz_neigh >= 0 && bz_neigh<buckets_per_dim[2]) {
-                            
+
                             //compute bucket id of neighboring cell
                             unsigned bucket_id_neigh =
                             bz_neigh*buckets_per_dim[1]*buckets_per_dim[0]+by_neigh*buckets_per_dim[0]+bx_neigh;
-                            
+
                             std::size_t i = buckets[bucket_id_self];
                             std::size_t j;
                             //loop over all particles in self cell
@@ -135,7 +135,7 @@ public:
                                     j = next[j];
                                 }
                                 i = next[i];
-                                //adjust self_offset 
+                                //adjust self_offset
                                 if (bucket_id_self==bucket_id_neigh)
                                     self_offset++;
                                 else
@@ -143,7 +143,7 @@ public:
                             }
                         }
                     }
-                    
+
                 }
             }
         }
@@ -151,25 +151,25 @@ public:
         delete[] next;
     }
 private:
-    
+
     //returns the bucket id of particle i
     template<class Pred>
     int get_bucket_id(int i, const Pred& pred)
     {
         Vektor<int,3> loc;
-        for (unsigned d=0; d<3; ++d) 
+        for (unsigned d=0; d<3; ++d)
             loc[d] = (particles.R[i][d]-rmin_m[d])/h_chaining[d];
         //loc[d] = (particles.R[i][d]-rmin_m[d])/pred.getRange(d);
         int bucket_id = loc[2]*buckets_per_dim[1]*buckets_per_dim[0]+loc[1]*buckets_per_dim[0]+loc[0];
         //std::cout << "bucket id of particle " << i << "with coords " << particles.R[i] << " = [" << loc[0] << "," << loc[1] << "," << loc[2] << "] => bucket id = "  << bucket_id << std::endl;
         //std::cout << particles.R[i][0] << "," << particles.R[i][1] << "," << particles.R[i][2] << "," << bucket_id << std::endl;
-        
+
         return bucket_id;
     }
-    
+
     PBase &particles;
     Vektor<int,3> buckets_per_dim;
-    
+
     Vektor<double,3> h_chaining;
     Vektor<double,3> rmin_m;
     Vektor<double,3> rmax_m;
diff --git a/ippl/src/Particle/PairBuilder/HashPairBuilderPeriodicParallel.h b/ippl/src/Particle/PairBuilder/HashPairBuilderPeriodicParallel.h
index b9fd8c8f15f44fb87d543ec3869c67f67cfdedca..870a74e686dde045a77c6413673b43019636e61f 100644
--- a/ippl/src/Particle/PairBuilder/HashPairBuilderPeriodicParallel.h
+++ b/ippl/src/Particle/PairBuilder/HashPairBuilderPeriodicParallel.h
@@ -27,31 +27,31 @@ class HashPairBuilderPeriodicParallel
 public:
     enum { Dim = PBase::Dim };
     typedef typename PBase::Position_t      Position_t;
-    
+
     HashPairBuilderPeriodicParallel(PBase &p) : particles(p) { hr_m = p.get_hr();}
-    
+
     template<class Pred, class OP>
     void for_each(const Pred& pred, const OP &op,Vektor<double,3> extend_l, Vektor<double,3> extend_r )
     {
         const std::size_t END = std::numeric_limits<std::size_t>::max();
         std::size_t size = particles.getLocalNum()+particles.getGhostNum();
-        
+
         // Inform dmsg("debug_msg:");
         // dmsg << "We use parallel hash pair builder small chaining mesh ****************************" << endl;
-        
+
         //compute which dimensions are really serial process neighbors itself in this direction
         Vektor<bool,3> parallel_dims(0,0,0);
-        
+
         NDIndex<3> globDomain = particles.getFieldLayout().getDomain();
         NDIndex<3> locDomain = particles.getFieldLayout().getLocalNDIndex();
-        
+
         parallel_dims[0] = !(globDomain[0]==locDomain[0]);
         parallel_dims[1] = !(globDomain[1]==locDomain[1]);
         parallel_dims[2] = !(globDomain[2]==locDomain[2]);
-        
+
         Vektor<double,3> period;
         period=extend_r-extend_l;
-        
+
         ///////// compute local chaining mesh
         Vektor<double,3> extend_l_local, extend_r_local, domain_width_local;
         for (unsigned i=0; i<3; ++i) {
@@ -59,42 +59,42 @@ public:
             extend_r_local[i] = extend_l[i]+(locDomain[i].last()+1)*hr_m[i];
             domain_width_local[i] = extend_r_local[i]-extend_l_local[i];
         }
-        
+
         //make sure that the chaining mesh covers the whole domain and has a gridwidth > r_cut
         buckets_per_dim[0]=floor(domain_width_local[0]/pred.getRange(0));
         buckets_per_dim[1]=floor(domain_width_local[1]/pred.getRange(1));
         buckets_per_dim[2]=floor(domain_width_local[2]/pred.getRange(2));
-        
+
         for (unsigned dim = 0; dim<3; ++dim)
             h_chaining[dim] = domain_width_local[dim]/buckets_per_dim[dim];
-        
+
         //extend the chaining mesh by one layer of chaining cells in each dimension
         rmin_m = extend_l_local-h_chaining;
         rmax_m = extend_r_local+h_chaining;
         buckets_per_dim+=2;
-        
+
         //dmsg << "local domain iwdth = " << domain_width_local << endl;
         //dmsg << "local extends : " << extend_l_local << "\t" << extend_r_local << endl;
         //dmsg << "local extends with chaining: " << rmin_m << "\t" << rmax_m << endl;
         //dmsg << "buckets per dim = " << buckets_per_dim << endl;
         //dmsg << "h_chaining = " << h_chaining << endl;
-        
+
         std::size_t Nbucket = buckets_per_dim[0]*buckets_per_dim[1]*buckets_per_dim[2];
-        
+
         std::size_t *buckets = new size_t[Nbucket]; //index of first particle in this bucket
         std::size_t *next = new size_t[size]; //index of next particle in this bucket. END indicates last particle of bucket
         std::fill(buckets, buckets+Nbucket, END);
         std::fill(next, next+size, END);
-        
+
         //in 3D we interact with 14 neighboring cells (including self cell interaction)
         unsigned neigh = 14;
-        
+
         int offset[14][3] = {{ 1, 1, 1}, { 0, 1, 1}, {-1, 1, 1},
             { 1, 0, 1}, { 0, 0, 1}, {-1, 0, 1},
             { 1,-1, 1}, { 0,-1, 1}, {-1,-1, 1},
             { 1, 1, 0}, { 0, 1, 0}, {-1, 1, 0},
             { 1, 0, 0}, { 0, 0, 0}};
-        
+
         //assign all particles to a bucket
         for(std::size_t i = 0;i<size;++i)
         {
@@ -103,7 +103,7 @@ public:
             next[i] = buckets[bucket_id];
             buckets[bucket_id] = i;
         }
-        
+
         double part_count = 0;
         //loop over all buckets
         for (int bx=0+int(!parallel_dims[0]); bx<buckets_per_dim[0]-int(!parallel_dims[0]); ++bx) {
@@ -114,7 +114,7 @@ public:
                     for (unsigned n=0; n<neigh;++n){
                         int bx_neigh, by_neigh, bz_neigh;
                         Vektor<double,3> shift(0,0,0);
-                        
+
                         bx_neigh = bx+offset[n][0];
                         //if we are serial in x-dimension we have no cached ghost particles. The local positions get periodically shifted
                         if (!parallel_dims[0]) {
@@ -141,7 +141,7 @@ public:
                                 shift[1] = period[1];
                             }
                         }
-                        
+
                         bz_neigh = bz+offset[n][2];
                         if (!parallel_dims[2]) {
                             if (bz_neigh == 0) {
@@ -153,18 +153,18 @@ public:
                                 shift[2] = period[2];
                             }
                         }
-                       
+
                         if (bx_neigh >= 0 && bx_neigh<buckets_per_dim[0] &&
                             by_neigh >= 0 && by_neigh<buckets_per_dim[1] &&
                             bz_neigh >= 0 && bz_neigh<buckets_per_dim[2]) {
-                            
+
                             unsigned bucket_id_neigh =
                             bz_neigh*buckets_per_dim[1]*buckets_per_dim[0]+by_neigh*buckets_per_dim[0]+bx_neigh;
-                            
+
                             //i is index of particle considered in active cahining cell, j is index of neighbor particle considered
                             std::size_t i = buckets[bucket_id_self];
                             std::size_t j;
-                            
+
                             //loop over all particles in self cell
                             //self offset avoids double counting in self cell
                             int self_offset = 0;
@@ -179,13 +179,13 @@ public:
                                 //loop over all particles in neighbor cell
                                 while(j != END) {
                                     if(pred(particles.R[i], particles.R[j]+shift)) {
-                                        if (i!=j) 
+                                        if (i!=j)
                                             op(i, j, particles, shift);
                                     }
                                     j = next[j];
                                 }
                                 i = next[i];
-                                //adjust self_offset 
+                                //adjust self_offset
                                 if (bucket_id_self==bucket_id_neigh)
                                     self_offset++;
                                 else
@@ -193,31 +193,31 @@ public:
                             }
                         }
                     }
-                    
+
                 }
             }
         }
-        
+
         delete[] buckets;
         delete[] next;
     }
 private:
-    
+
     //returns the bucket id of particle i
     template<class Pred>
     int get_bucket_id(int i, const Pred& pred)
     {
         // Inform dmsg("debug_msg:");
-        
+
         Vektor<int,3> loc;
-        for (unsigned d=0; d<3; ++d) 
+        for (unsigned d=0; d<3; ++d)
             loc[d] = (particles.R[i][d]-rmin_m[d])/h_chaining[d];
         int bucket_id = loc[2]*buckets_per_dim[1]*buckets_per_dim[0]+loc[1]*buckets_per_dim[0]+loc[0];
             // dmsg << "bucket id of particle " << i << "with coords " << particles.R[i] << " = [" << loc[0] << "," << loc[1] << "," << loc[2] << "] => bucket id = "  << bucket_id << endl;
             // dmsg << particles.R[i][0] << "," << particles.R[i][1] << "," << particles.R[i][2] << "," << bucket_id << endl;
         return bucket_id;
     }
-    
+
     PBase &particles;
     Vektor<int,3> buckets_per_dim;
     Vektor<double,3> h_chaining;
diff --git a/ippl/src/Particle/PairBuilder/HashPairBuilderPeriodicParallel_globCHaining.h b/ippl/src/Particle/PairBuilder/HashPairBuilderPeriodicParallel_globCHaining.h
index 39ba85c7f08b1a13fc2b0547863564d63755beba..a7eb08d719b19fc6efcefa6c9cc731e5323e4f9a 100644
--- a/ippl/src/Particle/PairBuilder/HashPairBuilderPeriodicParallel_globCHaining.h
+++ b/ippl/src/Particle/PairBuilder/HashPairBuilderPeriodicParallel_globCHaining.h
@@ -12,64 +12,64 @@ class HashPairBuilderPeriodicParallel
 public:
     enum { Dim = PBase::Dim };
     typedef typename PBase::Position_t      Position_t;
-    
+
     HashPairBuilderPeriodicParallel(PBase &p) : particles(p) { }
-    
+
     template<class Pred, class OP>
     void for_each(const Pred& pred, const OP &op,Vektor<double,3> extend_l, Vektor<double,3> extend_r )
     {
         const std::size_t END = std::numeric_limits<std::size_t>::max();
         std::size_t size = particles.getLocalNum()+particles.getGhostNum();
-        
+
         Inform dmsg("debug_msg:");
         std::cout << "We use parallel hash pair builder ****************************" << std::endl;
-        
+
         //compute which dimensions are really serial process neighbors itself in this direction
         Vektor<bool,3> parallel_dims(0,0,0);
-        
+
         NDIndex<3> globDomain = particles.getFieldLayout().getDomain();
         NDIndex<3> locDomain = particles.getFieldLayout().getLocalNDIndex();
-        
+
         parallel_dims[0] = !(globDomain[0]==locDomain[0]);
         parallel_dims[1] = !(globDomain[1]==locDomain[1]);
         parallel_dims[2] = !(globDomain[2]==locDomain[2]);
-        
+
         Vektor<double,3> period;
         period=extend_r-extend_l;
-        
+
         //make sure that the chaining mesh covers the whole domain and has a gridwidth > r_cut
         buckets_per_dim[0]=floor(period[0]/pred.getRange(0));
         buckets_per_dim[1]=floor(period[1]/pred.getRange(1));
         buckets_per_dim[2]=floor(period[2]/pred.getRange(2));
-        
+
         for (unsigned dim = 0; dim<3; ++dim)
             h_chaining[dim] = period[dim]/buckets_per_dim[dim];
-        
+
         //extend the chaining mesh by one layer of chaining cells in each dimension
         rmin_m = extend_l-h_chaining;
         rmax_m = extend_r+h_chaining;
         buckets_per_dim+=2;
-        
+
         dmsg << " period = " << period << endl;
         dmsg << "buckets per dim = " << buckets_per_dim << endl;
         dmsg << "h_chaining = " << h_chaining << endl;
-        
+
         std::size_t Nbucket = buckets_per_dim[0]*buckets_per_dim[1]*buckets_per_dim[2];
-        
+
         std::size_t *buckets = new size_t[Nbucket]; //index of first particle in this bucket
         std::size_t *next = new size_t[size]; //index of next particle in this bucket. END indicates last particle of bucket
         std::fill(buckets, buckets+Nbucket, END);
         std::fill(next, next+size, END);
-        
+
         //in 3D we interact with 14 neighboring cells (including self cell interaction)
         unsigned neigh = 14;
-        
+
         int offset[14][3] = {{ 1, 1, 1}, { 0, 1, 1}, {-1, 1, 1},
             { 1, 0, 1}, { 0, 0, 1}, {-1, 0, 1},
             { 1,-1, 1}, { 0,-1, 1}, {-1,-1, 1},
             { 1, 1, 0}, { 0, 1, 0}, {-1, 1, 0},
             { 1, 0, 0}, { 0, 0, 0}};
-        
+
         //assign all particles to a bucket
         for(std::size_t i = 0;i<size;++i)
         {
@@ -77,7 +77,7 @@ public:
             next[i] = buckets[bucket_id];
             buckets[bucket_id] = i;
         }
-        
+
         double part_count = 0;
         //loop over all buckets
         for (int bx=0+int(!parallel_dims[0]); bx<buckets_per_dim[0]-int(!parallel_dims[0]); ++bx) {
@@ -88,7 +88,7 @@ public:
                     for (unsigned n=0; n<neigh;++n){
                         int bx_neigh, by_neigh, bz_neigh;
                         Vektor<double,3> shift(0,0,0);
-                        
+
                         bx_neigh = bx+offset[n][0];
                         //if we are serial in x-dimension we have no cached ghost particles. The local positions get periodically shifted
                         if (!parallel_dims[0]) {
@@ -115,7 +115,7 @@ public:
                                 shift[1] = period[1];
                             }
                         }
-                        
+
                         bz_neigh = bz+offset[n][2];
                         if (!parallel_dims[2]) {
                             if (bz_neigh == 0) {
@@ -127,18 +127,18 @@ public:
                                 shift[2] = period[2];
                             }
                         }
-                        
+
                         if (bx_neigh >= 0 && bx_neigh<buckets_per_dim[0] &&
                             by_neigh >= 0 && by_neigh<buckets_per_dim[1] &&
                             bz_neigh >= 0 && bz_neigh<buckets_per_dim[2]) {
-                            
+
                             unsigned bucket_id_neigh =
                             bz_neigh*buckets_per_dim[1]*buckets_per_dim[0]+by_neigh*buckets_per_dim[0]+bx_neigh;
-                            
+
                             //i is index of particle considered in active cahining cell, j is index of neighbor particle considered
                             std::size_t i = buckets[bucket_id_self];
                             std::size_t j;
-                            
+
                             //loop over all particles in self cell
                             //self offset avoids double counting in self cell
                             int self_offset = 0;
@@ -153,13 +153,13 @@ public:
                                 //loop over all particles in neighbor cell
                                 while(j != END) {
                                     if(pred(particles.R[i], particles.R[j]+shift)) {
-                                        if (i!=j) 
+                                        if (i!=j)
                                             op(i, j, particles, shift);
                                     }
                                     j = next[j];
                                 }
                                 i = next[i];
-                                //adjust self_offset 
+                                //adjust self_offset
                                 if (bucket_id_self==bucket_id_neigh)
                                     self_offset++;
                                 else
@@ -167,30 +167,30 @@ public:
                             }
                         }
                     }
-                    
+
                 }
             }
         }
-        
+
         delete[] buckets;
         delete[] next;
     }
 private:
-    
+
     //returns the bucket id of particle i
     template<class Pred>
     int get_bucket_id(int i, const Pred& pred)
     {
         Vektor<int,3> loc;
-        for (unsigned d=0; d<3; ++d) 
+        for (unsigned d=0; d<3; ++d)
             loc[d] = (particles.R[i][d]-rmin_m[d])/h_chaining[d];
         int bucket_id = loc[2]*buckets_per_dim[1]*buckets_per_dim[0]+loc[1]*buckets_per_dim[0]+loc[0];
         //std::cout << "bucket id of particle " << i << "with coords " << particles.R[i] << " = [" << loc[0] << "," << loc[1] << "," << loc[2] << "] => bucket id = "  << bucket_id << std::endl;
         //std::cout << particles.R[i][0] << "," << particles.R[i][1] << "," << particles.R[i][2] << "," << bucket_id << std::endl;
-        
+
         return bucket_id;
     }
-    
+
     PBase &particles;
     Vektor<int,3> buckets_per_dim;
     Vektor<double,3> h_chaining;
diff --git a/ippl/src/Particle/PairBuilder/PairConditions.h b/ippl/src/Particle/PairBuilder/PairConditions.h
index 7aa1ae529da6ce557d198a63acebeada5e32af8e..3e52a23fe83f9c7fab536cb4a7653a8f57bfc0d5 100644
--- a/ippl/src/Particle/PairBuilder/PairConditions.h
+++ b/ippl/src/Particle/PairBuilder/PairConditions.h
@@ -15,7 +15,7 @@ public:
     {
         return true;
     }
-    
+
     T getRange(unsigned dim) const { return std::numeric_limits<T>::max(); }
 };
 
@@ -25,7 +25,7 @@ class RadiusCondition
 public:
     RadiusCondition(T r) : sqradius(r*r), radius(r)
     {  }
-    
+
     template<class V>
     bool operator()(const V &a, const V &b) const
     {
@@ -36,7 +36,7 @@ public:
         }
         return sqr <= sqradius;
     }
-    
+
     //periodic version of radius condition
     template<class V, class Vec>
     bool operator()(const V &a, const V &b, const Vec &period) const
@@ -56,8 +56,8 @@ public:
          */
         return sqr <= sqradius;
     }
-    
-    
+
+
     T getRange(unsigned d) const { return radius; }
 private:
     T sqradius, radius;
@@ -69,7 +69,7 @@ class BoxCondition
 public:
     BoxCondition(T b[Dim]) : box(b)
     {  }
-    
+
     template<class V>
     bool operator()(const V &a, const V &b) const
     {
@@ -81,7 +81,7 @@ public:
         }
         return true;
     }
-    
+
     T getRange(unsigned d) const { return box[d]; }
 private:
     T box[Dim];
diff --git a/ippl/src/Particle/PairBuilder/SortingPairBuilder.h b/ippl/src/Particle/PairBuilder/SortingPairBuilder.h
index f5f68ba23f2b8d35b6cede87f00aa96166d2aa68..3d0d7ac4361ba3a77034e1e2860ab1c56b959607 100644
--- a/ippl/src/Particle/PairBuilder/SortingPairBuilder.h
+++ b/ippl/src/Particle/PairBuilder/SortingPairBuilder.h
@@ -8,11 +8,11 @@ template<class A>
 struct ProxyPred_t
 {
     ProxyPred_t(const A &a, unsigned d) : array(a), dim(d) { }
-    
+
     template<class T>
     bool operator()(const T &a, const T &b)
     { return array[a][dim] < array[b][dim]; }
-    
+
     unsigned dim;
     const A &array;
 };
@@ -30,32 +30,32 @@ class SortingPairBuilder
 public:
     enum { Dim = PBase::Dim };
     typedef typename PBase::Position_t      Position_t;
-    
+
     SortingPairBuilder(PBase &p) : particles(p) { }
-    
+
     template<class Pred, class OP>
     void for_each(const Pred& pred, const OP &op)
     {
         std::size_t size = particles.getLocalNum()+particles.getGhostNum();
-        
+
         Position_t mean[Dim];
         Position_t variance[Dim];
-        
+
         //calculate mean position
         std::fill(mean, mean+Dim, 0);
         for(std::size_t i = 0;i<size;++i)
             for(int d = 0;d<Dim;++d)
                 mean[d] += particles.R[i][d];
-        
+
         for(int d = 0;d<Dim;++d)
             mean[d] /= size;
-        
+
         //calculate variance for each dimension
         std::fill(variance, variance+Dim, 0);
         for(std::size_t i = 0;i<size;++i)
             for(int d = 0;d<Dim;++d)
                 variance[d] += (mean[d]-particles.R[i][d])*(mean[d]-particles.R[i][d]);
-        
+
         int dimension = 0;
         int var = variance[0];
         for(int d = 1;d<Dim;++d)
@@ -64,14 +64,14 @@ public:
                 dimension = d;
                 var = variance[d];
             }
-        
+
         //sort index array
         std::size_t *indices = new std::size_t[size];
         for(std::size_t i = 0;i<size;++i)
             indices[i] = i;
-        
+
         std::sort(indices, indices+size, ProxyPred(particles.R, dimension));
-        
+
         for(std::size_t i = 0;i<size;++i)
             for(std::size_t j = i+1;j<size;++j)
                 if(pred(particles.R[indices[i]], particles.R[indices[j]]))
diff --git a/ippl/src/Particle/ParticleBalancer.hpp b/ippl/src/Particle/ParticleBalancer.hpp
index 5fe6b16b3a446f9d59c70c1b4e3804d29da8daf7..09e2c937d75b2c346a54c030b6e7357df14cf9f6 100644
--- a/ippl/src/Particle/ParticleBalancer.hpp
+++ b/ippl/src/Particle/ParticleBalancer.hpp
@@ -2,8 +2,8 @@
 /***************************************************************************
  *
  * The IPPL Framework
- * 
- * This program was prepared by PSI. 
+ *
+ * This program was prepared by PSI.
  * All rights in the program are reserved by PSI.
  * Neither PSI nor the author(s)
  * makes any warranty, express or implied, or assumes any liability or
@@ -17,7 +17,7 @@
 /***************************************************************************
  *
  * The IPPL Framework
- * 
+ *
  *
  * Visit http://people.web.psi.ch/adelmann/ for more details
  *
@@ -39,13 +39,13 @@
 
 
 /////////////////////////////////////////////////////////////////////////////
-// calculate a new RegionLayout for a given IpplParticleBase, and distribute the
+// calculate a new RegionLayout for a given ParticleBase, and distribute the
 // new RegionLayout to all the nodes.  This uses a Field BinaryBalancer.
 template < class T, unsigned Dim, class Mesh, class CachingPolicy>
 bool
 BinaryRepartition(IpplParticleBase<ParticleSpatialLayout<T,Dim,Mesh,CachingPolicy> >& PB, double offset) {
-  
-  
+
+
 
   static IntNGP interp; // to scatter particle density
 
@@ -82,7 +82,7 @@ BinaryRepartition(IpplParticleBase<ParticleSpatialLayout<T,Dim,Mesh,CachingPolic
     CenterOffset[d] = (TotalDomain[d].length() < mesh.gridSizes[d]);
     CenteringTotal += CenterOffset[d];
   }
-  
+
 
   if (CenteringTotal == Dim) { // allCell centering
     Field<double,Dim,Mesh,Cell> BF(mesh,FL,GuardCellSizes<Dim>(1));
@@ -151,7 +151,5 @@ BinaryRepartition(IpplParticleBase<ParticleUniformLayout<T,Dim> >&, double offse
 /***************************************************************************
  * $RCSfile: ParticleBalancer.cpp,v $   $Author: adelmann $
  * $Revision: 1.1.1.1 $   $Date: 2003/01/23 07:40:28 $
- * IPPL_VERSION_ID: $Id: ParticleBalancer.cpp,v 1.1.1.1 2003/01/23 07:40:28 adelmann Exp $ 
- ***************************************************************************/
-
-
+ * IPPL_VERSION_ID: $Id: ParticleBalancer.cpp,v 1.1.1.1 2003/01/23 07:40:28 adelmann Exp $
+ ***************************************************************************/
\ No newline at end of file
diff --git a/ippl/src/Particle/ParticleInteractLayout.hpp b/ippl/src/Particle/ParticleInteractLayout.hpp
index e04b74da0144fdbd56369b7ec40a08ebd2180bd6..ad618e5c9270a3fd5cdfe44cedfc45f598e3ad14 100644
--- a/ippl/src/Particle/ParticleInteractLayout.hpp
+++ b/ippl/src/Particle/ParticleInteractLayout.hpp
@@ -2,8 +2,8 @@
 /***************************************************************************
  *
  * The IPPL Framework
- * 
- * This program was prepared by PSI. 
+ *
+ * This program was prepared by PSI.
  * All rights in the program are reserved by PSI.
  * Neither PSI nor the author(s)
  * makes any warranty, express or implied, or assumes any liability or
@@ -17,7 +17,7 @@
 /***************************************************************************
  *
  * The IPPL Framework
- * 
+ *
  *
  * Visit http://people.web.psi.ch/adelmann/ for more details
  *
@@ -40,9 +40,9 @@
 // constructor, from a FieldLayout
 template < class T, unsigned Dim, class Mesh >
 ParticleInteractLayout<T,Dim,Mesh>::ParticleInteractLayout(FieldLayout<Dim>&
-							   fl) 
+							   fl)
   : ParticleSpatialLayout<T,Dim,Mesh>(fl) {
-  setup();			// perform necessary setup 
+  setup();			// perform necessary setup
 }
 
 
@@ -52,7 +52,7 @@ template < class T, unsigned Dim, class Mesh >
 ParticleInteractLayout<T,Dim,Mesh>::ParticleInteractLayout(FieldLayout<Dim>&
 							   fl, Mesh& mesh)
   : ParticleSpatialLayout<T,Dim,Mesh>(fl,mesh) {
-  setup();			// perform necessary setup 
+  setup();			// perform necessary setup
 }
 
 
@@ -61,7 +61,7 @@ ParticleInteractLayout<T,Dim,Mesh>::ParticleInteractLayout(FieldLayout<Dim>&
 template < class T, unsigned Dim, class Mesh >
 ParticleInteractLayout<T,Dim,Mesh>::ParticleInteractLayout(const
   RegionLayout<T,Dim,Mesh>& rl) : ParticleSpatialLayout<T,Dim,Mesh>(rl) {
-  setup();			// perform necessary setup 
+  setup();			// perform necessary setup
 }
 
 
@@ -71,7 +71,7 @@ ParticleInteractLayout<T,Dim,Mesh>::ParticleInteractLayout(const
 template < class T, unsigned Dim, class Mesh >
 ParticleInteractLayout<T,Dim,Mesh>::ParticleInteractLayout()
   : ParticleSpatialLayout<T,Dim,Mesh>() {
-  setup();			// perform necessary setup 
+  setup();			// perform necessary setup
 }
 
 
@@ -434,7 +434,7 @@ void ParticleInteractLayout<T,Dim,Mesh>::update(
   // local field space.  This is done in several passes, one for each
   // spatial dimension.  The NodeCount values are updated by this routine.
   if (N > 1 && getUpdateFlag(this->SWAP)) {
-    if (canSwap==0) 
+    if (canSwap==0)
       LocalNum = swap_particles(LocalNum, PData);
     else
       LocalNum = swap_particles(LocalNum, PData, *canSwap);
@@ -458,7 +458,7 @@ void ParticleInteractLayout<T,Dim,Mesh>::update(
 
       // put local particle count in the message
       msg->put(LocalNum);
-      
+
       // also put in our maximum interaction radius
       msg->put(maxrad);
 
@@ -540,12 +540,12 @@ void ParticleInteractLayout<T,Dim,Mesh>::update(
 
 /////////////////////////////////////////////////////////////////////
 // copy particles to other nodes for pairlist computation.  The arguments
-// are the current number of local particles, and the IpplParticleBase object.
+// are the current number of local particles, and the ParticleBase object.
 // Make sure not to send any particles to, or receive particles from,
 // nodes which have no particles on them.  This also takes care of
 // building the pairlists.
 template < class T, unsigned Dim, class Mesh >
-void ParticleInteractLayout<T,Dim,Mesh>::swap_ghost_particles(unsigned 
+void ParticleInteractLayout<T,Dim,Mesh>::swap_ghost_particles(unsigned
 							      LocalNum,
    IpplParticleBase< ParticleInteractLayout<T,Dim,Mesh> >& PData) {
 
@@ -591,20 +591,20 @@ void ParticleInteractLayout<T,Dim,Mesh>::swap_ghost_particles(unsigned
   for (i=0; i < N; i++)
     if (InterNodeList[i] && this->NodeCount[i] > 0)
       this->SwapMsgList[i] = new Message;
-  
+
   // Go through the particles, find those with interaction radius
   // which overlaps with a neighboring left node, and copy into a message.
   // The interaction radius used to check for whether to send the particle
   // is (max inter. radius of system)*2.
-  
-  
+
+
   //  for (i=0; i < LocalNum; ++i) {
-  
+
   // initialize the flags which indicate which node the particle will be
   // sent to
-  
+
   // ada    memset((void *)SentToNodeList, 0, N * sizeof(bool));
-  
+
   // get the position of the ith particle, and form an NDRegion which
   // is a cube with sides of length twice the interaction radius
   // ada    for (j=0; j < Dim; ++j)
@@ -617,7 +617,7 @@ void ParticleInteractLayout<T,Dim,Mesh>::swap_ghost_particles(unsigned
   // ada   for ( ; tVNit != touchingVN.second; ++tVNit) {
   // ada   Rnode<T,Dim> *tVN = (*tVNit).second;
   // ada  unsigned node = tVN->getNode();
-  
+
   // the node has been found - copy particle data into a message,
   // ada  if (this->NodeCount[node] > 0 && ! SentToNodeList[node]) {
   // ada	if (! InterNodeList[node]) {
@@ -631,10 +631,10 @@ void ParticleInteractLayout<T,Dim,Mesh>::swap_ghost_particles(unsigned
   //      }
   //    }
   //  }
-  
+
   // send out messages with ghost particles
 
-  /* 
+  /*
      ada: buggy     BUGGY node hangs in later receive_block
 
   int tag = Ippl::Comm->next_tag(P_SPATIAL_GHOST_TAG, P_LAYOUT_CYCLE);
@@ -651,7 +651,7 @@ void ParticleInteractLayout<T,Dim,Mesh>::swap_ghost_particles(unsigned
 
   // while we're waiting for messages to arrive, calculate our local pairs
   find_pairs(LocalNum, 0, LocalNum, true, PData);
-  
+
   // receive ghost particles from other nodes, and add them to our list
 
   /*
@@ -662,7 +662,7 @@ void ParticleInteractLayout<T,Dim,Mesh>::swap_ghost_particles(unsigned
 
     while (PData.ghostGetMessage(*recmsg, node) > 0);
     delete recmsg;
-    
+
     // find pairs with these ghost particles
     find_pairs(LocalNum, LocalNum + oldGN, LocalNum + PData.getGhostNum(),
     false, PData);
@@ -948,7 +948,7 @@ void ParticleInteractLayout<T,Dim,Mesh>::find_pairs(const unsigned LocalNum,
       // add interaction radius of this particle
       T intrad2 = intrad1 + getInteractionRadius(j);
       intrad2 *= intrad2;	// (intrad1 + intrad2)^2
- 
+
       // find distance^2 between these two particles
       Vektor<T,Dim> rsep = PData.R[j];
       rsep -= PData.R[i];
@@ -968,7 +968,7 @@ void ParticleInteractLayout<T,Dim,Mesh>::find_pairs(const unsigned LocalNum,
       // get interaction radius of this particle
       T intrad2 = intrad1 + getInteractionRadius(j);
       intrad2 *= intrad2;	// (intrad1 + intrad2)^2
- 
+
       // find distance^2 between these two particles
       Vektor<T,Dim> rsep = PData.R[j];
       rsep -= PData.R[i];
@@ -1024,5 +1024,5 @@ void ParticleInteractLayout<T,Dim,Mesh>::Repartition(UserList* userlist) {
 /***************************************************************************
  * $RCSfile: ParticleInteractLayout.cpp,v $   $Author: adelmann $
  * $Revision: 1.1.1.1 $   $Date: 2003/01/23 07:40:29 $
- * IPPL_VERSION_ID: $Id: ParticleInteractLayout.cpp,v 1.1.1.1 2003/01/23 07:40:29 adelmann Exp $ 
- ***************************************************************************/
+ * IPPL_VERSION_ID: $Id: ParticleInteractLayout.cpp,v 1.1.1.1 2003/01/23 07:40:29 adelmann Exp $
+ ***************************************************************************/
\ No newline at end of file
diff --git a/ippl/src/Particle/ParticleLayoutFromGrid.cpp b/ippl/src/Particle/ParticleLayoutFromGrid.cpp
index 125e71c056ef892f5b6ecea22750aff9fbec6f9d..bd1d06c83d115fe247fbeb59210df26157a7ad82 100644
--- a/ippl/src/Particle/ParticleLayoutFromGrid.cpp
+++ b/ippl/src/Particle/ParticleLayoutFromGrid.cpp
@@ -1,7 +1,7 @@
 //
 // C++ Implementation: ParticleLayoutFromGrid
 //
-// Description: 
+// Description:
 //
 //
 //
@@ -21,19 +21,19 @@ void ParticleLayoutFromGrid::update(IpplParticleBase< ParticleLayoutFromGrid >&
     size_t num_destroyed_particles = particles.getDestroyNum();
     particles.performDestroy();
     num_my_particles -= num_destroyed_particles;
-    
+
     // FIXME: This should be done in IpplParticleBase::performDestroy()
     particles.setLocalNum(num_my_particles);
 
     // Apply boundary conditions to the particle positions
     // apply_bconds(particles.R);
-    
-    // Redistribute particles, such that particles that have moved outside the 
+
+    // Redistribute particles, such that particles that have moved outside the
     // local domain are moved to the corresponding processor.
     unsigned num_active_procs = grid_->give_number_of_active_processes();
     if (num_active_procs > 1)
         num_my_particles = redistribute_particles(particles);
-        
+
     // Update total number of particles in particle container
     size_t num_total_particles;
     reduce(num_my_particles, num_total_particles, OpAddAssign());
@@ -44,21 +44,21 @@ void ParticleLayoutFromGrid::apply_bconds(ParticlePos_t& R)
 {
     Inform msg("update");
     size_t num_my_particles = R.size();
-    
+
     for (size_t ip = 0; ip < num_my_particles; ++ ip) {
         D3vector pos(R[ip](0), R[ip](1), R[ip](2));
         if (!geom_domain_->point_in_domain(pos)) {
             msg << "Particle " << ip << " moved outside domain." << endl;
         }
-    }    
+    }
 }
 
-size_t ParticleLayoutFromGrid::redistribute_particles(IpplParticleBase< ParticleLayoutFromGrid >& particles) 
+size_t ParticleLayoutFromGrid::redistribute_particles(IpplParticleBase< ParticleLayoutFromGrid >& particles)
 {
     unsigned num_procs = Ippl::getNodes();
     unsigned my_id = Ippl::myNode();
     size_t num_my_particles = particles.getLocalNum();
-    
+
     // FIXME: How do I test if I am an active processor?
     // FIXME: Assume that active processors are assigned the ids 0..num_active_procs-1.
     unsigned num_active_procs = grid_->give_number_of_active_processes();
@@ -66,7 +66,7 @@ size_t ParticleLayoutFromGrid::redistribute_particles(IpplParticleBase< Particle
     // Non-active processors return here!
     if (my_id >= num_active_procs)
         return num_my_particles;
-    
+
     std::vector<D3vector> bb_min;
     std::vector<D3vector> bb_max;
     for (int p = 0; p < num_active_procs; ++ p) {
@@ -77,19 +77,19 @@ size_t ParticleLayoutFromGrid::redistribute_particles(IpplParticleBase< Particle
     }
     // FIXME: Bounding boxes could be sorted, such that neighbors are close the beginning.
     // FIXME: Should the local bounding box be removed from this list?
-    
+
     // num_active_procs Message objects
     std::vector<Message> messages(num_active_procs);
     // List of particles for each message
     std::vector<size_t>* put_list = new std::vector<size_t>[num_active_procs];
-    
+
     for (size_t ip = 0; ip < num_my_particles; ++ ip) {
         D3vector pos(particles.R[ip][0], particles.R[ip][1], particles.R[ip][2]);
-        
-        if (!is_local_pos(pos)) 
+
+        if (!is_local_pos(pos))
         {
             // Particle has moved outside the local domain
-            
+
             // Identify processor which should receive the particle (linear search)
             unsigned target_id = num_active_procs;
             for (unsigned p = 0; p < num_active_procs; ++ p) {
@@ -100,12 +100,12 @@ size_t ParticleLayoutFromGrid::redistribute_particles(IpplParticleBase< Particle
             }
             assert(target_id != num_active_procs && target_id != my_id);
             put_list[target_id].push_back(ip);
-            
+
             // Mark particle for deletion
             particles.destroy(1, ip);
-        }      
+        }
     }
-    
+
     // Send particles to their destination nodes
     int tag = Ippl::Comm->next_tag(P_SPATIAL_TRANSFER_TAG, P_LAYOUT_CYCLE);
     for (int p = 0; p < num_active_procs; ++ p) {
@@ -123,10 +123,10 @@ size_t ParticleLayoutFromGrid::redistribute_particles(IpplParticleBase< Particle
     // Delete sent particles.
     num_my_particles -= particles.getDestroyNum();
     particles.performDestroy();
-    
+
     // FIXME: This should be done in IpplParticleBase::performDestroy()
     particles.setLocalNum(num_my_particles);
-    
+
     // Receive particles
     unsigned sendnum = num_active_procs - 1;
     while (sendnum-- > 0) {
@@ -139,10 +139,10 @@ size_t ParticleLayoutFromGrid::redistribute_particles(IpplParticleBase< Particle
         num_my_particles += total_recvd;
         delete recmsg;
     }
-    
+
     // FIXME: This should be done in IpplParticleBase::getMessage()
     particles.setLocalNum(num_my_particles);
-    
+
     delete[] put_list;
     return num_my_particles;
-}
+}
\ No newline at end of file
diff --git a/ippl/src/Particle/ParticleLayoutFromGrid.h b/ippl/src/Particle/ParticleLayoutFromGrid.h
index 74639a091fab752a47e745aaa3ed190398f3b718..986378877ead1dbff91628d940380c8ea6545736 100644
--- a/ippl/src/Particle/ParticleLayoutFromGrid.h
+++ b/ippl/src/Particle/ParticleLayoutFromGrid.h
@@ -1,7 +1,7 @@
 //
 // C++ Interface: ParticleLayoutFromGrid
 //
-// Description: 
+// Description:
 //
 //
 // Author: Roman Geus <geus@maxwell>, (C) 2005
@@ -34,28 +34,28 @@ public:
         geom_domain_(domain),
         my_corner_min_(local_min),
         my_corner_max_(local_max)
-    {}    
+    {}
     /**
      * Does "book--keeping" after particles have been integrated one time step.
      *
-     * "Book--keeping" includes 
-     *    - Detecting particles which have moved across a boundary and 
+     * "Book--keeping" includes
+     *    - Detecting particles which have moved across a boundary and
      *      taking appropriate measures. (not yet implemented)
      *    - Redistributing particles which have moved out of the domain
      *      assigned to the local processor.
      *    - Updating the total particle count.
      * @param particles Particle container.
      */
-    void update(IpplParticleBase< ParticleLayoutFromGrid >& particles);    
+    void update(IpplParticleBase< ParticleLayoutFromGrid >& particles);
     /**
      * Test if x is inside the domain assigned to my processor.
      * @param x Position to test.
      * @return  True if inside.
      */
     inline bool is_local_pos(const Vector_t& x) const {
-      const D3vector y(x[0],x[1],x[2]);      
+      const D3vector y(x[0],x[1],x[2]);
       return is_inside_box(my_corner_min_, my_corner_max_, y);
-    }    
+    }
     /**
      * Test if x is inside the domain assigned to my processor.
      * @param x Position to test.
@@ -63,7 +63,7 @@ public:
      */
     inline bool is_local_pos(const D3vector& x) const {
       return is_inside_box(my_corner_min_, my_corner_max_, x);
-    }    
+    }
 
     /**
      * Test if x is inside the geometric domain
@@ -95,7 +95,7 @@ public:
                corner_min[1] <= x[1] && x[1] < corner_max[1] &&
                corner_min[2] <= x[2] && x[2] < corner_max[2];
     }
-   
+
 private:
     /**
      * Dummy function for boundary treatment (currently not used)
@@ -103,7 +103,7 @@ private:
      */
     void apply_bconds(ParticlePos_t& R);
     /**
-     * Go through all local particles, and send particles which are no longer in 
+     * Go through all local particles, and send particles which are no longer in
      * the local bounding box to the corresponding processors.
      *
      * @param particles Particle container
@@ -128,4 +128,4 @@ private:
     D3vector my_corner_max_;
 };
 
-#endif
+#endif
\ No newline at end of file
diff --git a/ippl/src/Particle/ParticleSpatialLayout.h b/ippl/src/Particle/ParticleSpatialLayout.h
index 9563819b8d41ec1e6f6fb8d398a121f33f67bbbf..705247d22f5a6fbda18045aef558aa0bcb9152f2 100644
--- a/ippl/src/Particle/ParticleSpatialLayout.h
+++ b/ippl/src/Particle/ParticleSpatialLayout.h
@@ -533,7 +533,7 @@ protected:
                                 }
                                 else
                                 {
-				    
+
 				    // the node has been found - add index to put list
 				    unsigned node = (*(touchingVN.first)).second->getNode();
 				    PAssert(SwapNodeList[d][node]);
@@ -541,7 +541,7 @@ protected:
 
 				    // .. and then add to DestroyList
 				    PData.destroy(1, ip);
-				    
+
 				    // indicate we found it to quit this check
 				    foundit = true;
                                 }
diff --git a/ippl/src/Particle/inst/ParticleBaseInteract_Cart_1D.cpp b/ippl/src/Particle/inst/ParticleBaseInteract_Cart_1D.cpp
index da291d7388cfbb0cc5d3ac607f9230ea249988f3..41f635190a667a00d40dd60b4ee383b445415491 100644
--- a/ippl/src/Particle/inst/ParticleBaseInteract_Cart_1D.cpp
+++ b/ippl/src/Particle/inst/ParticleBaseInteract_Cart_1D.cpp
@@ -2,8 +2,8 @@
 /***************************************************************************
  *
  * The IPPL Framework
- * 
- * This program was prepared by PSI. 
+ *
+ * This program was prepared by PSI.
  * All rights in the program are reserved by PSI.
  * Neither PSI nor the author(s)
  * makes any warranty, express or implied, or assumes any liability or
@@ -17,7 +17,7 @@
 /***************************************************************************
  *
  * The IPPL Framework
- * 
+ *
  *
  * Visit http://people.web.psi.ch/adelmann/ for more details
  *
@@ -34,8 +34,7 @@ template class IpplParticleBase<ParticleInteractLayout<
 
 
 /***************************************************************************
- * $RCSfile: IpplParticleBaseInteract_Cart_1D.cpp,v $   $Author: adelmann $
+ * $RCSfile: ParticleBaseInteract_Cart_1D.cpp,v $   $Author: adelmann $
  * $Revision: 1.1.1.1 $   $Date: 2003/01/23 07:40:29 $
- * IPPL_VERSION_ID: $Id: IpplParticleBaseInteract_Cart_1D.cpp,v 1.1.1.1 2003/01/23 07:40:29 adelmann Exp $ 
- ***************************************************************************/
-
+ * IPPL_VERSION_ID: $Id: ParticleBaseInteract_Cart_1D.cpp,v 1.1.1.1 2003/01/23 07:40:29 adelmann Exp $
+ ***************************************************************************/
\ No newline at end of file
diff --git a/ippl/src/Particle/inst/ParticleBaseInteract_Cart_2D.cpp b/ippl/src/Particle/inst/ParticleBaseInteract_Cart_2D.cpp
index 148ea7eda4535946de77644277c0b56c6be9323d..92555b16df2761c5b1277e7bb71f252c74146703 100644
--- a/ippl/src/Particle/inst/ParticleBaseInteract_Cart_2D.cpp
+++ b/ippl/src/Particle/inst/ParticleBaseInteract_Cart_2D.cpp
@@ -2,8 +2,8 @@
 /***************************************************************************
  *
  * The IPPL Framework
- * 
- * This program was prepared by PSI. 
+ *
+ * This program was prepared by PSI.
  * All rights in the program are reserved by PSI.
  * Neither PSI nor the author(s)
  * makes any warranty, express or implied, or assumes any liability or
@@ -17,7 +17,7 @@
 /***************************************************************************
  *
  * The IPPL Framework
- * 
+ *
  *
  * Visit http://people.web.psi.ch/adelmann/ for more details
  *
@@ -34,8 +34,7 @@ template class IpplParticleBase<ParticleInteractLayout<
 
 
 /***************************************************************************
- * $RCSfile: IpplParticleBaseInteract_Cart_2D.cpp,v $   $Author: adelmann $
+ * $RCSfile: ParticleBaseInteract_Cart_2D.cpp,v $   $Author: adelmann $
  * $Revision: 1.1.1.1 $   $Date: 2003/01/23 07:40:29 $
- * IPPL_VERSION_ID: $Id: IpplParticleBaseInteract_Cart_2D.cpp,v 1.1.1.1 2003/01/23 07:40:29 adelmann Exp $ 
- ***************************************************************************/
-
+ * IPPL_VERSION_ID: $Id: ParticleBaseInteract_Cart_2D.cpp,v 1.1.1.1 2003/01/23 07:40:29 adelmann Exp $
+ ***************************************************************************/
\ No newline at end of file
diff --git a/ippl/src/Particle/inst/ParticleBaseInteract_Cart_3D.cpp b/ippl/src/Particle/inst/ParticleBaseInteract_Cart_3D.cpp
index cd78011132de5aa2701a0da1ee74a394a840eebb..eb0313fa16e0116fbe1c95bd1dd41255b82c57de 100644
--- a/ippl/src/Particle/inst/ParticleBaseInteract_Cart_3D.cpp
+++ b/ippl/src/Particle/inst/ParticleBaseInteract_Cart_3D.cpp
@@ -2,8 +2,8 @@
 /***************************************************************************
  *
  * The IPPL Framework
- * 
- * This program was prepared by PSI. 
+ *
+ * This program was prepared by PSI.
  * All rights in the program are reserved by PSI.
  * Neither PSI nor the author(s)
  * makes any warranty, express or implied, or assumes any liability or
@@ -17,7 +17,7 @@
 /***************************************************************************
  *
  * The IPPL Framework
- * 
+ *
  *
  * Visit http://people.web.psi.ch/adelmann/ for more details
  *
@@ -34,8 +34,7 @@ template class IpplParticleBase<ParticleInteractLayout<
 
 
 /***************************************************************************
- * $RCSfile: IpplParticleBaseInteract_Cart_3D.cpp,v $   $Author: adelmann $
+ * $RCSfile: ParticleBaseInteract_Cart_3D.cpp,v $   $Author: adelmann $
  * $Revision: 1.1.1.1 $   $Date: 2003/01/23 07:40:29 $
- * IPPL_VERSION_ID: $Id: IpplParticleBaseInteract_Cart_3D.cpp,v 1.1.1.1 2003/01/23 07:40:29 adelmann Exp $ 
- ***************************************************************************/
-
+ * IPPL_VERSION_ID: $Id: ParticleBaseInteract_Cart_3D.cpp,v 1.1.1.1 2003/01/23 07:40:29 adelmann Exp $
+ ***************************************************************************/
\ No newline at end of file
diff --git a/ippl/src/Particle/inst/ParticleBaseInteract_Unif_1D.cpp b/ippl/src/Particle/inst/ParticleBaseInteract_Unif_1D.cpp
index 973ad95e528fbe0f50d5e6f651ea850b782c7fc6..4f75c1a3bfbbc7525ea52ad6fd2acaf6f559cfdb 100644
--- a/ippl/src/Particle/inst/ParticleBaseInteract_Unif_1D.cpp
+++ b/ippl/src/Particle/inst/ParticleBaseInteract_Unif_1D.cpp
@@ -2,8 +2,8 @@
 /***************************************************************************
  *
  * The IPPL Framework
- * 
- * This program was prepared by PSI. 
+ *
+ * This program was prepared by PSI.
  * All rights in the program are reserved by PSI.
  * Neither PSI nor the author(s)
  * makes any warranty, express or implied, or assumes any liability or
@@ -17,7 +17,7 @@
 /***************************************************************************
  *
  * The IPPL Framework
- * 
+ *
  *
  * Visit http://people.web.psi.ch/adelmann/ for more details
  *
@@ -34,8 +34,7 @@ template class IpplParticleBase<ParticleInteractLayout<
 
 
 /***************************************************************************
- * $RCSfile: IpplParticleBaseInteract_Unif_1D.cpp,v $   $Author: adelmann $
+ * $RCSfile: ParticleBaseInteract_Unif_1D.cpp,v $   $Author: adelmann $
  * $Revision: 1.1.1.1 $   $Date: 2003/01/23 07:40:29 $
- * IPPL_VERSION_ID: $Id: IpplParticleBaseInteract_Unif_1D.cpp,v 1.1.1.1 2003/01/23 07:40:29 adelmann Exp $ 
- ***************************************************************************/
-
+ * IPPL_VERSION_ID: $Id: ParticleBaseInteract_Unif_1D.cpp,v 1.1.1.1 2003/01/23 07:40:29 adelmann Exp $
+ ***************************************************************************/
\ No newline at end of file
diff --git a/ippl/src/Particle/inst/ParticleBaseInteract_Unif_2D.cpp b/ippl/src/Particle/inst/ParticleBaseInteract_Unif_2D.cpp
index 57568fd584d3774f584e3ed7c2483fdf35e5ee4d..ba2ae39d4a6da9764695aa5d26956130f59243a4 100644
--- a/ippl/src/Particle/inst/ParticleBaseInteract_Unif_2D.cpp
+++ b/ippl/src/Particle/inst/ParticleBaseInteract_Unif_2D.cpp
@@ -2,8 +2,8 @@
 /***************************************************************************
  *
  * The IPPL Framework
- * 
- * This program was prepared by PSI. 
+ *
+ * This program was prepared by PSI.
  * All rights in the program are reserved by PSI.
  * Neither PSI nor the author(s)
  * makes any warranty, express or implied, or assumes any liability or
@@ -17,7 +17,7 @@
 /***************************************************************************
  *
  * The IPPL Framework
- * 
+ *
  *
  * Visit http://people.web.psi.ch/adelmann/ for more details
  *
@@ -34,8 +34,7 @@ template class IpplParticleBase<ParticleInteractLayout<
 
 
 /***************************************************************************
- * $RCSfile: IpplParticleBaseInteract_Unif_2D.cpp,v $   $Author: adelmann $
+ * $RCSfile: ParticleBaseInteract_Unif_2D.cpp,v $   $Author: adelmann $
  * $Revision: 1.1.1.1 $   $Date: 2003/01/23 07:40:29 $
- * IPPL_VERSION_ID: $Id: IpplParticleBaseInteract_Unif_2D.cpp,v 1.1.1.1 2003/01/23 07:40:29 adelmann Exp $ 
- ***************************************************************************/
-
+ * IPPL_VERSION_ID: $Id: ParticleBaseInteract_Unif_2D.cpp,v 1.1.1.1 2003/01/23 07:40:29 adelmann Exp $
+ ***************************************************************************/
\ No newline at end of file
diff --git a/ippl/src/Particle/inst/ParticleBaseInteract_Unif_3D.cpp b/ippl/src/Particle/inst/ParticleBaseInteract_Unif_3D.cpp
index c8e18936f32afb3b1af9850aafbc7f697437cde6..2225ce7f466bf87f069418381f4e32658b093024 100644
--- a/ippl/src/Particle/inst/ParticleBaseInteract_Unif_3D.cpp
+++ b/ippl/src/Particle/inst/ParticleBaseInteract_Unif_3D.cpp
@@ -2,8 +2,8 @@
 /***************************************************************************
  *
  * The IPPL Framework
- * 
- * This program was prepared by PSI. 
+ *
+ * This program was prepared by PSI.
  * All rights in the program are reserved by PSI.
  * Neither PSI nor the author(s)
  * makes any warranty, express or implied, or assumes any liability or
@@ -17,7 +17,7 @@
 /***************************************************************************
  *
  * The IPPL Framework
- * 
+ *
  *
  * Visit http://people.web.psi.ch/adelmann/ for more details
  *
@@ -34,8 +34,7 @@ template class IpplParticleBase<ParticleInteractLayout<
 
 
 /***************************************************************************
- * $RCSfile: IpplParticleBaseInteract_Unif_3D.cpp,v $   $Author: adelmann $
+ * $RCSfile: ParticleBaseInteract_Unif_3D.cpp,v $   $Author: adelmann $
  * $Revision: 1.1.1.1 $   $Date: 2003/01/23 07:40:29 $
- * IPPL_VERSION_ID: $Id: IpplParticleBaseInteract_Unif_3D.cpp,v 1.1.1.1 2003/01/23 07:40:29 adelmann Exp $ 
- ***************************************************************************/
-
+ * IPPL_VERSION_ID: $Id: ParticleBaseInteract_Unif_3D.cpp,v 1.1.1.1 2003/01/23 07:40:29 adelmann Exp $
+ ***************************************************************************/
\ No newline at end of file
diff --git a/ippl/src/Particle/inst/ParticleBaseSpatial_Cart_1D.cpp b/ippl/src/Particle/inst/ParticleBaseSpatial_Cart_1D.cpp
index d04fd4d9a430c774a7b37ac8e03d168685ad7ec9..fccc58e92f3bff1fbcc6adb15a2158ad1486bbb3 100644
--- a/ippl/src/Particle/inst/ParticleBaseSpatial_Cart_1D.cpp
+++ b/ippl/src/Particle/inst/ParticleBaseSpatial_Cart_1D.cpp
@@ -2,8 +2,8 @@
 /***************************************************************************
  *
  * The IPPL Framework
- * 
- * This program was prepared by PSI. 
+ *
+ * This program was prepared by PSI.
  * All rights in the program are reserved by PSI.
  * Neither PSI nor the author(s)
  * makes any warranty, express or implied, or assumes any liability or
@@ -17,7 +17,7 @@
 /***************************************************************************
  *
  * The IPPL Framework
- * 
+ *
  *
  * Visit http://people.web.psi.ch/adelmann/ for more details
  *
@@ -34,8 +34,7 @@ template class IpplParticleBase<ParticleSpatialLayout<
 
 
 /***************************************************************************
- * $RCSfile: IpplParticleBaseSpatial_Cart_1D.cpp,v $   $Author: adelmann $
+ * $RCSfile: ParticleBaseSpatial_Cart_1D.cpp,v $   $Author: adelmann $
  * $Revision: 1.1.1.1 $   $Date: 2003/01/23 07:40:29 $
- * IPPL_VERSION_ID: $Id: IpplParticleBaseSpatial_Cart_1D.cpp,v 1.1.1.1 2003/01/23 07:40:29 adelmann Exp $ 
- ***************************************************************************/
-
+ * IPPL_VERSION_ID: $Id: ParticleBaseSpatial_Cart_1D.cpp,v 1.1.1.1 2003/01/23 07:40:29 adelmann Exp $
+ ***************************************************************************/
\ No newline at end of file
diff --git a/ippl/src/Particle/inst/ParticleBaseSpatial_Cart_2D.cpp b/ippl/src/Particle/inst/ParticleBaseSpatial_Cart_2D.cpp
index 9ecaf9de1d463ecbcaf9d060b94e0a67760761c1..4a1f3d42bcb6b6aa4559dee855b81e1ea1842107 100644
--- a/ippl/src/Particle/inst/ParticleBaseSpatial_Cart_2D.cpp
+++ b/ippl/src/Particle/inst/ParticleBaseSpatial_Cart_2D.cpp
@@ -2,8 +2,8 @@
 /***************************************************************************
  *
  * The IPPL Framework
- * 
- * This program was prepared by PSI. 
+ *
+ * This program was prepared by PSI.
  * All rights in the program are reserved by PSI.
  * Neither PSI nor the author(s)
  * makes any warranty, express or implied, or assumes any liability or
@@ -17,7 +17,7 @@
 /***************************************************************************
  *
  * The IPPL Framework
- * 
+ *
  *
  * Visit http://people.web.psi.ch/adelmann/ for more details
  *
@@ -36,6 +36,5 @@ template class IpplParticleBase<ParticleSpatialLayout<
 /***************************************************************************
  * $RCSfile: IpplParticleBaseSpatial_Cart_2D.cpp,v $   $Author: adelmann $
  * $Revision: 1.1.1.1 $   $Date: 2003/01/23 07:40:29 $
- * IPPL_VERSION_ID: $Id: IpplParticleBaseSpatial_Cart_2D.cpp,v 1.1.1.1 2003/01/23 07:40:29 adelmann Exp $ 
- ***************************************************************************/
-
+ * IPPL_VERSION_ID: $Id: IpplParticleBaseSpatial_Cart_2D.cpp,v 1.1.1.1 2003/01/23 07:40:29 adelmann Exp $
+ ***************************************************************************/
\ No newline at end of file
diff --git a/ippl/src/Particle/inst/ParticleBaseSpatial_Cart_3D.cpp b/ippl/src/Particle/inst/ParticleBaseSpatial_Cart_3D.cpp
index adc2414460bcb6e71d26666da6701c294a3d54fd..da3757998478821672524d83e3c699203faa8e38 100644
--- a/ippl/src/Particle/inst/ParticleBaseSpatial_Cart_3D.cpp
+++ b/ippl/src/Particle/inst/ParticleBaseSpatial_Cart_3D.cpp
@@ -2,8 +2,8 @@
 /***************************************************************************
  *
  * The IPPL Framework
- * 
- * This program was prepared by PSI. 
+ *
+ * This program was prepared by PSI.
  * All rights in the program are reserved by PSI.
  * Neither PSI nor the author(s)
  * makes any warranty, express or implied, or assumes any liability or
@@ -17,7 +17,7 @@
 /***************************************************************************
  *
  * The IPPL Framework
- * 
+ *
  *
  * Visit http://people.web.psi.ch/adelmann/ for more details
  *
@@ -34,8 +34,7 @@ template class IpplParticleBase<ParticleSpatialLayout<
 
 
 /***************************************************************************
- * $RCSfile: IpplParticleBaseSpatial_Cart_3D.cpp,v $   $Author: adelmann $
+ * $RCSfile: ParticleBaseSpatial_Cart_3D.cpp,v $   $Author: adelmann $
  * $Revision: 1.1.1.1 $   $Date: 2003/01/23 07:40:29 $
- * IPPL_VERSION_ID: $Id: IpplParticleBaseSpatial_Cart_3D.cpp,v 1.1.1.1 2003/01/23 07:40:29 adelmann Exp $ 
- ***************************************************************************/
-
+ * IPPL_VERSION_ID: $Id: ParticleBaseSpatial_Cart_3D.cpp,v 1.1.1.1 2003/01/23 07:40:29 adelmann Exp $
+ ***************************************************************************/
\ No newline at end of file
diff --git a/ippl/src/Particle/inst/ParticleBaseSpatial_Unif_1D.cpp b/ippl/src/Particle/inst/ParticleBaseSpatial_Unif_1D.cpp
index 6afa33ee6af795fb1edf999399d45dd4cf753224..ae5e21475510db016d5c33304afd6e1ad3d3ed12 100644
--- a/ippl/src/Particle/inst/ParticleBaseSpatial_Unif_1D.cpp
+++ b/ippl/src/Particle/inst/ParticleBaseSpatial_Unif_1D.cpp
@@ -2,8 +2,8 @@
 /***************************************************************************
  *
  * The IPPL Framework
- * 
- * This program was prepared by PSI. 
+ *
+ * This program was prepared by PSI.
  * All rights in the program are reserved by PSI.
  * Neither PSI nor the author(s)
  * makes any warranty, express or implied, or assumes any liability or
@@ -17,7 +17,7 @@
 /***************************************************************************
  *
  * The IPPL Framework
- * 
+ *
  *
  * Visit http://people.web.psi.ch/adelmann/ for more details
  *
@@ -34,8 +34,7 @@ template class IpplParticleBase<ParticleSpatialLayout<
 
 
 /***************************************************************************
- * $RCSfile: IpplParticleBaseSpatial_Unif_1D.cpp,v $   $Author: adelmann $
+ * $RCSfile: ParticleBaseSpatial_Unif_1D.cpp,v $   $Author: adelmann $
  * $Revision: 1.1.1.1 $   $Date: 2003/01/23 07:40:29 $
- * IPPL_VERSION_ID: $Id: IpplParticleBaseSpatial_Unif_1D.cpp,v 1.1.1.1 2003/01/23 07:40:29 adelmann Exp $ 
- ***************************************************************************/
-
+ * IPPL_VERSION_ID: $Id: ParticleBaseSpatial_Unif_1D.cpp,v 1.1.1.1 2003/01/23 07:40:29 adelmann Exp $
+ ***************************************************************************/
\ No newline at end of file
diff --git a/ippl/src/Particle/inst/ParticleBaseSpatial_Unif_2D.cpp b/ippl/src/Particle/inst/ParticleBaseSpatial_Unif_2D.cpp
index 4c716a71d7025bbc0d8085d681720ee3dac844e5..a20d01d0c24fdc4d3a8be5c469973b9311d20aea 100644
--- a/ippl/src/Particle/inst/ParticleBaseSpatial_Unif_2D.cpp
+++ b/ippl/src/Particle/inst/ParticleBaseSpatial_Unif_2D.cpp
@@ -2,8 +2,8 @@
 /***************************************************************************
  *
  * The IPPL Framework
- * 
- * This program was prepared by PSI. 
+ *
+ * This program was prepared by PSI.
  * All rights in the program are reserved by PSI.
  * Neither PSI nor the author(s)
  * makes any warranty, express or implied, or assumes any liability or
@@ -17,7 +17,7 @@
 /***************************************************************************
  *
  * The IPPL Framework
- * 
+ *
  *
  * Visit http://people.web.psi.ch/adelmann/ for more details
  *
@@ -34,8 +34,7 @@ template class IpplParticleBase<ParticleSpatialLayout<
 
 
 /***************************************************************************
- * $RCSfile: IpplParticleBaseSpatial_Unif_2D.cpp,v $   $Author: adelmann $
+ * $RCSfile: ParticleBaseSpatial_Unif_2D.cpp,v $   $Author: adelmann $
  * $Revision: 1.1.1.1 $   $Date: 2003/01/23 07:40:29 $
- * IPPL_VERSION_ID: $Id: IpplParticleBaseSpatial_Unif_2D.cpp,v 1.1.1.1 2003/01/23 07:40:29 adelmann Exp $ 
- ***************************************************************************/
-
+ * IPPL_VERSION_ID: $Id: ParticleBaseSpatial_Unif_2D.cpp,v 1.1.1.1 2003/01/23 07:40:29 adelmann Exp $
+ ***************************************************************************/
\ No newline at end of file
diff --git a/ippl/src/Particle/inst/ParticleBaseSpatial_Unif_3D.cpp b/ippl/src/Particle/inst/ParticleBaseSpatial_Unif_3D.cpp
index 7b9257c9c9f2f4f7e60d7794b28656e6d6c53ede..9c15b359a4880d8088f3b5c116e1780b38ffd283 100644
--- a/ippl/src/Particle/inst/ParticleBaseSpatial_Unif_3D.cpp
+++ b/ippl/src/Particle/inst/ParticleBaseSpatial_Unif_3D.cpp
@@ -2,8 +2,8 @@
 /***************************************************************************
  *
  * The IPPL Framework
- * 
- * This program was prepared by PSI. 
+ *
+ * This program was prepared by PSI.
  * All rights in the program are reserved by PSI.
  * Neither PSI nor the author(s)
  * makes any warranty, express or implied, or assumes any liability or
@@ -17,7 +17,7 @@
 /***************************************************************************
  *
  * The IPPL Framework
- * 
+ *
  *
  * Visit http://people.web.psi.ch/adelmann/ for more details
  *
@@ -36,6 +36,5 @@ template class IpplParticleBase<ParticleSpatialLayout<
 /***************************************************************************
  * $RCSfile: IpplParticleBaseSpatial_Unif_3D.cpp,v $   $Author: adelmann $
  * $Revision: 1.1.1.1 $   $Date: 2003/01/23 07:40:29 $
- * IPPL_VERSION_ID: $Id: IpplParticleBaseSpatial_Unif_3D.cpp,v 1.1.1.1 2003/01/23 07:40:29 adelmann Exp $ 
- ***************************************************************************/
-
+ * IPPL_VERSION_ID: $Id: IpplParticleBaseSpatial_Unif_3D.cpp,v 1.1.1.1 2003/01/23 07:40:29 adelmann Exp $
+ ***************************************************************************/
\ No newline at end of file
diff --git a/ippl/src/Particle/inst/ParticleBaseUniform_1D.cpp b/ippl/src/Particle/inst/ParticleBaseUniform_1D.cpp
index 3c3f2e5213780be4cc423213da5e56071b3293af..bf39ac1d6c3e0e03c1a75703d49a65e2c3f66409 100644
--- a/ippl/src/Particle/inst/ParticleBaseUniform_1D.cpp
+++ b/ippl/src/Particle/inst/ParticleBaseUniform_1D.cpp
@@ -2,8 +2,8 @@
 /***************************************************************************
  *
  * The IPPL Framework
- * 
- * This program was prepared by PSI. 
+ *
+ * This program was prepared by PSI.
  * All rights in the program are reserved by PSI.
  * Neither PSI nor the author(s)
  * makes any warranty, express or implied, or assumes any liability or
@@ -17,7 +17,7 @@
 /***************************************************************************
  *
  * The IPPL Framework
- * 
+ *
  *
  * Visit http://people.web.psi.ch/adelmann/ for more details
  *
@@ -34,5 +34,5 @@ template class IpplParticleBase< ParticleUniformLayout<IPPL_PRECISION_TYPE,1U> >
 /***************************************************************************
  * $RCSfile: IpplParticleBaseUniform_1D.cpp,v $   $Author: adelmann $
  * $Revision: 1.1.1.1 $   $Date: 2003/01/23 07:40:29 $
- * IPPL_VERSION_ID: $Id: IpplParticleBaseUniform_1D.cpp,v 1.1.1.1 2003/01/23 07:40:29 adelmann Exp $ 
- ***************************************************************************/
+ * IPPL_VERSION_ID: $Id: IpplParticleBaseUniform_1D.cpp,v 1.1.1.1 2003/01/23 07:40:29 adelmann Exp $
+ ***************************************************************************/
\ No newline at end of file
diff --git a/ippl/src/Particle/inst/ParticleBaseUniform_2D.cpp b/ippl/src/Particle/inst/ParticleBaseUniform_2D.cpp
index 646a67c825f54182fcfeb9b3a4bf9fc912926d57..e8d93a243e4ba8d1226d076f437e44093fae1fc9 100644
--- a/ippl/src/Particle/inst/ParticleBaseUniform_2D.cpp
+++ b/ippl/src/Particle/inst/ParticleBaseUniform_2D.cpp
@@ -2,8 +2,8 @@
 /***************************************************************************
  *
  * The IPPL Framework
- * 
- * This program was prepared by PSI. 
+ *
+ * This program was prepared by PSI.
  * All rights in the program are reserved by PSI.
  * Neither PSI nor the author(s)
  * makes any warranty, express or implied, or assumes any liability or
@@ -17,7 +17,7 @@
 /***************************************************************************
  *
  * The IPPL Framework
- * 
+ *
  *
  * Visit http://people.web.psi.ch/adelmann/ for more details
  *
@@ -34,5 +34,5 @@ template class IpplParticleBase< ParticleUniformLayout<IPPL_PRECISION_TYPE,2U> >
 /***************************************************************************
  * $RCSfile: IpplParticleBaseUniform_2D.cpp,v $   $Author: adelmann $
  * $Revision: 1.1.1.1 $   $Date: 2003/01/23 07:40:29 $
- * IPPL_VERSION_ID: $Id: IpplParticleBaseUniform_2D.cpp,v 1.1.1.1 2003/01/23 07:40:29 adelmann Exp $ 
- ***************************************************************************/
+ * IPPL_VERSION_ID: $Id: IpplParticleBaseUniform_2D.cpp,v 1.1.1.1 2003/01/23 07:40:29 adelmann Exp $
+ ***************************************************************************/
\ No newline at end of file
diff --git a/ippl/src/Particle/inst/ParticleBaseUniform_3D.cpp b/ippl/src/Particle/inst/ParticleBaseUniform_3D.cpp
index c95afdf19ebd19ca1c45655916138a38fb6ff9d2..85c8887499746668b86b6df88485d6041d9ade48 100644
--- a/ippl/src/Particle/inst/ParticleBaseUniform_3D.cpp
+++ b/ippl/src/Particle/inst/ParticleBaseUniform_3D.cpp
@@ -2,8 +2,8 @@
 /***************************************************************************
  *
  * The IPPL Framework
- * 
- * This program was prepared by PSI. 
+ *
+ * This program was prepared by PSI.
  * All rights in the program are reserved by PSI.
  * Neither PSI nor the author(s)
  * makes any warranty, express or implied, or assumes any liability or
@@ -17,7 +17,7 @@
 /***************************************************************************
  *
  * The IPPL Framework
- * 
+ *
  *
  * Visit http://people.web.psi.ch/adelmann/ for more details
  *
@@ -32,7 +32,7 @@ template class IpplParticleBase< ParticleUniformLayout<IPPL_PRECISION_TYPE,3U> >
 
 
 /***************************************************************************
- * $RCSfile: IpplParticleBaseUniform_3D.cpp,v $   $Author: adelmann $
+ * $RCSfile: ParticleBaseUniform_3D.cpp,v $   $Author: adelmann $
  * $Revision: 1.1.1.1 $   $Date: 2003/01/23 07:40:32 $
- * IPPL_VERSION_ID: $Id: IpplParticleBaseUniform_3D.cpp,v 1.1.1.1 2003/01/23 07:40:32 adelmann Exp $ 
- ***************************************************************************/
+ * IPPL_VERSION_ID: $Id: ParticleBaseUniform_3D.cpp,v 1.1.1.1 2003/01/23 07:40:32 adelmann Exp $
+ ***************************************************************************/
\ No newline at end of file
diff --git a/ippl/src/Profile/CMakeLists.txt b/ippl/src/Profile/CMakeLists.txt
index 5048cd39a95d133918b6bf9bf626bf7b4997ab8c..676a3ad97750f820cd96477e28d3d97bb29c0e5a 100644
--- a/ippl/src/Profile/CMakeLists.txt
+++ b/ippl/src/Profile/CMakeLists.txt
@@ -9,7 +9,7 @@ INCLUDE_DIRECTORIES (
   ${CMAKE_CURRENT_SOURCE_DIR}
 )
 
-ADD_SOURCES (${_SRCS})
-ADD_HEADERS (${_HDRS})
+ADD_IPPL_SOURCES (${_SRCS})
+ADD_IPPL_HEADERS (${_HDRS})
 
 INSTALL (FILES ${_HDRS} DESTINATION include/Profile)
diff --git a/ippl/src/Region/CMakeLists.txt b/ippl/src/Region/CMakeLists.txt
index 35da0fc517cf0078d225850ca2be1d876cb9aee7..3c927dcd5b482d0cc5bec9960699bae32c0a4e96 100644
--- a/ippl/src/Region/CMakeLists.txt
+++ b/ippl/src/Region/CMakeLists.txt
@@ -13,7 +13,7 @@ INCLUDE_DIRECTORIES (
   ${CMAKE_CURRENT_SOURCE_DIR}
 )
 
-ADD_SOURCES (${_SRCS})
-ADD_HEADERS (${_HDRS})
+ADD_IPPL_SOURCES (${_SRCS})
+ADD_IPPL_HEADERS (${_HDRS})
 
 INSTALL (FILES ${_HDRS} DESTINATION include/Region)
diff --git a/ippl/src/SubField/CMakeLists.txt b/ippl/src/SubField/CMakeLists.txt
index 5d1b26e4219ba718068997f3584cb5b3bf101587..e12cadc67d0daa04b16a4d0de88c4cf67acb5571 100644
--- a/ippl/src/SubField/CMakeLists.txt
+++ b/ippl/src/SubField/CMakeLists.txt
@@ -17,7 +17,7 @@ INCLUDE_DIRECTORIES (
   ${CMAKE_CURRENT_SOURCE_DIR}
 )
 
-ADD_SOURCES (${_SRCS})
-ADD_HEADERS (${_HDRS})
+ADD_IPPL_SOURCES (${_SRCS})
+ADD_IPPL_HEADERS (${_HDRS})
 
 INSTALL (FILES ${_HDRS} DESTINATION include/SubField)
diff --git a/ippl/src/SubParticle/CMakeLists.txt b/ippl/src/SubParticle/CMakeLists.txt
index 9ef1b82e686ac47370826828db01752811b52dce..e70a5ab6cd16244ef5c2cba6a98fb515c5827f4d 100644
--- a/ippl/src/SubParticle/CMakeLists.txt
+++ b/ippl/src/SubParticle/CMakeLists.txt
@@ -13,7 +13,7 @@ INCLUDE_DIRECTORIES (
   ${CMAKE_CURRENT_SOURCE_DIR}
 )
 
-ADD_SOURCES (${_SRCS})
-ADD_HEADERS (${_HDRS})
+ADD_IPPL_SOURCES (${_SRCS})
+ADD_IPPL_HEADERS (${_HDRS})
 
 INSTALL (FILES ${_HDRS} DESTINATION include/SubParticle)
diff --git a/ippl/src/Utility/CMakeLists.txt b/ippl/src/Utility/CMakeLists.txt
index 88a1946b2f2e3a8d8b33a9f02a2228b104c6e6e7..db5c7f254a9bd8007f39f03c9c0e2b14bde49ec4 100644
--- a/ippl/src/Utility/CMakeLists.txt
+++ b/ippl/src/Utility/CMakeLists.txt
@@ -17,6 +17,7 @@ SET (_SRCS
   RNGXDiv.cpp
   RNGXCI.cpp
   RandomNumberGen.cpp
+  StaticIpplInfo.cpp
   Timer.cpp
   Unique.cpp
   User.cpp
@@ -72,6 +73,7 @@ SET (_HDRS
   RNGXCI.h
   RNGXDiv.h
   SequenceGen.h
+  StaticIpplInfo.h
   Timer.h
   Unique.h
   User.h
@@ -85,7 +87,7 @@ INCLUDE_DIRECTORIES (
   ${CMAKE_CURRENT_SOURCE_DIR}
 )
 
-ADD_SOURCES (${_SRCS})
-ADD_HEADERS (${_HDRS})
+ADD_IPPL_SOURCES (${_SRCS})
+ADD_IPPL_HEADERS (${_HDRS})
 
-INSTALL (FILES ${_HDRS} DESTINATION include/Utility)
+INSTALL (FILES ${_HDRS} DESTINATION include/Utility)
\ No newline at end of file
diff --git a/ippl/src/Utility/DiscParticle.h b/ippl/src/Utility/DiscParticle.h
index 84938e522cf9d16d2ac104d6165d7c8fcaa04d42..a35c3065af185fba593047a44896597bae30ba49 100644
--- a/ippl/src/Utility/DiscParticle.h
+++ b/ippl/src/Utility/DiscParticle.h
@@ -2,7 +2,7 @@
 /***************************************************************************
  *
  * The IPPL Framework
- * 
+ *
  *
  * Visit http://people.web.psi.ch/adelmann/ for more details
  *
@@ -150,7 +150,7 @@ public:
   bool read(IpplParticleBase<T> &pbase, unsigned int record) {
 
     // re-read the meta file since it might have changed
-    ConfigOK = read_meta(); 
+    ConfigOK = read_meta();
 
     // do some sanity checking first
     if (!ConfigOK) {
@@ -660,7 +660,7 @@ public:
 
 private:
   // a typedef used to select the data type for file offsets
-  typedef long  Offset_t; 
+  typedef long  Offset_t;
 
   // the configuration file mechanism
   DiscConfig *Config;
@@ -677,7 +677,7 @@ private:
   // file set
   struct RecordInfo {
     // a typedef used to select the data type for file offsets
-    typedef long  Offset_t; 
+    typedef long  Offset_t;
 
     int attributes;		 // number of attributes; 0 == just writing
 				 // one attribute, > 0 == writing a whole
@@ -744,5 +744,5 @@ private:
 /***************************************************************************
  * $RCSfile: DiscParticle.h,v $   $Author: adelmann $
  * $Revision: 1.1.1.1 $   $Date: 2003/01/23 07:40:33 $
- * IPPL_VERSION_ID: $Id: DiscParticle.h,v 1.1.1.1 2003/01/23 07:40:33 adelmann Exp $ 
- ***************************************************************************/
+ * IPPL_VERSION_ID: $Id: DiscParticle.h,v 1.1.1.1 2003/01/23 07:40:33 adelmann Exp $
+ ***************************************************************************/
\ No newline at end of file
diff --git a/ippl/src/Utility/IpplInfo.cpp b/ippl/src/Utility/IpplInfo.cpp
index ce4e63f91c3c165b9259ed100bfc0d06170d3c23..5c7789574e0fa53694f020616cf581b54542e2b7 100644
--- a/ippl/src/Utility/IpplInfo.cpp
+++ b/ippl/src/Utility/IpplInfo.cpp
@@ -2,8 +2,8 @@
 /***************************************************************************
  *
  * The IPPL Framework
- * 
- * This program was prepared by PSI. 
+ *
+ * This program was prepared by PSI.
  * All rights in the program are reserved by PSI.
  * Neither PSI nor the author(s)
  * makes any warranty, express or implied, or assumes any liability or
@@ -17,7 +17,7 @@
 /***************************************************************************
  *
  * The IPPL Framework
- * 
+ *
  *
  * Visit http://people.web.psi.ch/adelmann/ for more details
  *
@@ -47,6 +47,7 @@ Inform *IpplInfo::Info = new Inform("Ippl");
 Inform *IpplInfo::Warn = new Inform("Warning", std::cerr);
 Inform *IpplInfo::Error = new Inform("Error", std::cerr, INFORM_ALL_NODES);
 Inform *IpplInfo::Debug = new Inform("**DEBUG**", std::cerr, INFORM_ALL_NODES);
+std::stack<StaticIpplInfo> IpplInfo::stashedStaticMembers;
 
 //dks base member of IpplInfo initialized to default values
 bool IpplInfo::DKSEnabled = false;
@@ -194,7 +195,7 @@ IpplInfo::IpplInfo(int& argc, char**& argv, int removeargs, MPI_Comm mpicomm) {
         bool startcomm = false;
         bool comminit = true;         // do comm. system's init call
         int nprocs = (-1);		// num of processes to start; -1 means default
-        
+
 
         /*
           if no argument is given, we assume mpi as
@@ -230,7 +231,7 @@ IpplInfo::IpplInfo(int& argc, char**& argv, int removeargs, MPI_Comm mpicomm) {
                 // whatever initialization routine it might have (like MPI_Init).
                 // This is in case another agency has already done the initialization.
                 comminit = false;
-            } 
+            }
         }
 
         // create Communicate object now.
@@ -241,6 +242,7 @@ IpplInfo::IpplInfo(int& argc, char**& argv, int removeargs, MPI_Comm mpicomm) {
             Communicate *newcomm = CommCreator::create(commtype.c_str(),
                     argc, argv,
                     nprocs, comminit, mpicomm);
+
             if (newcomm == 0) {
                 if (CommCreator::supported(commtype.c_str()))
                     param_error("--commlib", "Could not initialize this ",
@@ -284,7 +286,7 @@ IpplInfo::IpplInfo(int& argc, char**& argv, int removeargs, MPI_Comm mpicomm) {
             for (i=1; i < argc; ++i)
                 retargv[retargc++] = argv[i];
 
-        
+
         // Parse command-line options, looking for ippl options.  When found,
         // save their suggested values and use them at the end to create data, etc.
         for (i=1; i < argc; ++i) {
@@ -403,7 +405,7 @@ IpplInfo::IpplInfo(int& argc, char**& argv, int removeargs, MPI_Comm mpicomm) {
                     ++i;
 
             } else if   ( strcmp(argv[i], "--profile") == 0 )  {
-                // handled above in 
+                // handled above in
                 if ( (i + 1) < argc && argv[i+1][0] != '-' )
                     ++i;
 
@@ -601,7 +603,7 @@ IpplInfo::~IpplInfo() {
     // close communication and clean up
     // Inform dbgmsg("IpplInfo::~IpplInfo", INFORM_ALL_NODES);
     // dbgmsg << "In destructor: Current NumCreated = " << NumCreated << endl;
-        
+
     if ((--NumCreated) == 0) {
         // at end of program, print statistics if requested to do so
         if (PrintStats) {
@@ -616,6 +618,7 @@ IpplInfo::~IpplInfo() {
              // dbgmsg << "  Deleting comm object, since now NumCreated = ";
              // dbgmsg << NumCreated << endl;
              delete Comm;
+             Comm = new Communicate();
 
              NeedDeleteComm = false;
         }
@@ -623,13 +626,19 @@ IpplInfo::~IpplInfo() {
 
         // delete other dynamically-allocated static objects
         delete [] MyArgv;
-        if (SMPIDList != 0)
+        if (SMPIDList != 0) {
             delete [] SMPIDList;
-        if (SMPNodeList != 0)
+        }
+        if (SMPNodeList != 0) {
             delete [] SMPNodeList;
-        
+        }
         delete Stats;
-    } 
+
+        MyArgv = 0;
+        SMPIDList = 0;
+        SMPNodeList = 0;
+        Stats = 0;
+    }
 }
 
 
@@ -667,7 +676,7 @@ void IpplInfo::abort(const char *msg, int exitcode) {
     }
 
     // that's it, folks this error will be propperly catched in the main
-    throw std::runtime_error("Error form IpplInfo::abort");   
+    throw std::runtime_error("Error form IpplInfo::abort");
 }
 
 
@@ -694,7 +703,7 @@ void IpplInfo::abortAllNodes(const char *msg, bool abortThisNode) {
     if (getNodes() > 1)
         Comm->broadcast_others(new Message, IPPL_ABORT_TAG);
 
-    throw std::runtime_error("Error form IpplInfo::abortAllNodes");   
+    throw std::runtime_error("Error form IpplInfo::abortAllNodes");
 
 }
 
@@ -801,7 +810,7 @@ void IpplInfo::printVersion(bool printFull) {
 
 /////////////////////////////////////////////////////////////////////
 // here: as in stop in IpplInfo::here (in the debugger)
-void IpplInfo::here() 
+void IpplInfo::here()
 {
 }
 
@@ -1006,6 +1015,110 @@ void IpplInfo::find_smp_nodes() {
     // }
 }
 
+void IpplInfo::stash() {
+    PAssert(stashedStaticMembers.size() == 0);
+
+    StaticIpplInfo obj;
+
+    obj.Comm =                Comm;
+    obj.Stats =               Stats;
+    obj.deferGuardCellFills = deferGuardCellFills;
+    obj.noFieldCompression =  noFieldCompression;
+    obj.offsetStorage =       offsetStorage;
+    obj.extraCompressChecks = extraCompressChecks;
+    obj.useDirectIO =         useDirectIO;
+    obj.communicator_m =      communicator_m;
+    obj.NumCreated =          NumCreated;
+    obj.CommInitialized =     CommInitialized;
+    obj.PrintStats =          PrintStats;
+    obj.NeedDeleteComm =      NeedDeleteComm;
+    obj.UseChecksums =        UseChecksums;
+    obj.Retransmit =          Retransmit;
+    obj.MyArgc =              MyArgc;
+    obj.MyArgv =              MyArgv;
+    obj.MyNode =              MyNode;
+    obj.TotalNodes =          TotalNodes;
+    obj.NumSMPs =             NumSMPs;
+    obj.SMPIDList =           SMPIDList;
+    obj.SMPNodeList =         SMPNodeList;
+    obj.MaxFFTNodes =         MaxFFTNodes;
+    obj.ChunkSize =           ChunkSize;
+    obj.PerSMPParallelIO =    PerSMPParallelIO;
+
+#ifdef IPPL_COMM_ALARMS
+    obj.CommTimeoutSeconds = CommTimeoutSeconds;
+#endif
+
+    stashedStaticMembers.push(obj);
+
+    Comm = new Communicate();
+    Stats = new IpplStats();
+    deferGuardCellFills = false;
+    noFieldCompression = false;
+    offsetStorage = false;
+    extraCompressChecks = false;
+    useDirectIO = false;
+    communicator_m = MPI_COMM_WORLD;
+    NumCreated = 0;
+    CommInitialized = false;
+    PrintStats = false;
+    NeedDeleteComm = false;
+    UseChecksums = false;
+    Retransmit = false;
+    MyArgc = 0;
+    MyArgv = 0;
+    MyNode = 0;
+    TotalNodes = 1;
+    NumSMPs = 1;
+    SMPIDList = 0;
+    SMPNodeList = 0;
+    MaxFFTNodes = 0;
+    ChunkSize = 512*1024; // 512K == 64K doubles
+    PerSMPParallelIO = false;
+}
+
+void IpplInfo::pop() {
+    PAssert(stashedStaticMembers.size() == 1);
+
+    StaticIpplInfo obj = stashedStaticMembers.top();
+    stashedStaticMembers.pop();
+    // Delete the communications object, if necessary, to shut down parallel
+    // environment
+    delete Comm;
+    delete [] MyArgv;
+    delete [] SMPIDList;
+    delete [] SMPNodeList;
+    delete Stats;
+
+    Comm =                obj.Comm;
+    Stats =               obj.Stats;
+    deferGuardCellFills = obj.deferGuardCellFills;
+    noFieldCompression =  obj.noFieldCompression;
+    offsetStorage =       obj.offsetStorage;
+    extraCompressChecks = obj.extraCompressChecks;
+    useDirectIO =         obj.useDirectIO;
+    communicator_m =      obj.communicator_m;
+    NumCreated =          obj.NumCreated;
+    CommInitialized =     obj.CommInitialized;
+    PrintStats =          obj.PrintStats;
+    NeedDeleteComm =      obj.NeedDeleteComm;
+    UseChecksums =        obj.UseChecksums;
+    Retransmit =          obj.Retransmit;
+    MyArgc =              obj.MyArgc;
+    MyArgv =              obj.MyArgv;
+    MyNode =              obj.MyNode;
+    TotalNodes =          obj.TotalNodes;
+    NumSMPs =             obj.NumSMPs;
+    SMPIDList =           obj.SMPIDList;
+    SMPNodeList =         obj.SMPNodeList;
+    MaxFFTNodes =         obj.MaxFFTNodes;
+    ChunkSize =           obj.ChunkSize;
+    PerSMPParallelIO =    obj.PerSMPParallelIO;
+
+#ifdef IPPL_COMM_ALARMS
+    CommTimeoutSeconds = obj.CommTimeoutSeconds;
+#endif
+}
 
 #ifdef IPPL_RUNTIME_ERRCHECK
 /////////////////////////////////////////////////////////////////////
@@ -1034,5 +1147,5 @@ void __C_runtime_error ( int trap_code, char *name, int line_no, ... ) {
 /***************************************************************************
  * $RCSfile: IpplInfo.cpp,v $   $Author: adelmann $
  * $Revision: 1.1.1.1 $   $Date: 2003/01/23 07:40:33 $
- * IPPL_VERSION_ID: $Id: IpplInfo.cpp,v 1.1.1.1 2003/01/23 07:40:33 adelmann Exp $ 
- ***************************************************************************/
+ * IPPL_VERSION_ID: $Id: IpplInfo.cpp,v 1.1.1.1 2003/01/23 07:40:33 adelmann Exp $
+ ***************************************************************************/
\ No newline at end of file
diff --git a/ippl/src/Utility/IpplInfo.h b/ippl/src/Utility/IpplInfo.h
index b215dfa18d0d38ab027e1d8f4740529839d2dc2b..acace03e86cc65c0fb6598be1b323ad039f71561 100644
--- a/ippl/src/Utility/IpplInfo.h
+++ b/ippl/src/Utility/IpplInfo.h
@@ -2,7 +2,7 @@
 /***************************************************************************
  *
  * The IPPL Framework
- * 
+ *
  *
  * Visit http://people.web.psi.ch/adelmann/ for more details
  *
@@ -11,7 +11,7 @@
 #ifndef IPPL_INFO_H
 #define IPPL_INFO_H
 
-/* 
+/*
  * IpplInfo.has the following capabilities:
  *   1) It initializes all globally-used Ippl variables, such as the
  *      Communicate class and other manager classes;
@@ -46,8 +46,10 @@
 // include files
 #include "Utility/Inform.h"
 #include "Message/Communicate.h"
+#include "Utility/StaticIpplInfo.h"
 
 #include <iostream>
+#include <stack>
 
 //FIXME: Including this header here (regardless of the used commlib) here is
 //necessary to enable IPPL to work on a user define communicator group
@@ -81,11 +83,6 @@ public:
   // or REMOVE them
   enum { KEEP = 0, REMOVE = 1 };
 
-  //
-  // global static objects, available to all Ippl applications (even if
-  // no IpplInfo object is instantiated)
-  //
-
   // Inform object to use to print messages to the console (or even to a
   // file if requested)
   static Inform *Info;
@@ -104,7 +101,6 @@ public:
   static DKSBase *DKS;
 #endif
 
-public:
   // Constructor 1: specify the argc, argv values from the cmd line.
   // The second argument controls whether the IPPL-specific command line
   // arguments are stripped out (the default) or left in (if the setting
@@ -179,7 +175,7 @@ public:
   //
   // Functions which return information about the current Ippl application.
   //
-  
+
   static MPI_Comm getComm() {return communicator_m;}
 
   // Return the number of the 'current' node.
@@ -287,6 +283,12 @@ public:
   //Static flag telling wheteher to use DKS when runnign OPAL
   static bool DKSEnabled;
 
+  // stash all static members
+  static void stash();
+
+  // restore all static members
+  static void pop();
+
   // Static flag telling whether to use optimization for reducing
   // communication by deferring guard cell fills.
   static bool deferGuardCellFills;
@@ -374,16 +376,18 @@ private:
   static unsigned int CommTimeoutSeconds;
 #endif
 
+  static std::stack<StaticIpplInfo> stashedStaticMembers;
+
   // Indicate an error occurred while trying to parse the given command-line
   // option, and quit.  Arguments are: parameter, error message, bad value
-  void param_error(const char *, const char *, const char *);
-  void param_error(const char *, const char *, const char *, const char *);
+  static void param_error(const char *, const char *, const char *);
+  static void param_error(const char *, const char *, const char *, const char *);
 
   // find out how many SMP's there are, and which processor we are on
   // our local SMP (e.g., if there are two SMP's with 4 nodes each,
   // the process will have a node number from 0 ... 7, and an SMP node
   // number from 0 ... 3
-  void find_smp_nodes();
+  static void find_smp_nodes();
 };
 
 // macros used to print out messages to the console or a directed file
@@ -408,5 +412,5 @@ typedef IpplInfo Ippl;
 /***************************************************************************
  * $RCSfile: IpplInfo.h,v $   $Author: adelmann $
  * $Revision: 1.1.1.1 $   $Date: 2003/01/23 07:40:33 $
- * IPPL_VERSION_ID: $Id: IpplInfo.h,v 1.1.1.1 2003/01/23 07:40:33 adelmann Exp $ 
- ***************************************************************************/
+ * IPPL_VERSION_ID: $Id: IpplInfo.h,v 1.1.1.1 2003/01/23 07:40:33 adelmann Exp $
+ ***************************************************************************/
\ No newline at end of file
diff --git a/ippl/src/Utility/IpplTimings.cpp b/ippl/src/Utility/IpplTimings.cpp
index fef23e11e850fb49e7a031cacfb2869a145af332..5c8066cb45d04ed7e12cdd30ea54431b632f9230 100644
--- a/ippl/src/Utility/IpplTimings.cpp
+++ b/ippl/src/Utility/IpplTimings.cpp
@@ -36,69 +36,79 @@
 #include <iostream>
 #include <algorithm>
 // static data members of IpplTimings class
-IpplTimings::TimerList_t IpplTimings::TimerList;
-IpplTimings::TimerMap_t  IpplTimings::TimerMap;
 
+Timing* IpplTimings::instance = new Timing();
+std::stack<Timing*> IpplTimings::stashedInstance;
 
 //////////////////////////////////////////////////////////////////////
 // default constructor
-IpplTimings::IpplTimings() { }
+Timing::Timing():
+    TimerList(),
+    TimerMap()
+{ }
 
 
 //////////////////////////////////////////////////////////////////////
 // destructor
-IpplTimings::~IpplTimings() { }
+Timing::~Timing() {
+    for (TimerMap_t::iterator it = TimerMap.begin(); it != TimerMap.end(); ++ it) {
+        it->second = 0;
+    }
+    TimerMap.clear();
+
+    TimerList.clear();
+}
 
 
 //////////////////////////////////////////////////////////////////////
 // create a timer, or get one that already exists
-IpplTimings::TimerRef IpplTimings::getTimer(const char *nm) {
-  std::string s(nm);
-  TimerInfo *tptr = 0;
-  TimerMap_t::iterator loc = TimerMap.find(s);
-  if (loc == TimerMap.end()) {
-    tptr = new TimerInfo;
-    tptr->indx = TimerList.size();
-    tptr->name = s;
-    TimerMap.insert(TimerMap_t::value_type(s,tptr));
-    TimerList.push_back(my_auto_ptr<TimerInfo>(tptr));
-  } else {
-    tptr = (*loc).second;
-  }
-  return tptr->indx;
+Timing::TimerRef Timing::getTimer(const char *nm) {
+    std::string s(nm);
+    TimerInfo *tptr = 0;
+    TimerMap_t::iterator loc = TimerMap.find(s);
+    if (loc == TimerMap.end()) {
+        tptr = new TimerInfo;
+        tptr->indx = TimerList.size();
+        tptr->name = s;
+        TimerMap.insert(TimerMap_t::value_type(s,tptr));
+        TimerList.push_back(my_auto_ptr<TimerInfo>(tptr));
+    } else {
+        tptr = (*loc).second;
+    }
+    return tptr->indx;
 }
 
 
 //////////////////////////////////////////////////////////////////////
 // start a timer
-void IpplTimings::startTimer(TimerRef t) {
-  if (t >= TimerList.size())
-    return;
-  TimerList[t]->start();
+void Timing::startTimer(TimerRef t) {
+    if (t >= TimerList.size())
+        return;
+    TimerList[t]->start();
 }
 
 
 //////////////////////////////////////////////////////////////////////
 // stop a timer, and accumulate it's values
-void IpplTimings::stopTimer(TimerRef t) {
+void Timing::stopTimer(TimerRef t) {
     if (t >= TimerList.size())
-    return;
-  TimerList[t]->stop();
+        return;
+    TimerList[t]->stop();
 }
 
 
 //////////////////////////////////////////////////////////////////////
 // clear a timer, by turning it off and throwing away its time
-void IpplTimings::clearTimer(TimerRef t) {
-  if (t >= TimerList.size())
-    return;
-  TimerList[t]->clear();
+void Timing::clearTimer(TimerRef t) {
+    if (t >= TimerList.size())
+        return;
+    TimerList[t]->clear();
 }
 
 #ifdef IPPL_XT3
 //////////////////////////////////////////////////////////////////////
 // print out the timing results
-void IpplTimings::print() {
+void Timing::print() {
     int i,j;
     if (TimerList.size() < 1)
 	return;
@@ -154,7 +164,7 @@ void IpplTimings::print() {
 
 //////////////////////////////////////////////////////////////////////
 // print out the timing results
-void IpplTimings::print() {
+void Timing::print() {
     if (TimerList.size() < 1)
         return;
 
@@ -218,7 +228,7 @@ void IpplTimings::print() {
 
 //////////////////////////////////////////////////////////////////////
 // save the timing results into a file
-void IpplTimings::print(std::string fn) {
+void Timing::print(const std::string &fn) {
 
     std::ofstream *timer_stream;
     Inform *msg;
@@ -229,7 +239,7 @@ void IpplTimings::print(std::string fn) {
     timer_stream = new std::ofstream;
     timer_stream->open( fn.c_str(), std::ios::out );
     msg = new Inform( 0, *timer_stream, 0 );
-
+    Inform gmsg("bla ");
     // report the average time for each timer
     // Inform msg("Timings");
     /*
@@ -279,7 +289,7 @@ void IpplTimings::print(std::string fn) {
          << std::setw(11) << "Wall avg\n"
          << std::string().assign(87,'=')
          << "\n";
-    for (unsigned int i=1; i < TimerList.size(); ++i) {
+    for (unsigned int i=0; i < TimerList.size(); ++i) {
         TimerInfo *tptr = TimerList[i].get();
         double wallmax = 0.0, cpumax = 0.0, wallmin = 0.0, cpumin = 0.0;
         double wallavg = 0.0, cpuavg = 0.0;
@@ -308,6 +318,23 @@ void IpplTimings::print(std::string fn) {
     delete timer_stream;
 }
 
+IpplTimings::IpplTimings() { }
+IpplTimings::~IpplTimings() { }
+
+void IpplTimings::stash() {
+    PAssert(stashedInstance.size() == 0);
+
+    stashedInstance.push(instance);
+    instance = new Timing();
+}
+
+void IpplTimings::pop() {
+    PAssert(stashedInstance.size() > 0);
+
+    delete instance;
+    instance = stashedInstance.top();
+    stashedInstance.pop();
+}
 
 /***************************************************************************
  * $RCSfile: IpplTimings.cpp,v $   $Author: adelmann $
diff --git a/ippl/src/Utility/IpplTimings.h b/ippl/src/Utility/IpplTimings.h
index 10f8ed2b1c50201560804a765411c5d12a4777fa..c4744a61cdb46f7f7ee3c3effe00475a7c259ba1 100644
--- a/ippl/src/Utility/IpplTimings.h
+++ b/ippl/src/Utility/IpplTimings.h
@@ -42,138 +42,192 @@
 #include <vector>
 #include <map>
 #include <limits>
-#include <string>
+#include <stack>
 
 #ifdef TIMERDEBUG
 #include <exception>
 #endif
+
 // a simple class used to store timer values
 class IpplTimerInfo
 {
 public:
-  // typedef for reference to a timer
-  typedef unsigned int TimerRef;
-
-  // constructor
-  IpplTimerInfo() : name(""), cpuTime(0.0), wallTime(0.0), indx(std::numeric_limits<TimerRef>::max()) {
-    clear();
-  }
-
-  // destructor
-  ~IpplTimerInfo() { }
-
-  // timer operations
-  void start() {
-    if (!running) {
-      running = true;
-      t.stop();
-      t.clear();
-      t.start();
+    // typedef for reference to a timer
+    typedef unsigned int TimerRef;
+
+    // constructor
+    IpplTimerInfo() : name(""), cpuTime(0.0), wallTime(0.0), indx(std::numeric_limits<TimerRef>::max()) {
+        clear();
     }
+
+    // destructor
+    ~IpplTimerInfo() { }
+
+    // timer operations
+    void start() {
+        if (!running) {
+            running = true;
+            t.stop();
+            t.clear();
+            t.start();
+        }
 #ifdef TIMERDEBUG
-    else {
-        throw std::runtime_error("Timer '" + name + "' already running");
-    }
+        else {
+            throw std::runtime_error("Timer '" + name + "' already running");
+        }
 #endif
-  }
-
-  void stop() {
-    if (running) {
-      t.stop();
-      running = false;
-      cpuTime += t.cpu_time();
-      wallTime += t.clock_time();
     }
+
+    void stop() {
+        if (running) {
+            t.stop();
+            running = false;
+            cpuTime += t.cpu_time();
+            wallTime += t.clock_time();
+        }
 #ifdef TIMERDEBUG
-    else {
-        throw std::runtime_error("Timer '" + name + "' already idling");
-    }
+        else {
+            throw std::runtime_error("Timer '" + name + "' already idling");
+        }
 #endif
-  }
+    }
 
-  void clear() {
-    t.stop();
-    t.clear();
-    running = false;
-  }
+    void clear() {
+        t.stop();
+        t.clear();
+        running = false;
+    }
 
-  // the IPPL timer that this object manages
-  Timer t;
+    // the IPPL timer that this object manages
+    Timer t;
 
-  // the name of this timer
-  std::string name;
+    // the name of this timer
+    std::string name;
 
-  // the accumulated time
-  double cpuTime;
-  double wallTime;
+    // the accumulated time
+    double cpuTime;
+    double wallTime;
 
-  // is the timer turned on right now?
-  bool running;
+    // is the timer turned on right now?
+    bool running;
 
-  // an index value for this timer
-  TimerRef indx;
+    // an index value for this timer
+    TimerRef indx;
 };
 
+struct Timing
+{
+    // typedef for reference to a timer
+    typedef unsigned int TimerRef;
 
+    // a typedef for the timer information object
+    typedef IpplTimerInfo TimerInfo;
 
-class IpplTimings
-{
-public:
-  // typedef for reference to a timer
-  typedef unsigned int TimerRef;
+    // Default constructor
+    Timing();
 
-  // a typedef for the timer information object
-  typedef IpplTimerInfo TimerInfo;
+    // Destructor - clear out the existing timers
+    ~Timing();
 
-public:
-  // Default constructor
-  IpplTimings();
+    // create a timer, or get one that already exists
+    TimerRef getTimer(const char *);
 
-  // Destructor - clear out the existing timers
-  ~IpplTimings();
+    // start a timer
+    void startTimer(TimerRef);
 
-  //
-  // timer manipulation methods
-  //
+    // stop a timer, and accumulate it's values
+    void stopTimer(TimerRef);
 
-  // create a timer, or get one that already exists
-  static TimerRef getTimer(const char *);
+    // clear a timer, by turning it off and throwing away its time
+    void clearTimer(TimerRef);
+
+    // return a TimerInfo struct by asking for the name
+    TimerInfo *infoTimer(const char *nm) {
+        return TimerMap[std::string(nm)];
+    }
 
-  // start a timer
-  static void startTimer(TimerRef);
+    // print the results to standard out
+    void print();
 
-  // stop a timer, and accumulate it's values
-  static void stopTimer(TimerRef);
+    // print the results to a file
+    void print(const std::string &fn);
 
-  // clear a timer, by turning it off and throwing away its time
-  static void clearTimer(TimerRef);
 
-  // return a TimerInfo struct by asking for the name
-  static TimerInfo *infoTimer(const char *nm) {
-    return TimerMap[std::string(nm)];
-  }
+    // type of storage for list of TimerInfo
+    typedef std::vector<my_auto_ptr<TimerInfo> > TimerList_t;
+    typedef std::map<std::string, TimerInfo *> TimerMap_t;
 
-  //
-  // I/O methods
-  //
+private:
+    // a list of timer info structs
+    TimerList_t TimerList;
 
-  // print the results to standard out
-  static void print();
+    // a map of timers, keyed by string
+    TimerMap_t TimerMap;
+};
 
-  // print the results to a file
-  static void print(std::string fn);
 
 
+class IpplTimings
+{
+public:
+    // typedef for reference to a timer
+    typedef Timing::TimerRef TimerRef;
+
+    // a typedef for the timer information object
+    typedef Timing::TimerInfo TimerInfo;
+
+    // create a timer, or get one that already exists
+    static TimerRef getTimer(const char * nm) {
+        return instance->getTimer(nm);
+    }
+
+    // start a timer
+    static void startTimer(TimerRef t) {
+        instance->startTimer(t);
+    }
+
+    // stop a timer, and accumulate it's values
+    static void stopTimer(TimerRef t) {
+        instance->stopTimer(t);
+    }
+
+    // clear a timer, by turning it off and throwing away its time
+    static void clearTimer(TimerRef t) {
+        instance->clearTimer(t);
+    }
+
+    // return a TimerInfo struct by asking for the name
+    static TimerInfo *infoTimer(const char *nm) {
+        return instance->infoTimer(nm);
+    }
+
+    // print the results to standard out
+    static void print() {
+        instance->print();
+    }
+
+    // print the results to a file
+    static void print(std::string fn) {
+        instance->print(fn);
+    }
+
+    static void stash();
+    static void pop();
+
 private:
-  // type of storage for list of TimerInfo
-  typedef std::vector<my_auto_ptr<TimerInfo> > TimerList_t;
-  typedef std::map<std::string, TimerInfo *> TimerMap_t;
+    // type of storage for list of TimerInfo
+    typedef Timing::TimerList_t TimerList_t;
+    typedef Timing::TimerMap_t TimerMap_t;
+
+    // Default constructor
+    IpplTimings();
+
+    // Destructor - clear out the existing timers
+    ~IpplTimings();
 
-  // a list of timer info structs
-  static TimerList_t TimerList;
 
-  // a map of timers, keyed by string
-  static TimerMap_t TimerMap;
+    static Timing *instance;
+    static std::stack<Timing*> stashedInstance;
 };
 
 #endif
diff --git a/ippl/test/6dtrack/GTChargedParticles/GTChargedParticles.hh b/ippl/test/6dtrack/GTChargedParticles/GTChargedParticles.hh
index 67bba31d8b1bfdae247a8cef638358333e070c48..9843aac79f2ee0f7d5166c3c3b3838dd5fbcfc48 100644
--- a/ippl/test/6dtrack/GTChargedParticles/GTChargedParticles.hh
+++ b/ippl/test/6dtrack/GTChargedParticles/GTChargedParticles.hh
@@ -14,7 +14,7 @@ typedef ParticleSpatialLayout<double, 6> playout_t;
 template<class PL>
 class ChargedParticles : public IpplParticleBase<PL> {
 
-  
+
   typedef UniformCartesian<6,double>               Mesh_t;
   typedef Cell                                     Center_t;
   typedef CenteredFieldLayout<6, Mesh_t, Center_t> FieldLayout_t;
@@ -31,7 +31,7 @@ class ChargedParticles : public IpplParticleBase<PL> {
 
 
  private:
-    
+
   Field_t  rho_m;
   BConds<double,6,Mesh_t,Center_t> bc_m;
 
@@ -46,7 +46,7 @@ class ChargedParticles : public IpplParticleBase<PL> {
   Vector3 rmean_m, pmean_m;
   Vector3 rrms_m, prms_m, eps_m, rprms_m;
   Vector3 csbeta_m,csgamma_m,csalpha_m;
-  
+
   // macroparticle charge in Cb
   double q_m;
   double spos_m;
@@ -58,7 +58,7 @@ class ChargedParticles : public IpplParticleBase<PL> {
 
 public:
 
-  // the attributes for this set of particles (atoms).  
+  // the attributes for this set of particles (atoms).
 
   ParticleAttrib< double > Q;
 
@@ -80,10 +80,10 @@ public:
 
     Vektor<int,6> nr(simCfg.nx,simCfg.ny,simCfg.nz,
 		     simCfg.nx,simCfg.ny,simCfg.nz);
-    
+
     for(int i=0; i<6; i++)
 	domain[i] = domain[i] = Index(nr[i] + 1);
-  
+
     for (int d=0; d < 6; ++d) {
 	if (d<4)
 	    decomp[d] = PARALLEL;
@@ -91,52 +91,52 @@ public:
 	    decomp[d] = SERIAL;
     }
     // create mesh and layout objects for this problem domain
-    
+
     mesh = new Mesh_t(domain);
     FL   = new FieldLayout_t(*mesh, decomp);
 
     initialize(new PL(*FL,*mesh));
-    
+
     // register our attributes with the base class
     addAttribute(Q);
-    
+
     for (int i=0; i < 2*6; ++i) {
 	bc_m[i] = new ZeroFace<double,6,Mesh_t,Center_t>(i);
 	getBConds()[i] = ParticleNoBCond;
     }
-    
+
     rho_m.initialize(getMesh(), getFieldLayout(), GuardCellSizes<6>(1), bc_m);
-    
+
     msg << " Field and domain construction done = " << domain << endl;
 
   }
-  
-  /** 
+
+  /**
    * Interpolates the charge in Q onto a grid rho_m
    * @param none
    * @return none
-   */  
+   */
   void scatterQ() {
-    rho_m = 0.0;                                  
-    Q.scatter(rho_m, this->R, IntrplNGP_t());                             
+    rho_m = 0.0;
+    Q.scatter(rho_m, this->R, IntrplNGP_t());
   }
-  
-  /** 
-   * Shows how to work with fields and validated the 
+
+  /**
+   * Shows how to work with fields and validated the
    * charge deposition method. Is used if FIELDCHEK
    * is defined
    * @param none
    * @return none
-   */  
+   */
     void checkScatteredQ() {
-      
+
       Inform m("checkScatteredQ ");
-    
+
       double s1Q = sum(Q);
       double s2Q = sum(rho_m);
       m << "s1Q= " << s1Q << " s2Q= " << s2Q << " delta= " << abs(s1Q-s2Q) << endl;
   }
-    
+
 
   double getLocalVolumes(Vector_t r) {
     double ret=0;
@@ -144,7 +144,7 @@ public:
     NDIndex<6> elem = getMesh().getCellContaining(r);
     if (lIdx.contains(elem)) {
       ret = getMesh().getCellVolume(elem);
-    }    
+    }
     return ret;
   }
 
@@ -155,18 +155,18 @@ public:
     NDIndex<6> elem = getMesh().getCellContaining(r);
     if (lIdx.contains(elem)) {
       ret = rho_m.localElement(elem);
-    }    
+    }
     return ret;
   }
 
 
 
 
-  /** 
+  /**
    * Calculats the local density at a given particle position r
-   * @param r position of the particle 
-   * @return local density in [Q m**-3] 
-   */  
+   * @param r position of the particle
+   * @return local density in [Q m**-3]
+   */
   double getLocalDensity(Vector_t r) {
     double den=0;
     NDIndex<6> lIdx = getFieldLayout().getLocalNDIndex();
@@ -175,16 +175,16 @@ public:
       double lDen = rho_m.localElement(elem);
       double lVol = getMesh().getCellVolume(elem);
       den = lDen/lVol;
-    }    
+    }
     return den;
   }
 
-  /** 
+  /**
    * Calculats the analytic local density at a given particle position r
-   * @param r position of the particle 
-   * @param p momentum of the particle 
-   * @return local density in [Q m**-3] 
-   */  
+   * @param r position of the particle
+   * @param p momentum of the particle
+   * @return local density in [Q m**-3]
+   */
   double getLocalDensityAnalytic(Vector_t r, Vector_t p) {
     Vector_t e = get_emit();
     Vector_t a = get_csalpha();
@@ -195,16 +195,16 @@ public:
 
     for(unsigned i = 0; i < 3; i++)
       rho(i) = 1 / (2 * Physics::pi * e(i)) * exp(- abs(1/(2 * e(i)) * (g(i) * r(i) * r(i) + 2 * a(i) * r(i) * p(i) + b(i) * p(i) * p(i))));
-    
+
     return rho(0) * rho(1) * rho(2);
   }
- /** 
+ /**
    * Prototypes implemented in GTChargedParticles.cpp
-   * 
-   * 
-   * 
-   */  
-  
+   *
+   *
+   *
+   */
+
   void openFiles(string baseFn, string title,bool restartMode);
   void closeFiles();
   void calcBeamParameters();
@@ -235,7 +235,7 @@ public:
     collided[i] = 1;
     collided[j] = 1;
   }
-  
+
   inline const Mesh_t& getMesh() const { return getLayout().getLayout().getMesh(); }
   inline       Mesh_t& getMesh() { return getLayout().getLayout().getMesh(); }
   inline const FieldLayout_t& getFieldLayout() const {
@@ -248,135 +248,135 @@ public:
   inline bool isRoot() { return Ippl::myNode()==0; }
 
   void boundp() {
-    
+
     bounds(R,rmin_m,rmax_m);
-    
+
     NDIndex<6> domain = getFieldLayout().getDomain();
     for(int i=0; i<6; i++)
       nr_m[i] = domain[i].length();
-    
+
     Vektor<double,6> len = (rmax_m - rmin_m);
-      
+
     for(int i=0; i<6; i++)
       hr_m[i]    = (len[i] / (nr_m[i]-1));
-      
+
     // rescale mesh
     getMesh().set_meshSpacing(&(hr_m[0]));
     getMesh().set_origin( rmin_m );
 
     //    BinaryRepartition(*this);
     update();
-    rho_m.initialize(getMesh(), getFieldLayout(), GuardCellSizes<6>(1), bc_m);                     
+    rho_m.initialize(getMesh(), getFieldLayout(), GuardCellSizes<6>(1), bc_m);
   }
 
- /** 
-   * 
-   * 
-   * 
+ /**
+   *
+   *
+   *
    * @return the macroparticle charge in Cb
-   */  
+   */
   inline double getMoment(int i, int j) {return moments_m[i][j];}
 
 
- /** 
-   * 
-   * 
-   * 
+ /**
+   *
+   *
+   *
    * @return the macroparticle charge in Cb
-   */  
+   */
   //void writePartSDDSHeader(string title, unsigned int N, double qTot);
 
 
- /** 
-   * 
-   * 
-   * 
+ /**
+   *
+   *
+   *
    * @return the macroparticle charge in Cb
-   */  
+   */
   inline double getQ()    { return q_m;}
-  
-  
-  /** 
-   * 
-   * 
-   * 
+
+
+  /**
+   *
+   *
+   *
    * @return the actual simulation time [s]
-   */    
+   */
   inline double getTime()  { return spos_m; }
-  
 
-  /** 
-   * 
-   * 
-   * 
+
+  /**
+   *
+   *
+   *
    * @return increment the simulation time [s]
-   */  
+   */
   inline void incTime(double tInc) { actTime_m += tInc;}
- 
 
-  /** 
-   * 
-   * 
-   * 
+
+  /**
+   *
+   *
+   *
    * @return the relativistic factor []
-   */  
+   */
   inline double getGamma() {return pdata_m.getGamma();}
 
 
-  /** 
-   * 
-   * 
-   * 
+  /**
+   *
+   *
+   *
    * @return beta v/c []
-   */  
+   */
   inline double getBeta()  {return pdata_m.getBeta();}
-  
-  
-  /** 
-   * 
-   * 
-   * 
+
+
+  /**
+   *
+   *
+   *
    * @return get the actual position along the design orbit [m]
-   */  
+   */
   inline double set_spos(double s) { spos_m = s; }
- 
-  /** 
-   * 
-   * 
-   * 
+
+  /**
+   *
+   *
+   *
    * @return get the actual position along the design orbit [m]
-   */  
+   */
   inline double get_spos() { return spos_m; }
 
 
 
-  /** 
-   * 
-   * 
-   * 
+  /**
+   *
+   *
+   *
    * @return get the total charge of the bunch [Cb]
-   */  
+   */
   inline double getQTot() { return getTotalNum()*q_m; }
 
 
 
-  /** 
+  /**
    *    * --------- max
    *    *     0/0
    *    * --------- *
    *
    * @return get the maximal (max) extent of the bunch [m]
-   */  
+   */
   inline Vector_t get_maxExtend() { return rmax_m; }
 
-  
-  /** 
+
+  /**
    *    * --------- *
    *    *     0/0
    *  min --------- *
    *
    * @return get the minimal (min) extent of the bunch [m]
-   */  
+   */
   inline Vector_t get_origin() { return rmin_m; }
 
 
@@ -389,7 +389,7 @@ public:
   inline Vector_t get_csbeta() const { return csbeta_m; }
   inline Vector_t get_csgamma() const { return csgamma_m; }
   inline Vector_t get_csalpha() const { return csalpha_m; }
- 
+
   inline Vector_t get_rmean() const { return rmean_m; }
   inline Vector_t get_pmean() const { return pmean_m; }
   inline Vector_t get_rrms() const { return rrms_m; }
@@ -405,27 +405,27 @@ public:
   void writeRestartInfo(string basename, unsigned turn);
 
   void getInbalance(string fn, bool first) {
-  
+
     unsigned long int locN = getLocalNum();
     unsigned long int idealN = getTotalNum()/Ippl::getNodes();
     ofstream of;
- 
-    /* 
+
+    /*
        Get the particle inbalance from all the nodes
     */
     double  *locBal  = (double*) malloc(Ippl::getNodes()*sizeof(double));
     double  *globBal = (double*) malloc(Ippl::getNodes()*sizeof(double));
-  
-    for(int i=0; i<Ippl::getNodes(); i++) 
+
+    for(int i=0; i<Ippl::getNodes(); i++)
       locBal[i]=globBal[i]=0.0;
-  
+
     locBal[Ippl::myNode()] = locN;
-    
+
     reduce(locBal, locBal + Ippl::getNodes(), globBal, OpAddAssign());
-    
+
     if (first && isRoot()) {
       of.open(fn.c_str(),ios::out);
-      of << "# inbalance N_i, i=1.." << Ippl::getNodes() << " and Ntotal " << endl;  
+      of << "# inbalance N_i, i=1.." << Ippl::getNodes() << " and Ntotal " << endl;
       for(int i=0; i<Ippl::getNodes(); i++)
 	of << globBal[i] << "\t";
       of << getTotalNum() << endl;
@@ -445,4 +445,4 @@ public:
   }
 };
 #include "GTChargedParticles.cpp"
-#endif
+#endif
\ No newline at end of file
diff --git a/ippl/test/AMR/AmrPartBunch.h b/ippl/test/AMR/AmrPartBunch.h
index 53c76b0ea03f1f12976679224b3f6b6e89724ee2..75860b71b064837aaa01d16502206c4f7940dbbb 100644
--- a/ippl/test/AMR/AmrPartBunch.h
+++ b/ippl/test/AMR/AmrPartBunch.h
@@ -32,84 +32,83 @@ class AmrPartBunch : public PartBunchBase,
 {
 public:
     typedef std::map<int, std::tuple<int, int, int> > map_t;
-    
+
     static size_t nAttributes;
 
 public:
-    
+
     /// Just calls constructor of ParticleContainer
     AmrPartBunch(const Geometry & geom, const DistributionMapping & dmap,
                  const BoxArray & ba);
-    
+
     /// Just calls constructor of ParticleContainer
     AmrPartBunch(const Array<Geometry>& geom,
                  const Array<DistributionMapping>& dmap,
                  const Array<BoxArray>& ba,
                  const Array<int>& rr);
-                 
-    
+
+
     /// Does nothing.
     virtual ~AmrPartBunch();
-    
+
     // ------------------------------------------------------------------------
     // INHERITED MEMBER FUNCTIONS
     // ------------------------------------------------------------------------
-    
+
     void myUpdate();
-    
+
     void create(size_t m);
-    
+
     void gatherStatistics();
-    
+
     size_t getLocalNum() const;
-    
+
     size_t getTotalNum() const;
-    
+
     ///@todo Implement
     Vector_t getRMin();
-    
+
     ///@todo Implement
     Vector_t getRMax();
-    
+
     ///@todo Implement
     Vector_t getHr();
-    
+
     ///@todo Implement
     double scatter();
-    
+
     ///@todo Implement
     void initFields();
-    
+
     ///@todo Implement
     void gatherCIC();
-    
-    inline Vector_t getR(int i);
-    
-    inline double getQM(int i);
-    
-    inline Vector_t getP(int i);
-    
-    inline Vector_t getE(int i);
-    
-    inline Vector_t getB(int i);
-    
-    inline void setR(Vector_t pos, int i);
-    
-    inline void setQM(double q, int i);
-    
-    inline void setP(Vector_t v, int i);
-    
-    inline void setE(Vector_t Ef, int i);
-    
-    inline void setB(Vector_t Bf, int i);
-    
-    
+
+    Vector_t getR(int i);
+
+    double getQM(int i);
+
+    Vector_t getP(int i);
+
+    Vector_t getE(int i);
+
+    Vector_t getB(int i);
+
+    void setR(Vector_t pos, int i);
+
+    void setQM(double q, int i);
+
+    void setP(Vector_t v, int i);
+
+    void setE(Vector_t Ef, int i);
+
+    void setB(Vector_t Bf, int i);
+
     void destroyAll() {
         for (std::size_t i = 0; i < m_particles.size(); ++i)
             this->RemoveParticlesAtLevel(i);
         nLocalParticles_m = 0;
     }
-    
+
 //     void setParGDB(AmrParGDB* gdb) {
 //         Define(gdb);
 //     }
@@ -120,9 +119,9 @@ public:
         for (int i = 0; i < Ippl::getNodes(); ++i) {
             if ( i == Ippl::myNode() ) {
                 wm = (i == 0) ? wm : Inform::APPEND;
-                
+
                 const ParGDBBase* gdb = GetParGDB();
-                
+
                 std::string grid_file = "pyplot_grids_" + st + ".dat";
                 Inform msg("", grid_file.c_str(), wm, i);
                 for (int l = 0; l < gdb->finestLevel() + 1; ++l) {
@@ -135,14 +134,14 @@ public:
                         msg << endl;
                     }
                 }
-                
+
                 std::string particle_file = "pyplot_particles_" + st + ".dat";
                 Inform msg2all("", particle_file.c_str(), wm, i);
                 int l, g, dq;
                 for (size_t i = 0; i < this->getLocalNum(); ++i) {
-                    
+
                     std::tie(l,g,dq) = idxMap_m[i];
-                    
+
                     msg2all << m_particles[l][g][dq].m_pos[0] << " "
                             << m_particles[l][g][dq].m_pos[1] << " "
                             << m_particles[l][g][dq].m_pos[2]
@@ -152,20 +151,20 @@ public:
             Ippl::Comm->barrier();
         }
     }
-    
+
     int getLevel(int i) {
         int l, g, dq;
         std::tie(l,g,dq) = idxMap_m[i];
         return l;
     }
-    
+
     Vector_t interpolate(int i, MultiFab& quantity) {
-        
+
         int lev, grid, dq;
         std::tie(lev, grid, dq) = idxMap_m[i];
-        
+
         const Real strttime  = ParallelDescriptor::second();
-        
+
         MultiFab* ac_pointer;
         if (OnSameGrids(lev,quantity)) {
             ac_pointer = &quantity;
@@ -177,10 +176,10 @@ public:
             ac_pointer->copy(quantity,0,0,quantity.nComp());
             ac_pointer->FillBoundary(); // DO WE NEED GHOST CELLS FILLED ???
         }
-        
+
         const FArrayBox& gfab = (*ac_pointer)[grid];
         Real grav[3] = { 0.0, 0.0, 0.0 };
-        
+
         int idx[3] = { 0, 1, 2 };
 
     ParticleBase::Interp(m_particles[lev][grid][dq],
@@ -189,16 +188,16 @@ public:
                          idx,
                          grav,
                          BL_SPACEDIM);
-        
+
         return Vector_t(grav[0], grav[1], grav[2]);
     }
-    
+
 private:
     /// Create the index mapping in order to have random access
     void buildIndexMapping_m();
-    
+
     int nLocalParticles_m;
-    
+
 private:
     /* Mapping for
      * index --> (level, grid, deque length)
diff --git a/ippl/test/AMR/Distribution.h b/ippl/test/AMR/Distribution.h
index f847196881ac4a9b881b89a89a2ea8adc776ae19..eb290611fe6bef075baf9bb687b0ff1fab964eb2 100644
--- a/ippl/test/AMR/Distribution.h
+++ b/ippl/test/AMR/Distribution.h
@@ -22,15 +22,15 @@
 
 /// Create particle distributions
 class Distribution {
-    
+
 public:
     typedef std::vector<double> container_t;
-    
-    
+
+
 public:
-    
+
     Distribution();
-    
+
     /// Generate an uniform particle distribution
     /*!
      * @param lower boundary
@@ -39,7 +39,7 @@ public:
      * @param seed of the Mersenne-Twister
      */
     void uniform(double lower, double upper, size_t nloc, int seed);
-    
+
     /// Generate a Gaussian particle distribution
     /*!
      * @param mean also called centroid
@@ -48,14 +48,14 @@ public:
      * @param seed of the Mersenne-Twister
      */
     void gaussian(double mean, double stddev, size_t nloc, int seed);
-    
+
     /// Read in a distribution from an H5 file
     /*!
      * @param filename is the path and name of the H5 file.
      * @param step to be read in.
      */
     void readH5(const std::string& filename, int step);
-    
+
     /// Transfer distribution to particle bunch object.
     /*! @param bunch is either an AmrPartBunch or an PartBunch object
      * @param doDelete removes all particles already in bunch before
@@ -63,32 +63,32 @@ public:
      * @param shift all particles, each direction independently
      */
     void injectBeam(PartBunchBase& bunch, bool doDelete = true, std::array<double, 3> shift = {{0.0, 0.0, 0.0}});
-    
+
     /// Update a distribution (only single-core)
     /*! @param bunch is either an AmrPartBunch or an PartBunch object
      * @param filename is the path and name of the H5 file
      * @param step to be read in from a H5 file
      */
     void setDistribution(PartBunchBase& bunch, const std::string& filename, int step);
-    
+
     /// Write the particles to a text file that can be read by OPAL. (sec. 11.3 in OPAL manual)
     /*!
      * @param pathname where to store.
      */
     void print2file(std::string pathname);
-    
+
 private:
     container_t x_m;    ///< Horizontal particle positions [m]
     container_t y_m;    ///< Vertical particle positions [m]
     container_t z_m;    ///< Longitudinal particle positions [m]
-    
+
     container_t px_m;   ///< Horizontal particle momentum
     container_t py_m;   ///< Vertical particle momentum
     container_t pz_m;   ///< Longitudinal particle momentum
     container_t q_m;    ///< Particle charge (always set to 1.0, except for Distribution::readH5)
-    
+
     size_t nloc_m;      ///< Local number of particles
     size_t ntot_m;      ///< Total number of particles
 };
 
-#endif
+#endif
\ No newline at end of file
diff --git a/ippl/test/AMR/PartBunch.h b/ippl/test/AMR/PartBunch.h
index b5d79ed89b55be8411c6f6b55c8ecceace6eb0a8..4353abf9e32cc1137d9f8048605abf79efe12dc7 100644
--- a/ippl/test/AMR/PartBunch.h
+++ b/ippl/test/AMR/PartBunch.h
@@ -23,32 +23,32 @@ class PartBunch : public IpplParticleBase<PL>,
                   public PartBunchBase
 {
 private:
-    
+
     Field<Vektor<double,Dim>,Dim> EFD_m;
     Field<double,Dim> EFDMag_m;
-    
+
     // Boundary conditions (all periodic)
     BConds<double,Dim,Mesh_t,Center_t> bc_m;
     BConds<Vector_t,Dim,Mesh_t,Center_t> vbc_m;
-    
+
     Vektor<int,Dim> nr_m;           ///< Number of grid points in each direction (nx, ny, nz)
-    
+
     bool fieldNotInitialized_m;     ///< Check in case of myUpdate() if field is initialized
-    
+
     e_dim_tag decomp_m[Dim];
-    
+
     Vector_t hr_m;                  ///< Mesh spacing
     Vector_t rmin_m;                ///< Lower corner of domain
     Vector_t rmax_m;                ///< Upper corner of domain
-    
-    
+
+
     ParticleAttrib<double>     qm; ///< charge-to-mass ratio
     typename PL::ParticlePos_t P;  ///< particle velocity
     typename PL::ParticlePos_t E;  ///< electric field at particle position
     typename PL::ParticlePos_t B;  ///< magnetic field at particle position
-    
+
 public:
-    
+
     /*!
      * @param pl is the particle layout (defines the distribution mapping)
      * @param hr is the mesh spacing
@@ -57,8 +57,8 @@ public:
      */
     PartBunch(PL* pl, Vector_t hr, Vector_t rmin,
               Vector_t rmax, e_dim_tag decomp[Dim]);
-    
-    
+
+
     inline const Mesh_t& getMesh() const;
 
     /*!
@@ -66,45 +66,45 @@ public:
      * decomposition
      */
     inline Mesh_t& getMesh();
-    
+
     /*!
      * @return the layout of the field.
      */
     inline FieldLayout_t& getFieldLayout();
-    
+
     void savePhaseSpace(std::string fn, int idx);
-    
+
     inline void gatherCIC();
-    
+
     // ------------------------------------------------------------------------
     // INHERITED MEMBER FUNCTIONS
     // ------------------------------------------------------------------------
     inline void create(size_t m);
-    
+
     inline size_t getLocalNum() const;
-    
+
     inline size_t getTotalNum() const;
-    
+
     inline Vector_t getR(int i);
-    
+
     inline double getQM(int i);
-    
+
     inline Vector_t getP(int i);
-    
+
     inline Vector_t getE(int i);
-    
+
     inline Vector_t getB(int i);
-    
+
     inline void setR(Vector_t pos, int i);
-    
+
     inline void setQM(double q, int i);
-    
+
     inline void setP(Vector_t v, int i);
-    
+
     inline void setE(Vector_t Ef, int i);
-    
+
     inline void setB(Vector_t Bf, int i);
-    
+
     double scatter();
 
     void myUpdate();
@@ -116,16 +116,16 @@ public:
     inline Vector_t getRMin();
     inline Vector_t getRMax();
     inline Vector_t getHr();
-    
-    
+
+
     void destroyAll() {
-        
+
     }
-    
+
 private:
 
     inline void setBCAllPeriodic_m();
-    
+
     inline void scatterCIC_m();
 };
 
@@ -151,9 +151,9 @@ PartBunch<PL>::PartBunch(PL* pl, Vector_t hr, Vector_t rmin,
     this->addAttribute(P);
     this->addAttribute(E);
     this->addAttribute(B);
-    
+
     setBCAllPeriodic_m();
-    
+
     for (unsigned int i = 0; i < Dim; ++i)
         decomp_m[i] = decomp[i];
 }
@@ -372,9 +372,9 @@ template <class PL>
 double PartBunch<PL>::scatter() {
     Inform m("scatter ");
     double initialQ = sum(qm);
-    
+
     scatterCIC_m();
-    
+
     Field<double,Dim> tmpf;
     NDIndex<Dim> domain = getFieldLayout().getDomain();
 
@@ -398,7 +398,7 @@ double PartBunch<PL>::scatter() {
             }
         }
     }
-    
+
     reduce(Q,Q,OpAddAssign());
     m << "sum(qm)= " << initialQ << " sum(EFDMag)= " << sum(EFDMag_m) << endl;
     return initialQ-Q;
@@ -411,11 +411,11 @@ void PartBunch<PL>::myUpdate() {
         fieldNotInitialized_m=false;
         getMesh().set_meshSpacing(&(hr_m[0]));
         getMesh().set_origin(rmin_m);
-            
+
         EFD_m.initialize(getMesh(), getFieldLayout(), GuardCellSizes<Dim>(1), vbc_m);
         EFDMag_m.initialize(getMesh(), getFieldLayout(), GuardCellSizes<Dim>(1), bc_m);
     }
-    
+
     this->update();
 }
 
@@ -427,14 +427,14 @@ void PartBunch<PL>::gatherStatistics() {
 
     double *partPerNode = new double[Ippl::getNodes()];
     double *globalPartPerNode = new double[Ippl::getNodes()];
-    
+
     for (int i=0; i<Ippl::getNodes(); i++)
         partPerNode[i] = globalPartPerNode[i] = 0.0;
-    
+
     partPerNode[Ippl::myNode()] = this->getLocalNum();
-    
+
     reduce(partPerNode,partPerNode+Ippl::getNodes(),globalPartPerNode,OpAddAssign());
-    
+
     for (int i = 0; i < Ippl::getNodes(); ++i)
         m << "Node " << i << " has "
           <<   globalPartPerNode[i]/this->getTotalNum()*100.0 << " \% of the total particles " << endl;
@@ -455,13 +455,13 @@ void PartBunch<PL>::initFields() {
     int nz = nr_m[2];
 
     double phi0 = 0.1*nx;
-    
+
     m << "rmin= " << rmin_m << " rmax= " << rmax_m << " h= " << hr_m << " n= " << nr_m << endl;
 
     Index I(nx), J(ny), K(nz);
-    
+
     assign(EFD_m[I][J][K](0), -2.0*pi*phi0/nx * cos(2.0*pi*(I+0.5)/nx) * cos(4.0*pi*(J+0.5)/ny) * cos(pi*(K+0.5)/nz));
-    
+
     assign(EFD_m[I][J][K](1),  4.0*pi*phi0/ny * sin(2.0*pi*(I+0.5)/nx) * sin(4.0*pi*(J+0.5)/ny));
 
     assign(EFD_m[I][J][K](2),  4.0*pi*phi0/ny * sin(2.0*pi*(I+0.5)/nx) * sin(4.0*pi*(J+0.5)/ny));
diff --git a/ippl/test/AMR/PartBunchBase.h b/ippl/test/AMR/PartBunchBase.h
index 6106c3bdb675b94191d23ae20fa3a7c527df018f..3bfe9c8f1dcac824bb13c2fc46ff8f7c82b82e27 100644
--- a/ippl/test/AMR/PartBunchBase.h
+++ b/ippl/test/AMR/PartBunchBase.h
@@ -25,7 +25,7 @@ const double pi = acos(-1.0);
  * @details In order to work properly with OPAL it has
  * to provide the functionalities of the
  * ippl/src/Particle/IpplParticleBase
- * and classic/src/Algorithms/PartBunch class.
+ * and src/Classic/Algorithms/PartBunch class.
  * @authors Matthias Frey \n
  *          Andreas Adelmann \n
  *          Ann Almgren \n
@@ -39,133 +39,133 @@ const double pi = acos(-1.0);
 class PartBunchBase {
 
 public:
-    
+
     /// Does nothing.
     virtual ~PartBunchBase() {}
-    
-    
+
+
     /// After tracking the particle need to be redistributed to guarantee load balancing
     virtual void myUpdate() = 0;
-    
+
     /// Each processor creates m particles (see IpplParticleBase)
     /*! @param m is the number of particles to be created.
      */
     virtual void create(size_t m) = 0;
-    
+
     /// Local number of particles (see IpplParticleBase)
     /*! @returns the local number of particles
      */
     virtual size_t getLocalNum() const = 0;
-    
+
     /// Total number of particles (see IpplParticleBase)
     /*! @returns the total number of particles
      */
     virtual size_t getTotalNum() const = 0;
-    
+
     // Load balancing statistics
     /*!
      * Obtain load balancing information and print
      * it to the shell.
      */
     virtual void gatherStatistics() = 0;
-    
+
     /// Lower corner of domain.
     /*! @returns the lower corner of the box domain.
      */
     virtual Vector_t getRMin() = 0;
-    
+
     /// Upper corner of domain.
     /*! @returns the upper corner of the box domain.
      */
     virtual Vector_t getRMax() = 0;
-    
+
     /// Mesh spacing
     /*! @returns the mesh spacing.
      */
     virtual Vector_t getHr() = 0;
-    
+
     /// Access the position of a particle
     /*! @returns the i-th particle position (x, y, z)
      */
     virtual Vector_t getR(int i) = 0;
-    
+
     /// Access the charge-to-mass ratio of a particle
     /*! @returns the charge-to-mass ratio of the i-th particle
      */
     virtual double getQM(int i) = 0;
-    
+
     /// Access the velocity of a particle
     /*! @returns the i-th particle velocity (px, py, pz)
      */
     virtual Vector_t getP(int i) = 0;
-    
+
     /// Access the electric field at the particle location
     /*! @returns (Ex, Ey, Ez) at i-th particle location
      */
     virtual Vector_t getE(int i) = 0;
-    
+
     /// Access the magnetic field a the particle location
     /*! @returns (Bx, By, Bz) at i-th particle location
      */
     virtual Vector_t getB(int i) = 0;
-    
+
     /// Set the particle position
     /*!
      * @param pos is the position (x, y, z)
      * @param i specifies the i-th particle
      */
     virtual void setR(Vector_t pos, int i) = 0;
-    
+
     /// Set the particle charge-to-mass ratio
     /*!
      * @param q is the new charge-to-mass ratio
      * @param i specifies the i-th particle
      */
     virtual void setQM(double q, int i) = 0;
-    
+
     /// Set the particle velocity
     /*!
      * @param v is the velocity (vx, vy, vz)
      * @param i specifies the i-th particle
      */
     virtual void setP(Vector_t v, int i) = 0;
-    
+
     /// Set the E-field
     /*!
      * @param Ef is the electric field (Ex, Ey, Ez)
      * @param i specifies the i-th particle
      */
     virtual void setE(Vector_t Ef, int i) = 0;
-    
+
     /// Set the particle position
     /*!
      * @param Bf is the magnetic field (Bx, By, Bz)
      * @param i specifies the i-th particle
      */
     virtual void setB(Vector_t Bf, int i) = 0;
-    
+
     virtual double scatter() = 0;
     virtual void initFields() = 0;
     virtual void gatherCIC() = 0;
-    
+
     /// Writes the particles (x, y, z) to the shell.
-    inline void print();
-    
+    void print();
+
     /// Delete all particles and free allocated memory
     virtual void destroyAll() = 0;
 };
 
 
-
+inline
 void PartBunchBase::print() {
     for (int p = 0; p < Ippl::getNodes(); ++p) {
-        
+
         if ( p == Ippl::myNode() )
             for (size_t i = 0; i < getLocalNum(); ++i) {
                 std::cout << std::setprecision(8) << getR(i)(0) << " "
                           << getR(i)(1) << " " << getR(i)(2) << std::endl;
             }
-        
+
         Ippl::Comm->barrier();
     }
 }
diff --git a/ippl/test/AMR/README b/ippl/test/AMR/README
index a31227a1f728910a51848264671d05c097e8385d..a3c9b82dff299c15a892c1f929d345617c369075 100644
--- a/ippl/test/AMR/README
+++ b/ippl/test/AMR/README
@@ -32,14 +32,14 @@ b) follow instructions of website
 c) in order to run you add following line either to your
    .bashrc file or you execute it everytime you want to start
    a new session in a new terminal
-   
+
    source $YT_DIR/yt-x86_64/bin/activate
-    
+
 d) just run the script with python
-   
+
    $ python visualize.py
-   
-   
+
+
 The following programs are in this directory:
     - testAmrPartBunch:     OPAL - BoxLib - Particle - Marriage example
     - testSolver:           Solving \Lap\phi = -1 using FMultiGrid solver of BoxLib
diff --git a/ippl/test/AMR/Solver.h b/ippl/test/AMR/Solver.h
index 7d9ec8afe0e0c0c9f7a90f4af7278c3a224d005c..5c86d244e3fffae9fc872a5e2f5f37160524ac71 100644
--- a/ippl/test/AMR/Solver.h
+++ b/ippl/test/AMR/Solver.h
@@ -14,6 +14,7 @@
 #include <VisMF.H>
 #include <FMultiGrid.H>
 
+
 #include <memory>
 #include <vector>
 
@@ -50,7 +51,7 @@ public:
     typedef PArray<MultiFab> container_t;
 #endif
     typedef Array<MultiFab*> container_pt;      // instead of PArray<MultiFab>
-    
+
     /*!
      * Prepares the solver and calls the solve_with_f90 function.
      * @param rhs is the density at each level (cell-centered)
@@ -68,7 +69,8 @@ public:
                          int base_level,
                          int finest_level,
                          Real offset);
-    
+
+
     /*!
      * Actual solve.
      * @param rhs is the density at each level (cell-centered)
@@ -81,18 +83,18 @@ public:
      * @param abs_tol is \f$ 10^{-14}\f$ (specified in solve_for_accel)
      */
     void solve_with_f90(container_t& rhs,
-                        container_t& phi, Array< container_t >& grad_phi_edge, 
+                        container_t& phi, Array< container_t >& grad_phi_edge,
                         const Array<Geometry>& geom, int base_level, int finest_level, Real tol, Real abs_tol);
-    
+
 #ifdef USEHYPRE
     void solve_with_hypre(MultiFab& soln, MultiFab& rhs, const BoxArray& bs,
                           const Geometry& geom);
-    
+
 private:
     void set_boundary(BndryData& bd, const MultiFab& rhs, int comp);
-    
+
 #endif
 };
 
 
-#endif
+#endif
\ No newline at end of file
diff --git a/ippl/test/CavityTrack/ChargedParticles/ChargedParticles.hh b/ippl/test/CavityTrack/ChargedParticles/ChargedParticles.hh
index aa56b13509760b057d6d2b56438accd24c465da8..dd6fbdf861c835f1bfc0fc22298a906a42962df1 100644
--- a/ippl/test/CavityTrack/ChargedParticles/ChargedParticles.hh
+++ b/ippl/test/CavityTrack/ChargedParticles/ChargedParticles.hh
@@ -75,53 +75,53 @@
 
 template <class T, unsigned int Dim>
 class ChargedParticles : public IpplParticleBase< ParticleSpatialLayout<T,Dim> > {
-  
+
 private:
-    
+
     T coupling_m;
 
     unsigned long N0_m;
-    double current_m;    
+    double current_m;
 
     unsigned int numberOfClones;
 
 public:
-    
-    typedef IntCIC IntrplCIC_t; 
+
+    typedef IntCIC IntrplCIC_t;
     typedef IntNGP IntrplNGP_t;
-    
+
     typedef typename ParticleSpatialLayout<T,Dim>::ParticlePos_t Ppos_t;
     typedef typename ParticleSpatialLayout<T,Dim>::ParticleIndex_t PID_t;
-    
+
     typedef UniformCartesian<Dim,T> Mesh_t;
-    
+
     typedef typename ParticleSpatialLayout<T,Dim>::SingleParticlePos_t Vector_t;
-    
+
     typedef ParticleSpatialLayout<T, Dim, Mesh_t>      Layout_t;
-  
+
     typedef Cell                                       Center_t;
-    
+
     typedef CenteredFieldLayout<Dim, Mesh_t, Center_t> FieldLayout_t;
     typedef Field<T, Dim, Mesh_t, Center_t>            Field_t;
     typedef Field<Vector_t, Dim, Mesh_t, Center_t>     VField_t;
-    
+
     ParticleAttrib<T>          q_m; // charge (=mass if gravity)
     ParticleAttrib<T>          mass_m; //  mass
     ParticleAttrib<T>          h; // stepsize
     ParticleAttrib<T>          Ti;
     ParticleAttrib<T>          tact; // actual time
-    ParticleAttrib<Vector_t>   P;    // particle velocity 
+    ParticleAttrib<Vector_t>   P;    // particle velocity
     ParticleAttrib<Vector_t>   Ef;   // electric field at particle position
     ParticleAttrib<int>        bunchNo; // which bunch am  I
 
     Vector_t rmin_m, rmax_m;
     Vector_t CenterOfMass_m;
-    
+
     inline T getq() { return q_m[0]; }
     inline T getmass() { return mass_m[0]; }
-    
+
 /** Clone business
-    
+
 */
 
     Vector_t MeanR_m[MAXCLONE];
@@ -134,21 +134,21 @@ public:
 
     unsigned long int locNum_m[MAXCLONE];
     unsigned long int totNum_m[MAXCLONE];
-    
+
 
     inline void setNumOfClones(unsigned int nc) {numberOfClones=nc;}
     inline unsigned int getNumOfClones() {return numberOfClones;}
-    
-    inline Vector_t getMeanR() { 
+
+    inline Vector_t getMeanR() {
         /** assume all clones have the same number of particles
             and they are equal the number of particles of the mother bunch
         */
         double den = 1.0/(getTotalNum()/(numberOfClones+1));
-  
-        for (int j=0; j<MAXCLONE; j++) 
+
+        for (int j=0; j<MAXCLONE; j++)
             MeanR_loc[j] = MeanR_m[j] = 0.0;
-        
-        for (unsigned long int i=0; i<getLocalNum(); i++) 
+
+        for (unsigned long int i=0; i<getLocalNum(); i++)
             MeanR_loc[bunchNo[i]] += R[i]*den;
         reduce(MeanR_loc, MeanR_loc + MAXCLONE, MeanR_m, OpAddAssign());
         return MeanR_m[0];
@@ -156,16 +156,16 @@ public:
     /** assume a previous call to  getMeanR() */
     inline Vector_t getMeanR(int k) { return MeanR_m[k]; }
 
-    inline Vector_t getMeanP() { 
+    inline Vector_t getMeanP() {
         /** assume all clones have the same number of particles
             and they are equal the number of particles of the mother bunch
         */
         double den = 1.0/(getTotalNum()/(numberOfClones+1));
-  
-        for (int j=0; j<MAXCLONE; j++) 
+
+        for (int j=0; j<MAXCLONE; j++)
             MeanP_loc[j] = MeanP_m[j] = 0.0;
-        
-        for (unsigned long int i=0; i<getLocalNum(); i++) 
+
+        for (unsigned long int i=0; i<getLocalNum(); i++)
             MeanP_loc[bunchNo[i]] += P[i]*den;
         reduce(MeanP_loc, MeanP_loc + MAXCLONE, MeanP_m, OpAddAssign());
         return MeanP_m[0];
@@ -181,42 +181,42 @@ public:
         }
     }
 
-    inline T getGamma(int k) { 
+    inline T getGamma(int k) {
         return gamma_m[k];
     }
 
-    inline T getGamma() { 
+    inline T getGamma() {
         return gamma_m[0];
     }
-    
-    inline T getBeta() { 
+
+    inline T getBeta() {
         return sqrt(1.0-(1.0/(gamma_m[0]*gamma_m[0])));
     }
 
-    void updateBunches() {        
-        /** 
+    void updateBunches() {
+        /**
             Must be done after each integration step
             in consequence all getXXX(k) are valid
         */
-        
+
         Vector_t cm = getMeanP();
         Vector_t cv = getMeanR();
         compGamma();
-        
-        for (unsigned long int i=0; i<MAXCLONE ; i++) 
+
+        for (unsigned long int i=0; i<MAXCLONE ; i++)
             locNum_m[i] = totNum_m[i] = 0;
-        
+
         if (getNumOfClones()==0) {
             locNum_m[0]=getLocalNum();
             totNum_m[0]=getTotalNum();
         }
         else {
-            for (unsigned long int i=0; i<getLocalNum(); i++) 
+            for (unsigned long int i=0; i<getLocalNum(); i++)
                 locNum_m[bunchNo[i]]++;
             reduce(locNum_m,locNum_m+MAXCLONE,totNum_m,OpAddAssign());
         }
     }
-    
+
 
     inline unsigned long int getLocalnum(unsigned int clone) {return locNum_m[clone];}
     inline unsigned long int getTotalnum(unsigned int clone) {return totNum_m[clone];}
@@ -224,7 +224,7 @@ public:
     inline T getTime(int clone) {
         unsigned nPartLoc = 0;
         double ti = 0.0;
-        
+
         for (unsigned k=0; k<getLocalNum(); k++) {
             if (bunchNo[k] == clone) {
                 nPartLoc++;
@@ -233,15 +233,15 @@ public:
         }
         return ti/nPartLoc;
     }
-    
+
     inline void setTime(int clone, double t) {
-        for (unsigned k=0; k<getLocalNum(); k++) 
+        for (unsigned k=0; k<getLocalNum(); k++)
             if (bunchNo[k] == clone)
                 Ti[k] = t;
     }
-    
+
     inline Vector_t getCenterOfMass() { return CenterOfMass_m; }
-    
+
     inline Vector_t getGridSize() { return nr_m; }
     inline Vector_t getMeshSpacing() { return hr_m; }
 
@@ -249,12 +249,12 @@ public:
     inline Vector_t getRmax() { return rmax_m; }
 
     inline void setCurrent(double I) { current_m = I; }
-    inline double getCurrent() { return  current_m; }    
+    inline double getCurrent() { return  current_m; }
 
     inline void setN0() {N0_m = getTotalNum();}
     inline void setN0(unsigned long n) {N0_m = n;}
     inline unsigned long getN0() {return N0_m;}
-    
+
     inline bool isRoot() { return (Ippl::Comm->myNode() == 0); }
 
 
@@ -270,16 +270,16 @@ public:
         else
             return  CLIGHT*beta;
     }
-    
+
     inline double cu2mks(double p) {
-        double gamma2 = pow(p,2) + 1.0;     
+        double gamma2 = pow(p,2) + 1.0;
         double beta = sqrt(1.0 - (1.0/gamma2));
         if (p<0.0)
             return  -1.0*CLIGHT*beta;
         else
             return  CLIGHT*beta;
     }
-    
+
     inline double mks2mcu(double p) {
         double beta = p/CLIGHT;
         double gamma2 = 1.0 / (1.0 - (beta*beta));
@@ -288,40 +288,40 @@ public:
         else
             return  1.0e3*sqrt(gamma2-1.0);
     }
-    
+
 
     // Grid stuff
     Field_t  rho_m;                       // charge density/electric potential
     VField_t  eg_m;                       // electric field on grid
-    
+
     BCT bcType_m;                        // type of BC
-   
+
     Vector_t hr_m;
     Vektor<int,Dim> nr_m;
-    
+
     T act_s;
     T act_phi;
     T frequ_m;
-    
+
     BConds<T,Dim,Mesh_t,Center_t> bc_m;
     BConds<Vector_t,Dim,Mesh_t,Center_t> vbc_m;
-  
+
     
 
-    
+
     inline T   getFrequ() { return frequ_m; }
     inline void setFrequ(T f) { frequ_m = f; }
-    
+
     string getTitle() { return string("pcyclint"); }
-    
+
       
     //constructor
-    ChargedParticles(Layout_t *playout, BCT bc) : 
+    ChargedParticles(Layout_t *playout, BCT bc) :
             IpplParticleBase< ParticleSpatialLayout<T,Dim> >(playout),
             bcType_m(bc),
             numberOfClones(0)
         {
-        
+
         // register the particle attributes
         addAttribute(q_m);
         addAttribute(P);
@@ -330,7 +330,7 @@ public:
         addAttribute(h);
         addAttribute(Ti);
         addAttribute(tact);
-        addAttribute(bunchNo); 
+        addAttribute(bunchNo);
 
         if (bcType_m == PPP) {
             setBCAllPeriodic();
@@ -358,9 +358,9 @@ public:
 	R  = Vector_t(0.0);
     }
 
-    inline const Mesh_t& getMesh() const { 
+    inline const Mesh_t& getMesh() const {
         return getLayout().getLayout().getMesh(); }
-    inline Mesh_t& getMesh() { 
+    inline Mesh_t& getMesh() {
         return getLayout().getLayout().getMesh(); }
     inline const FieldLayout_t& getFieldLayout() const {
         return dynamic_cast<FieldLayout_t&>(getLayout().getLayout().getFieldLayout());
@@ -368,11 +368,11 @@ public:
     inline FieldLayout_t& getFieldLayout() {
         return dynamic_cast<FieldLayout_t&>(getLayout().getLayout().getFieldLayout());
     }
-    
+
     inline void setCoupling(T c) {
         coupling_m = c;
     }
-    
+
     inline T getCoupling() {
         return coupling_m;
     }
@@ -403,28 +403,28 @@ public:
     void boundp() {
       Inform msg2all("boundp ", INFORM_ALL_NODES);
       bounds(R, rmin_m, rmax_m);
-      
-      NDIndex<Dim> domain = getFieldLayout().getDomain(); 
+
+      NDIndex<Dim> domain = getFieldLayout().getDomain();
       for(int i=0; i<Dim; i++)
 	nr_m[i] = domain[i].length();
-      
-      // enlarge domaine 
+
+      // enlarge domaine
       Vector_t dr = 1.05 * (rmax_m - rmin_m);
-      
+
       for(int i=0; i<Dim; i++)
-	hr_m[i] = (rmax_m[i] - rmin_m[i]) / (nr_m[i] - 1.0); 
-      
-      // rescale mesh 
+	hr_m[i] = (rmax_m[i] - rmin_m[i]) / (nr_m[i] - 1.0);
+
+      // rescale mesh
       getMesh().set_meshSpacing( &(hr_m[0])  );
-      getMesh().set_origin( rmin_m ); 
+      getMesh().set_origin( rmin_m );
       // (re) initialize the fields
-      rho_m.initialize(getMesh(), 
-		       getFieldLayout(), 
-		       GuardCellSizes<Dim>(1), 
+      rho_m.initialize(getMesh(),
+		       getFieldLayout(),
+		       GuardCellSizes<Dim>(1),
 		       bc_m);
-      eg_m.initialize(getMesh(), 
-		      getFieldLayout(), 
-		      GuardCellSizes<Dim>(1), 
+      eg_m.initialize(getMesh(),
+		      getFieldLayout(),
+		      GuardCellSizes<Dim>(1),
 		      vbc_m);
       rho_m = 0.0;
       eg_m = Vector_t(0.0);
@@ -435,26 +435,26 @@ public:
 	totNum_m[0]=getTotalNum();
       }
       else {
-	for (unsigned long int i=0; i<getLocalNum(); i++) 
+	for (unsigned long int i=0; i<getLocalNum(); i++)
 	  locNum_m[bunchNo[i]]++;
 	reduce(locNum_m,locNum_m+MAXCLONE,totNum_m,OpAddAssign());
       }
     }
 
-    inline void scaleIn () { 
+    inline void scaleIn () {
         for (unsigned long int i=0; i<getLocalNum(); i++)
             R[i] -= MeanR_m[bunchNo[i]];
         boundp();
     }
-    
+
 
     inline void scaleOut (Vector_t center)  {
         /** special scaleOut for the first bunch in the machine
          */
         R += center;
     }
-    
-    inline void scaleOut ()  { 
+
+    inline void scaleOut ()  {
         for (unsigned long int i=0; i<getLocalNum(); i++)
             R[i] += MeanR_m[bunchNo[i]];
     }
@@ -462,16 +462,16 @@ public:
 
     inline void do_binaryRepart(int maxDev) {
         Inform msg("do_binaryRepart ");
-        if(maxDev>0) {            
+        if(maxDev>0) {
 #ifdef USE_PBE
             pbe_start(2,"binaryRepart");
-#endif  
+#endif
             double idealNp     = getTotalNum()/Ippl::getNodes();
             double localDev    = 100.0*std::abs((idealNp-getLocalNum())/idealNp);
             double actMaxDev = 0.0;
-            
+
             reduce(localDev, actMaxDev, OpMaxAssign());
-            
+
             if (actMaxDev > maxDev) {
                 msg << "do binaryRepart threshold is " << maxDev << " max inbalance reached is " << actMaxDev << endl;
                 do_binaryRepart();
@@ -485,9 +485,9 @@ public:
 #endif
         }
     }
-    
+
     inline void do_binaryRepart() {
-        scaleIn(); 
+        scaleIn();
         BinaryRepartition(*this);
         scaleOut();
     }
@@ -498,7 +498,7 @@ public:
         reduce(localmin, globalMin, OpMinAssign());
         return globalMin;
     }
-    
+
 
 
 
@@ -509,7 +509,7 @@ public:
             getBConds()[i] = ParticleNoBCond;
         }
     }
-  
+
     inline void setBCAllPeriodic() {
         for (int i=0; i < 2*Dim; ++i) {
             bc_m[i] = new PeriodicFace<T,Dim,Mesh_t,Center_t>(i);
@@ -517,18 +517,18 @@ public:
             getBConds()[i] = ParticlePeriodicBCond;
         }
     }
-  
+
     inline void setBCPeriodicInZOpenInXY() {
         bc_m[0] = new ZeroFace<T,Dim,Mesh_t,Center_t>(0);
         bc_m[1] = new ZeroFace<T,Dim,Mesh_t,Center_t>(1);
         bc_m[2] = new ZeroFace<T,Dim,Mesh_t,Center_t>(2);
         bc_m[3] = new ZeroFace<T,Dim,Mesh_t,Center_t>(3);
-    
+
         vbc_m[0] = new ZeroFace<Vector_t,Dim,Mesh_t,Center_t>(0);
         vbc_m[1] = new ZeroFace<Vector_t,Dim,Mesh_t,Center_t>(1);
         vbc_m[2] = new ZeroFace<Vector_t,Dim,Mesh_t,Center_t>(2);
         vbc_m[3] = new ZeroFace<Vector_t,Dim,Mesh_t,Center_t>(3);
-    
+
         getBConds()[0] = ParticleNoBCond;
         getBConds()[1] = ParticleNoBCond;
         getBConds()[2] = ParticleNoBCond;
@@ -541,19 +541,19 @@ public:
             bc_m[5] = new PeriodicFace<T,Dim,Mesh_t,Center_t>(5);
             vbc_m[4] = new PeriodicFace<Vector_t,Dim,Mesh_t,Center_t>(4);
             vbc_m[5] = new PeriodicFace<Vector_t,Dim,Mesh_t,Center_t>(5);
-    
+
         } else {
             bc_m[4] = new PeriodicFace<T,Dim,Mesh_t,Center_t>(4);
             bc_m[5] = new PeriodicFace<T,Dim,Mesh_t,Center_t>(5);
             vbc_m[4] = new PeriodicFace<Vector_t,Dim,Mesh_t,Center_t>(4);
             vbc_m[5] = new PeriodicFace<Vector_t,Dim,Mesh_t,Center_t>(5);
-        }    
+        }
     }
      
-    inline void writeHeader(ofstream &os, unsigned int idx, double ga, 
+    inline void writeHeader(ofstream &os, unsigned int idx, double ga,
         unsigned long int N, Vector_t pmin, Vector_t pmax,  Vector_t cm, double t,
         double I, unsigned long N0,  Vector_t rcm, double r, double phi, unsigned int turn) {
-        
+
         os << "# " << getTitle() << " format: x/m,y/m,z/m,px,y,pz,id (p == v/(beta*c)" << endl;
         os << "# s: "<< 0.0  << " rcm= " << rcm << " r= " << r << " phi= " << phi << " turn= " << turn << endl;
         os << "# struture lenght: 0 ... not used t= " << t << endl;
@@ -568,57 +568,57 @@ public:
         os << "# Energy drive beam (gamma) " << ga << endl;
         os << "# Data set  " << idx << endl;
     }
-        
+
     inline void writePhaseSpace(string fn,unsigned int fnum, double rcm, double phi, unsigned int turn, unsigned int clone) {
-        
+
         stringstream ff;
         ofstream of;
 	Inform msg("writePhaseSpace: ", INFORM_ALL_NODES);
-	
+
 #ifdef USE_PBE
         pbe_start(10,"writePhaseSpace");
-#endif                    
+#endif
         if (clone==0)
             ff << fn  << setw(4) << setfill('0') << fnum << ".dat";
         else
             ff << fn + string("-clone-") << setw(4) << setfill('0') << fnum << ".dat";
-        
+
         int tag = Ippl::Comm->next_tag(IPPL_APP_TAG4, IPPL_APP_CYCLE);
-        
+
 
         double ga = getGamma(clone);
-        double be = sqrt(1.0-(1.0/(ga*ga)));  
-        
+        double be = sqrt(1.0-(1.0/(ga*ga)));
+
         double v0 = be*CLIGHT;
         double t = getTime(clone);
-        
+
         Vector_t pmin, pmax;
         bounds(P,pmin, pmax);
-        
+
         Vector_t cm = getCenterOfMass();
         scaleIn();
-        
+
         double current = getCurrent();
         unsigned long N0 = getN0();
-        
+
         if(isRoot()) {
             of.open(ff.str().c_str(),ios::out);
             of.precision(15);
             of.setf(ios::scientific, ios::floatfield);
             writeHeader(of,fnum,ga,getTotalnum(clone),pmax,pmin,cm,t,current,N0,MeanR_m[clone],rcm,phi,turn);
-            
+
             unsigned int dataBlocks=0;
             unsigned int id=0;
-            
+
             double x,y,z,px,py,pz;
-            
+
             for (unsigned k = 0; k < getLocalNum(); k++) {
                 if (bunchNo[k] == clone)
                     of <<  R[k](0) << "  " << R[k](1)   << "  " << R[k](2) << "  "
                        <<  P[k](0) << "  " << P[k](1)   << "  " << P[k](2) << "  " << ID[k] << endl;
             }
-            
-            int notReceived =  Ippl::getNodes() - 1; 
+
+            int notReceived =  Ippl::getNodes() - 1;
             while (notReceived > 0) {
                 int node = COMM_ANY_NODE;
                 Message* rmsg =  Ippl::Comm->receive_block(node, tag);
@@ -642,7 +642,7 @@ public:
             of.close();
         }
         else {
-            
+
             Message* smsg = new Message();
             unsigned dataBlocks = 7*getLocalnum(clone);
             smsg->put(dataBlocks);
@@ -655,18 +655,18 @@ public:
                     smsg->put(ID[k]);
                 }
             }
-            bool res = Ippl::Comm->send(smsg, 0, tag);	
-            if (! res) 
+            bool res = Ippl::Comm->send(smsg, 0, tag);
+            if (! res)
                 ERRORMSG("Ippl::Comm->send(smsg, 0, tag) failed " << endl;);
         }
         IpplInfo::Comm->barrier();
         scaleOut();
 #ifdef USE_PBE
         pbe_stop(10);
-#endif                    
+#endif
     }
-    
-    
+
+
     inline void writeStatistics(string fn, int turn, bool calcTune, double r, double phi, double dT) {
         ofstream ofs1,ofs2;
         Vector_t MeanR;
@@ -678,67 +678,67 @@ public:
         Vector_t rmsEmit;
         Vector_t TotalP;
         Vector_t TotalL;
-        
+
         Vector_t rmsR;
         Vector_t rmsP;
 
 #ifdef USE_PBE
             pbe_start(9,"writeStatistics");
-#endif                    
-            scaleIn();  
-            
+#endif
+            scaleIn();
+
             T denN = 1.0 / getTotalNum();
             int Np  = getTotalNum();
-        
+
             MeanR = sum(R) * denN;
             MeanP = sum(P) * denN;
-            
+
             MeanR2 = sum(R*R) * denN;
             MeanP2 = sum(P*P) * denN;
-            
+
             MeanRP = sum(R*P) * denN;
             Mean2RP = MeanRP * MeanRP;
-            
+
             double ga = getGamma(0);
-            
+
 
             // Calculate rms emittance and standard deviation of R and P: rmsR and rmsP
             for (int i=0;i<Dim;i++) {
                 rmsEmit(i) = sqrt( (MeanR2*MeanP2)(i) - Mean2RP(i)  ) / ( getBeta()*CLIGHT );
                 rmsEmit(2) /= ga*ga;
-                rmsR(i) = sqrt( MeanR2(i) - (MeanR*MeanR)(i)  ); 
-                rmsP(i) = sqrt( MeanP2(i) - (MeanP*MeanP)(i)  ); 
+                rmsR(i) = sqrt( MeanR2(i) - (MeanR*MeanR)(i)  );
+                rmsP(i) = sqrt( MeanP2(i) - (MeanP*MeanP)(i)  );
             }
-            
+
             CenterOfMass_m = sum(mass_m*R) / sum(mass_m);
-            
+
             //Calculate total momentum and angular momentum
-            
+
             TotalP = sum(P);
             TotalL = sum(cross(R,P));
-            
+
             // maximal radius
             Vector_t maxR = max(R);
             Vector_t maxE = max(Ef);
-            
+
             Vector_t meanPrad = sum(MeanP - P)/MeanP;
             Vector_t rmsPrad = sum(rmsP - P)/rmsP;
             T actTime = getTime(0);
-            
-            
+
+
             if (isRoot()) {
-                ofs1.precision(14);  
+                ofs1.precision(14);
                 ofs1.open(fn.c_str(),ios::app);
-                ofs1.setf(ios_base::scientific); 
+                ofs1.setf(ios_base::scientific);
                 ofs1 << MeanR[0]  << "  "  << MeanR[1]  << "  "   << MeanR[2]  << "  " // 1 2 3      [m]
                      << meanPrad[0] << "  "  << meanPrad[1] << "  "   << meanPrad[2] << "  " // 4 5 6     [rad]
                      << actTime  << "  "                                                     // 7          [s]
                      << rmsR[0]   << "  "  << rmsR[1]    << "  "   << rmsR[2]   << "  " // 8 9 10    [m]
-                     << rmsPrad[0]  << "  "  << rmsPrad[1]   << "  "   << rmsPrad[2]  << "  " // 11 12 13    [rad]    
+                     << rmsPrad[0]  << "  "  << rmsPrad[1]   << "  "   << rmsPrad[2]  << "  " // 11 12 13    [rad]
                      << maxR[0]     << "  "  << maxR[1]      << "  "   << maxR[2]     << "  " // 14 15 16    [m]
                      << maxE[0]     << "  "  << maxE[1]      << "  "   << maxE[2]     << "  " // 17 18 19     [V/m]
-                     << rmsEmit[0] << "  " << rmsEmit[1] << "  "   << rmsEmit[2] << "  " // 20 21 22    
-                     << TotalP[0] << "  "  << TotalP[1]  << "  "   << TotalP[2] << "  "  // 23 24 25 
+                     << rmsEmit[0] << "  " << rmsEmit[1] << "  "   << rmsEmit[2] << "  " // 20 21 22
+                     << TotalP[0] << "  "  << TotalP[1]  << "  "   << TotalP[2] << "  "  // 23 24 25
                      << TotalL[0] << "  "  << TotalL[1]  << "  "   << TotalL[2] << "  "  // 26 27 28
                      << MeanR_m[0](0) << "  " << MeanR_m[0](1) << "  " << MeanR_m[0](2) << "  "                        // 29 30 31    [m]
                      << MeanP_m[0](0) << "  " << MeanP_m[0](1) << "  " << MeanP_m[0](2) << "  "                        // 32 33 34    [m]
@@ -752,26 +752,26 @@ public:
             long locNum = getLocalNum();
             long minLocNum = 0;
             long maxLocNum = 0;
-            
+
             reduce(locNum, minLocNum, OpMinAssign());
             reduce(locNum, maxLocNum, OpMaxAssign());
 
             if (isRoot()) {
-                ofs1.precision(14);  
+                ofs1.precision(14);
                 ofs1.open((fn+string("-comp")).c_str(),ios::app);
-                ofs1.setf(ios_base::scientific); 
-                
+                ofs1.setf(ios_base::scientific);
+
                 ofs1 << dT << "  " <<  minLocNum << "  " << maxLocNum << endl;
-                
+
                 ofs1.close();
             }
-            
+
             IpplInfo::Comm->barrier();
             scaleOut();
 #ifdef USE_PBE
             pbe_stop(9);
-#endif                    
+#endif
     }
-  
+
 };
-#endif
+#endif
\ No newline at end of file
diff --git a/ippl/test/hdf5/hdf5write-1.cpp b/ippl/test/hdf5/hdf5write-1.cpp
index e0b967e508dc2e1cf7bef51b99c7d60637aed3a0..84bcd4c352c7ab08a8ab7093c7fe5080dde01e93 100644
--- a/ippl/test/hdf5/hdf5write-1.cpp
+++ b/ippl/test/hdf5/hdf5write-1.cpp
@@ -2,8 +2,8 @@
 /***************************************************************************
  *
  * The IPPL Framework
- * 
- * This program was prepared by PSI. 
+ *
+ * This program was prepared by PSI.
  * All rights in the program are reserved by PSI.
  * Neither PSI nor the author(s)
  * makes any warranty, express or implied, or assumes any liability or
@@ -15,10 +15,10 @@
 
 /***************************************************************************
 
- This test program sets up a simple sine-wave electric field in 3D, 
+ This test program sets up a simple sine-wave electric field in 3D,
    creates a population of particles with random q/m values (charge-to-mass
    ratio) and velocities, and then tracks their motions in the static
-   electric field using nearest-grid-point interpolation. 
+   electric field using nearest-grid-point interpolation.
 
    After each timestep the full phase space is saved
 Usage:
@@ -52,7 +52,7 @@ Usage:
 // dimension of our positions
 const unsigned Dim = 3;
 
-// some typedefs 
+// some typedefs
 typedef ParticleSpatialLayout<double,Dim>::SingleParticlePos_t Vector_t;
 typedef ParticleSpatialLayout<double,Dim> playout_t;
 typedef UniformCartesian<Dim,double> Mesh_t;
@@ -81,7 +81,7 @@ public:
   typename PL::ParticlePos_t E;  // electric field at particle position
   typename PL::ParticlePos_t B;  // magnetic field at particle position
 
-  ChargedParticles(PL* pl, BC_t bc, InterPol_t interpol, e_dim_tag decomp[Dim], bool gCells) : 
+  ChargedParticles(PL* pl, BC_t bc, InterPol_t interpol, e_dim_tag decomp[Dim], bool gCells) :
     IpplParticleBase<PL>(pl),
     bco_m(bc),
     interpol_m(interpol),
@@ -101,18 +101,18 @@ public:
     openDataSink(string("dataH5.dat"));
 
   }
-  
+
   ~ChargedParticles() {
     H5PartCloseFile(file_m);
   }
-  
+
   /*
     In case we have OOP or PPP boundary conditions
     we must define the domain, i.e can not be deduced from the
     particles as in the OOO case.
   */
 
-  ChargedParticles(PL* pl, BC_t bc, InterPol_t interpol, Vector_t hr, Vector_t rmin, Vector_t rmax, e_dim_tag decomp[Dim], bool gCells) : 
+  ChargedParticles(PL* pl, BC_t bc, InterPol_t interpol, Vector_t hr, Vector_t rmin, Vector_t rmax, e_dim_tag decomp[Dim], bool gCells) :
     IpplParticleBase<PL>(pl),
     bco_m(bc),
     interpol_m(interpol),
@@ -132,7 +132,7 @@ public:
     for(int i=0; i<Dim; i++)
 	decomp_m[i]=decomp[i];
     openDataSink(string("dataH5.dat"));
-    
+
   }
   
   void setupBCs() {
@@ -140,14 +140,14 @@ public:
       setBCAllOpen();
     else if (bco_m == PPP)
       setBCAllPeriodic();
-    else 
+    else
       setBCOOP();
   }
 
   inline const Mesh_t& getMesh() const { return this->getLayout().getLayout().getMesh(); }
-  
+
   inline Mesh_t& getMesh() { return this->getLayout().getLayout().getMesh(); }
-    
+
   inline const FieldLayout_t& getFieldLayout() const {
     return dynamic_cast<FieldLayout_t&>(this->getLayout().getLayout().getFieldLayout());
   }
@@ -170,12 +170,12 @@ public:
       scatterCIC();
     else
       scatterNGP();
-    
+
     /*
       now sum over all gridpoints ... a bit nasty !
 
     */
-    
+
     Field<double,Dim> tmpf;
     NDIndex<Dim> domain = getFieldLayout().getDomain();
 
@@ -198,7 +198,7 @@ public:
 		Q +=  tmpf.localElement(elem);
 	    }
         }
-	
+
     }
     reduce(Q,Q,OpAddAssign());
     m << "sum(Q)= " << initialQ << " sum(EFDMag)= " << sum(EFDMag_m) << endl;
@@ -206,21 +206,21 @@ public:
   }
   
   void myUpdate() {
-    
+
     double hz   = hr_m[2];
     double zmin = rmin_m[2];
     double zmax = rmax_m[2];
 
     if (bco_m != PPP) {
       bounds(this->R, rmin_m, rmax_m);
-                  
-      NDIndex<Dim> domain = this->getFieldLayout().getDomain(); 
-      
+
+      NDIndex<Dim> domain = this->getFieldLayout().getDomain();
+
       for(int i=0; i<Dim; i++)
 	nr_m[i] = domain[i].length();
-	
+
       for(int i=0; i<Dim; i++)
-	  hr_m[i] = (rmax_m[i] - rmin_m[i]) / (nr_m[i] - 1.0); 
+	  hr_m[i] = (rmax_m[i] - rmin_m[i]) / (nr_m[i] - 1.0);
 
       if (bco_m == OOP) {
 	rmin_m[2] = zmin;
@@ -239,7 +239,7 @@ public:
 	  EFD_m.initialize(getMesh(), getFieldLayout(), vbc_m);
 	  EFDMag_m.initialize(getMesh(), getFieldLayout(), bc_m);
       }
-    } 
+    }
     else {
       if(fieldNotInitialized_m) {
 	fieldNotInitialized_m=false;
@@ -260,29 +260,29 @@ public:
 
   void initFields() {
     Inform m("initFields ");
-    
+
     NDIndex<Dim> domain = getFieldLayout().getDomain();
-    
+
     for(int i=0; i<Dim; i++)
       nr_m[i] = domain[i].length();
-  
+
     int nx = nr_m[0];
     int ny = nr_m[1];
     int nz = nr_m[2];
 
-    double phi0 = 0.1*nx;            
+    double phi0 = 0.1*nx;
 
     m << "rmin= " << rmin_m << " rmax= " << rmax_m << " h= " << hr_m << " n= " << nr_m << endl;
-    
+
     Index I(nx), J(ny), K(nz);
-  
+
     assign(EFD_m[I][J][K](0), -2.0*pi*phi0/nx * cos(2.0*pi*(I+0.5)/nx) * cos(4.0*pi*(J+0.5)/ny) * cos(pi*(K+0.5)/nz));
 
     assign(EFD_m[I][J][K](1),  4.0*pi*phi0/ny * sin(2.0*pi*(I+0.5)/nx) * sin(4.0*pi*(J+0.5)/ny));
 
     assign(EFD_m[I][J][K](2),  4.0*pi*phi0/ny * sin(2.0*pi*(I+0.5)/nx) * sin(4.0*pi*(J+0.5)/ny));
 
-    assign(EFDMag_m[I][J][K], 
+    assign(EFDMag_m[I][J][K],
 	   EFD_m[I][J][K](0) * EFD_m[I][J][K](0) +
 	   EFD_m[I][J][K](1) * EFD_m[I][J][K](1) +
 	   EFD_m[I][J][K](2) * EFD_m[I][J][K](2));
@@ -299,9 +299,9 @@ public:
 
     Inform msg("savePhaseSpaceData ");
     Inform msg2all("savePhaseSpaceData ",INFORM_ALL_NODES);
-    
+
     long long  N = this->getLocalNum();
-    
+
     void *varray = malloc(N*sizeof(double));
     double *farray = (double*)varray;
 <<<<<<< .mine
@@ -310,21 +310,21 @@ public:
 =======
     h5part_int64_t *larray = (h5part_int64_t *)varray;
 >>>>>>> .r6004
-  
-    /* ------------------------------------------------------------------------ 
+
+    /* ------------------------------------------------------------------------
        Get the particle decomposition from all the nodes
     */
     long long *locN = (long long *) malloc(Ippl::getNodes()*sizeof(long long));
     long long  *globN = (long long*) malloc(Ippl::getNodes()*sizeof(long long));
-    
+
     for(int i=0; i<Ippl::getNodes(); i++) {
       globN[i] = locN[i]=0;
     }
     locN[Ippl::myNode()] = N;
     reduce(locN, locN + Ippl::getNodes(), globN, OpAddAssign());
-    
+
     /* ------------------------------------------------------------------------ */
-    
+
     double actPos           = 0.0;
     double structLenght     = 0.0;
     Vector_t org(0.0);
@@ -337,59 +337,59 @@ public:
     Vector_t centroid(0.0);
     unsigned nTot           = this->getTotalNum();
 
-    H5PartSetStep(file_m,idx_m);  
-    H5PartSetNumParticles(file_m,N); 
-  
+    H5PartSetStep(file_m,idx_m);
+    H5PartSetNumParticles(file_m,N);
+
     /* write scalar data i.e the header */
     long long step = idx_m;
     H5PartWriteStepAttrib(file_m,"Step", H5T_NATIVE_INT64,&step,1);
-  
+
     H5PartWriteStepAttrib(file_m,"Spos",     H5T_NATIVE_DOUBLE,&actPos,1);
-    H5PartWriteStepAttrib(file_m,"structLen",H5T_NATIVE_DOUBLE,&structLenght,1);  
+    H5PartWriteStepAttrib(file_m,"structLen",H5T_NATIVE_DOUBLE,&structLenght,1);
     H5PartWriteStepAttrib(file_m,"org",      H5T_NATIVE_DOUBLE,&org,3);
     H5PartWriteStepAttrib(file_m,"maxX",     H5T_NATIVE_DOUBLE,&maxX,3);
     H5PartWriteStepAttrib(file_m,"minX",     H5T_NATIVE_DOUBLE,&minX,3);
     H5PartWriteStepAttrib(file_m,"maxP",     H5T_NATIVE_DOUBLE,&maxP,3);
     H5PartWriteStepAttrib(file_m,"minP",     H5T_NATIVE_DOUBLE,&minP,3);
     H5PartWriteStepAttrib(file_m,"centroid", H5T_NATIVE_DOUBLE,&centroid,3);
-  
+
     H5PartWriteStepAttrib(file_m,"nloc",H5T_NATIVE_INT64, globN, Ippl::getNodes());
 
     for (long long i=0; i<N;i++)
       farray[i] =  this->R[i](0);
-    H5PartWriteDataFloat64(file_m,"x",farray); 
-  
+    H5PartWriteDataFloat64(file_m,"x",farray);
+
     for (long long i=0; i<N;i++)
       farray[i] =  this->R[i](1);
-    H5PartWriteDataFloat64(file_m,"y",farray); 
+    H5PartWriteDataFloat64(file_m,"y",farray);
 
     for (long long i=0; i<N;i++)
       farray[i] =  this->R[i](2);
-    H5PartWriteDataFloat64(file_m,"z",farray); 
-    
+    H5PartWriteDataFloat64(file_m,"z",farray);
+
     for (long long i=0; i<N;i++)
       farray[i] =  P[i](0);
-    H5PartWriteDataFloat64(file_m,"px",farray); 
+    H5PartWriteDataFloat64(file_m,"px",farray);
 
     for (long long i=0; i<N;i++)
       farray[i] =  P[i](1);
-    H5PartWriteDataFloat64(file_m,"py",farray); 
+    H5PartWriteDataFloat64(file_m,"py",farray);
 
     for (long long i=0; i<N;i++)
       farray[i] =  P[i](2);
-    H5PartWriteDataFloat64(file_m,"pz",farray); 
-  
+    H5PartWriteDataFloat64(file_m,"pz",farray);
+
     for (long long i=0; i<N;i++) {
-      if (Q[i] > 0.0) 
+      if (Q[i] > 0.0)
 	larray[i] =  this->ID[i];
-      else           
+      else
 	larray[i] =  -1*(long long int)this->ID[i];
     }
-    H5PartWriteDataInt64(file_m,"id",larray);  
+    H5PartWriteDataInt64(file_m,"id",larray);
 <<<<<<< .mine
 
     // ada save block data
-    /*  
+    /*
   NDIndex<Dim> idx = getFieldLayout().getLocalNDIndex();
     NDIndex<Dim> elem;
     h5part_int64_t herr = H5BlockDefine3DFieldLayout (
@@ -411,21 +411,21 @@ public:
 	  ii++;
 	}
       }
-    } 
+    }
     herr = H5Block3dWriteScalarField ( file_m, "EFmag", data );
-    
+
     if(data)
       free(data);
 
 */
 
-    if(varray)  
+    if(varray)
 =======
 
     // ada save block data
 
     h5part_int64_t l[6];
-    
+
     NDIndex<Dim> idx = getFieldLayout().getLocalNDIndex();
     NDIndex<Dim> elem;
     h5part_int64_t herr = H5BlockDefine3DFieldLayout (
@@ -449,7 +449,7 @@ public:
 	  ii++;
 	}
       }
-    } 
+    }
 
     herr = H5Block3dWriteScalarField ( file_m, "EFmag", data );
     if (herr < 0)
@@ -462,17 +462,17 @@ public:
 	herr = H5Block3dGetPartitionOfProc(file_m, p, &l[0], &l[1], &l[2], &l[3], &l[4], &l[5]);
 	stringstream lstr;
 	lstr << "layout" << p;
-	H5BlockWriteFieldAttrib (file_m,"EFmag", lstr.str().c_str(), H5PART_INT64,l,6);       
+	H5BlockWriteFieldAttrib (file_m,"EFmag", lstr.str().c_str(), H5PART_INT64,l,6);
       }
     }
 
 
     if(data)
       free(data);
-  if(varray)  
+  if(varray)
 >>>>>>> .r6004
       free(varray);
-    
+
     idx_m++;
   }
 
@@ -488,7 +488,7 @@ private:
     if(!file_m) {
       INFOMSG("File open failed:  exiting!" << endl);
       exit(0);
-    }   
+    }
 
     idx_m = 0;
   }
@@ -500,13 +500,13 @@ private:
       vbc_m[i] = new ZeroFace<Vector_t,Dim,Mesh_t,Center_t>(i);
     }
   }
-  
+
   inline void setBCAllPeriodic() {
     for (int i=0; i < 2*Dim; i++) {
       this->getBConds()[i] = ParticlePeriodicBCond;
       bc_m[i]  = new PeriodicFace<double  ,Dim,Mesh_t,Center_t>(i);
       vbc_m[i] = new PeriodicFace<Vector_t,Dim,Mesh_t,Center_t>(i);
-    }  
+    }
   }
 
   inline void setBCOOP() {
@@ -518,8 +518,8 @@ private:
     for (int i= 2*Dim - 2; i < 2*Dim; i++) {
       bc_m[i]  = new PeriodicFace<double  ,Dim,Mesh_t,Center_t>(i);
       vbc_m[i] = new PeriodicFace<Vector_t,Dim,Mesh_t,Center_t>(i);
-      this->getBConds()[i] = ParticlePeriodicBCond;    
-    }  
+      this->getBConds()[i] = ParticlePeriodicBCond;
+    }
   }
 
   inline void gatherNGP() {
@@ -548,12 +548,12 @@ private:
 
   Field<Vektor<double,Dim>,Dim> EFD_m;
   Field<double,Dim> EFDMag_m;
-  
+
   BConds<double,Dim,Mesh_t,Center_t> bc_m;
   BConds<Vector_t,Dim,Mesh_t,Center_t> vbc_m;
 
   Vektor<int,Dim> nr_m;
-    
+
   Vector_t hr_m;
   Vector_t rmin_m;
   Vector_t rmax_m;
@@ -562,9 +562,9 @@ private:
   InterPol_t interpol_m;
   bool fieldNotInitialized_m;
   bool doRepart_m;
-  bool withGuardCells_m;  
+  bool withGuardCells_m;
   e_dim_tag decomp_m[Dim];
-  
+
 #ifdef GTHDF5
   H5PartFile *file_m;
 #endif
@@ -590,27 +590,27 @@ int main(int argc, char *argv[]){
     myInterpol = CIC;
   else
     myInterpol = NGP;
-  
+
   bool gCells;
   gCells =  (string(argv[8])==string("GUARDCELLS"));
-  
+
 
   msg << "Particle test PIC3d " << endl;
   msg << "nt " << nt << " Np= " << totalP << " grid = " << nr <<endl;
-  
+
   if (myInterpol==CIC)
-    msg << "Cloud in cell (CIC) interpolation selected" << endl; 
+    msg << "Cloud in cell (CIC) interpolation selected" << endl;
   else
-    msg << "Nearest grid point (NGP) interpolation selected" << endl; 
-  
+    msg << "Nearest grid point (NGP) interpolation selected" << endl;
+
   if (gCells)
       msg << "Using guard cells" << endl;
   else
       msg << "Not using guard cells" << endl;
 
-  BC_t myBC;  
+  BC_t myBC;
   if (string(argv[7])==string("OOO")) {
-    myBC = OOO; // open boundary 
+    myBC = OOO; // open boundary
     msg << "BC == OOO" << endl;
   }
   else if (string(argv[7])==string("OOP")) {
@@ -618,7 +618,7 @@ int main(int argc, char *argv[]){
     msg << "BC == OOP" << endl;
   }
   else {
-    myBC = PPP; // all periodic 
+    myBC = PPP; // all periodic
     msg << "BC == PPP" << endl;
   }
 
@@ -643,7 +643,7 @@ int main(int argc, char *argv[]){
 
   for (int d=0; d < Dim; ++d)
       decomp[d] = (d == serialDim) ? SERIAL : PARALLEL;
-  
+
   // create mesh and layout objects for this problem domain
   mesh          = new Mesh_t(domain);
   FL            = new FieldLayout_t(*mesh, decomp);
@@ -670,9 +670,9 @@ int main(int argc, char *argv[]){
   // initialize the particle object: do all initialization on one node,
   // and distribute to others
   P->create(totalP / Ippl::getNodes());
-    
+
   msg << "particles created " << endl;
-    
+
   // quiet start for particle positions
   assign(P->R(0), IpplRandom * nr[0]);
   assign(P->R(1), IpplRandom * nr[1]);
@@ -682,22 +682,22 @@ int main(int argc, char *argv[]){
 
   // random initialization for charge-to-mass ratio
   assign(P->Q,q);
-    
+
   msg << "initial conditions assigned " << endl;
 
   // redistribute particles based on spatial layout
-  P->myUpdate(); 
+  P->myUpdate();
 
   msg2all << "Nlocal= " << P->getLocalNum() << endl;
   Ippl::Comm->barrier();
 
   msg << "initial update and initial mesh done .... Q= " << sum(P->Q) << endl;
-  
+
   msg << P->getMesh() << endl;
   msg << P->getFieldLayout() << endl;
 
   msg << "scatter test done delta= " <<  P->scatter() << endl;
-    
+
   P->initFields();
   msg << "P->initField() done " << endl;
 
@@ -710,28 +710,28 @@ int main(int argc, char *argv[]){
     // basic leapfrogging timestep scheme.  velocities are offset
     // by half a timestep from the positions.
     assign(P->R, P->R + dt * P->P);
-    
+
     // update particle distribution across processors
     P->myUpdate();
-    
+
     // gather the local value of the E field
     P->gather();
-      
+
     // advance the particle velocities
     assign(P->P, P->P + dt * P->Q * P->E);
     msg << "Finished iteration " << it << " - min/max r and h " << P->getRMin() << P->getRMax() << P->getHr() << endl;
-    mytimer.clear();    
+    mytimer.clear();
     mytimer.start();
     P->savePhaseSpace();
     mytimer.stop();
 
     long long  N = P->getLocalNum();
-    double rate = ((6*N*sizeof(double) + N*sizeof(unsigned))/1000000.0) / mytimer.clock_time(); 
-    reduce(rate,rate,OpAddAssign());      
-    reduce(N,N,OpAddAssign());      
-    msg << "Number of particles (x,y,z,px,py,pz,id) " << N << " in file set Write to disk bw= " << rate << " [MB/s] "<< endl; 
+    double rate = ((6*N*sizeof(double) + N*sizeof(unsigned))/1000000.0) / mytimer.clock_time();
+    reduce(rate,rate,OpAddAssign());
+    reduce(N,N,OpAddAssign());
+    msg << "Number of particles (x,y,z,px,py,pz,id) " << N << " in file set Write to disk bw= " << rate << " [MB/s] "<< endl;
   }
-  
+
   Ippl::Comm->barrier();
   msg << "Particle test PIC3d: End." << endl;
 
@@ -743,6 +743,5 @@ int main(int argc, char *argv[]){
 /***************************************************************************
  * $RCSfile: addheaderfooter,v $   $Author: adelmann $
  * $Revision: 1.1.1.1 $   $Date: 2003/01/23 07:40:17 $
- * IPPL_VERSION_ID: $Id: addheaderfooter,v 1.1.1.1 2003/01/23 07:40:17 adelmann Exp $ 
- ***************************************************************************/
-
+ * IPPL_VERSION_ID: $Id: addheaderfooter,v 1.1.1.1 2003/01/23 07:40:17 adelmann Exp $
+ ***************************************************************************/
\ No newline at end of file
diff --git a/ippl/test/particle/1dperiodic.cpp b/ippl/test/particle/1dperiodic.cpp
index a53bbe4f1000a918221a3f092c6d983c6a287bf4..2e95220adee92b89033faf631be4eb1bd9112906 100644
--- a/ippl/test/particle/1dperiodic.cpp
+++ b/ippl/test/particle/1dperiodic.cpp
@@ -2,27 +2,27 @@
 /***********************************************************************************
  *
  * The IPPL Framework
- * 
- * This program was prepared by PSI. 
- * All rights in the program are reserved by PSI. 
+ *
+ * This program was prepared by PSI.
+ * All rights in the program are reserved by PSI.
  * Neither PSI nor the author(s)
  * makes any warranty, express or implied, or assumes any liability or
  * responsibility for the use of this software
  *
  * Visit http://www.
  *
- * This test program sets up a simple sine-wave electric field in 3D, 
+ * This test program sets up a simple sine-wave electric field in 3D,
  * creates a population of particles with random q/m values (charge-to-mass
  * ratio) and velocities, and then tracks their motions in the static
- * electric field using nearest-grid-point interpolation. 
+ * electric field using nearest-grid-point interpolation.
  *
  * Usage:
  *
  * $MYMPIRUN -np 2 salman-1 128 128 ??? 10000 10 NGP initialx initialy --commlib mpi
  *
  *          nx,ny xx  xxx NP NTstep  Interp  xini yini dx  dy  meshorgx meshorgy hx  hy
- *          |     |       |  |       |       |    |    |   |   |        |        |   |  
- * salman-1 4     xx  xxx 1  7       NGP     1.0  1.0  1.0 1.0 1.0      1.0      1.0 1.0 --commlib mpi 
+ *          |     |       |  |       |       |    |    |   |   |        |        |   |
+ * salman-1 4     xx  xxx 1  7       NGP     1.0  1.0  1.0 1.0 1.0      1.0      1.0 1.0 --commlib mpi
  *
  *
  *          nx,ny Interp  meshorgx meshorgy hx  hy  domplus steps
@@ -40,7 +40,7 @@
 // dimension of our positions
 const unsigned Dim = 1;
 
-// some typedefs 
+// some typedefs
 typedef ParticleSpatialLayout<double,Dim>::SingleParticlePos_t Vector_t;
 typedef ParticleSpatialLayout<double,Dim> playout_t;
 typedef UniformCartesian<Dim,double> Mesh_t;
@@ -68,7 +68,7 @@ public:
   typename PL::ParticlePos_t E;  // electric field at particle position
   typename PL::ParticlePos_t B;  // magnetic field at particle position
 
-  ChargedParticles(PL* pl, InterPol_t interpol, Vector_t hr, e_dim_tag decomp[Dim], Vector_t mesh_org) : 
+  ChargedParticles(PL* pl, InterPol_t interpol, Vector_t hr, e_dim_tag decomp[Dim], Vector_t mesh_org) :
     IpplParticleBase<PL>(pl),
     interpol_m(interpol),
     hr_m(hr),
@@ -78,25 +78,25 @@ public:
     // register the particle attributes
     this->addAttribute(qm);
 
-    NDIndex<Dim> domain = getFieldLayout().getDomain(); 
+    NDIndex<Dim> domain = getFieldLayout().getDomain();
 
     for(int i=0; i<Dim; i++)
       nr_m[i] = domain[i].length();
-    
-    hr_m = hr; 
+
+    hr_m = hr;
     getMesh().set_meshSpacing(&(hr_m[0]));
     getMesh().set_origin(mesh_org);
-    
+
     for(int i=0; i<Dim; i++)
       decomp_m[i]=decomp[i];
 
-    setBCAllPeriodic();  
+    setBCAllPeriodic();
   }
   
   inline const Mesh_t& getMesh() const { return this->getLayout().getLayout().getMesh(); }
-  
+
   inline Mesh_t& getMesh() { return this->getLayout().getLayout().getMesh(); }
-    
+
   inline const FieldLayout_t& getFieldLayout() const {
     return dynamic_cast<FieldLayout_t&>( this->getLayout().getLayout().getFieldLayout());
   }
@@ -112,12 +112,12 @@ public:
       scatterCIC();
     else
       scatterNGP();
-    
+
     /*
       now sum over all gridpoints ... a bit nasty !
 
-   
-    
+
+
     Field<double,Dim> tmpf;
     NDIndex<Dim> domain = getFieldLayout().getDomain();
 
@@ -140,7 +140,7 @@ public:
 		Q +=  tmpf.localElement(elem);
 	    }
         }
-	
+
     }
     reduce(Q,Q,OpAddAssign());
     m << "sum(qm)= " << initialQ << " sum(rho_m)= " << sum(rho_m) << endl;
@@ -152,16 +152,16 @@ public:
     bounds(this->R, rmin_m, rmax_m);
     if(fieldNotInitialized_m) {
 
-      // rescale mesh 
+      // rescale mesh
       // getMesh().set_meshSpacing(&(hr_m[0]));
-      // getMesh().set_origin( -hr_m/2.0 ); 
+      // getMesh().set_origin( -hr_m/2.0 );
       // getMesh().set_origin(Vector_t(1.0));
       rho_m.initialize(getMesh(), getFieldLayout(), GuardCellSizes<Dim>(GUARDCELL), bc_m);
       fieldNotInitialized_m=false;
     }
     this->update();
   }
-  
+
   void myUpdate() {
     bounds(this->R, rmin_m, rmax_m);
     this->update();
@@ -178,12 +178,12 @@ public:
   void savePhaseSpace(string fn, int idx) {
   }
 
-  inline void setBCAllPeriodic() {    
+  inline void setBCAllPeriodic() {
     for (int i=0; i < 2*Dim; i++) {
       this->getBConds()[i] = ParticlePeriodicBCond;
       bc_m[i]  = new ParallelPeriodicFace<double  ,Dim,Mesh_t,Center_t>(i);
       vbc_m[i] = new ParallelPeriodicFace<Vector_t,Dim,Mesh_t,Center_t>(i);
-    }  
+    }
   }
 
   Field<double,Dim> rho_m;
@@ -207,7 +207,7 @@ private:
   BConds<Vector_t,Dim,Mesh_t,Center_t> vbc_m;
 
   Vektor<int,Dim> nr_m;
-    
+
   Vector_t hr_m;
   Vector_t rmin_m;
   Vector_t rmax_m;
@@ -243,16 +243,16 @@ int main(int argc, char *argv[]){
     myInterpol = CIC;
   else
     myInterpol = NGP;
-  
+
   msg << "Np= " << totalP << " grid = " << nr <<endl;
   msg << "0 <= x <= " << nx-1 << " 0 <= y <= " << ny-1 << endl;
-  
+
   if (myInterpol==CIC)
-    msg << "Cloud in cell (CIC) interpolation selected" << endl; 
+    msg << "Cloud in cell (CIC) interpolation selected" << endl;
   else
-    msg << "Nearest grid point (NGP) interpolation selected" << endl; 
-  
-  msg << "BC: periodic in all dimensions" << endl; 
+    msg << "Nearest grid point (NGP) interpolation selected" << endl;
+
+  msg << "BC: periodic in all dimensions" << endl;
 
   e_dim_tag decomp[Dim];
   int serialDim = 2;//Dim-1;
@@ -266,44 +266,44 @@ int main(int argc, char *argv[]){
   NDIndex<Dim> domain;
   for(int i=0; i<Dim; i++) {
     domain[i] = domain[i] = Index(nr[i] + domplus);
-    decomp[i] = (i == serialDim) ? SERIAL : PARALLEL; 
+    decomp[i] = (i == serialDim) ? SERIAL : PARALLEL;
   }
 
   // create mesh and layout objects for this problem domain
   mesh          = new Mesh_t(domain);
   FL            = new FieldLayout_t(*mesh, decomp);
   playout_t* PL = new playout_t(*FL, *mesh);
-  
+
   P = new ChargedParticles<playout_t>(PL,myInterpol,hr,decomp,mesh_org);
-  
-  P->create(totalP);  
+
+  P->create(totalP);
   size_t k = 0;
   for (int i=0; i<nx; i++) {
       P->R[k]  = Vector_t(i);//,j);
       k++;
     }
-  
+
   double q = 1.0;
   assign(P->qm,q);
   P->update();
 
   // redistribute particles based on spatial layout
-  P->myInitialUpdate(); 
-  
+  P->myInitialUpdate();
+
   msg << P->getMesh() << endl;
   msg << P->getFieldLayout() << endl;
   msg << "particles created and initial conditions assigned Q=" << sum(P->qm) << endl;
 
   size_t loc = (nx*ny) - 1;
-  
-  
+
+
   P->scatter();
-  for(int i=0; i < nr[0]; i++) 
+  for(int i=0; i < nr[0]; i++)
       P->rho_m[i]=(i+1)*100;
   P->rho_m.fillGuardCells();
   msg << "[" << nr[0] << "]: " << P->rho_m[nr[0]] << endl;
   msg << "[-1]: " << P->rho_m[-1] << endl;
-  P->myUpdate(); 
+  P->myUpdate();
   //P->printField(msg, P->rho_m);
 
 
@@ -311,19 +311,19 @@ int main(int argc, char *argv[]){
     //P->rho_m= 0.0;
     //P->R[loc] += Vector_t(0.0,0.1);
     //P->update();
-  
+
     //k = 0;
     //for (int i=0; i<nx; i++) {
       //msg << endl;
       //for (int j=0; j<ny; j++) {
-	//msg << P->R[k] << " "; 
+	//msg << P->R[k] << " ";
 	//k++;
       //}
     //}
     //msg << endl << endl;
-  
-    //P->scatter();     
-    //P->myUpdate(); 
+
+    //P->scatter();
+    //P->myUpdate();
     //P->printField(msg, P->rho_m);
   //}
   //Ippl::Comm->barrier();
@@ -334,7 +334,7 @@ int main(int argc, char *argv[]){
 /***************************************************************************
  * $RCSfile: addheaderfooter,v $   $Author: adelmann $
  * $Revision: 1.1.1.1 $   $Date: 2003/01/23 07:40:17 $
- * IPPL_VERSION_ID: $Id: addheaderfooter,v 1.1.1.1 2003/01/23 07:40:17 adelmann Exp $ 
+ * IPPL_VERSION_ID: $Id: addheaderfooter,v 1.1.1.1 2003/01/23 07:40:17 adelmann Exp $
  ***************************************************************************/
 
 
@@ -344,7 +344,7 @@ int main(int argc, char *argv[]){
       }
 
 
-  msg << "Particle at " << xi << " beign pushed by dL= " << hr[0] << endl;   
+  msg << "Particle at " << xi << " beign pushed by dL= " << hr[0] << endl;
 
   P->R[0]  = xi;
   Vector_t xf = xi;
@@ -367,5 +367,4 @@ int main(int argc, char *argv[]){
 
 
 
-  */
-
+  */
\ No newline at end of file
diff --git a/ippl/test/particle/CMakeLists.txt b/ippl/test/particle/CMakeLists.txt
index 7cfa03080107da10eee20d53693c6433e21adb72..2676a5b31bb645e9b9551128e6f1453bd1d5225f 100644
--- a/ippl/test/particle/CMakeLists.txt
+++ b/ippl/test/particle/CMakeLists.txt
@@ -76,5 +76,3 @@ set_source_files_properties(SOURCE PIC3d.cpp p3m3d.cpp
 #add_executable (test-scatter-1 test-scatter-1.cpp)
 #target_link_libraries (test-scatter-1 ${IPPL_LIBS})
 
-
-
diff --git a/ippl/test/particle/ChargedParticleFactory.hpp b/ippl/test/particle/ChargedParticleFactory.hpp
index 7d590fc967211625afd7bd5e7e5ef9c995a850ab..0fda9123eb5b914cece93e132b2f4ed251d9ac56 100644
--- a/ippl/test/particle/ChargedParticleFactory.hpp
+++ b/ippl/test/particle/ChargedParticleFactory.hpp
@@ -86,8 +86,8 @@ void createParticleDistribution(Particles & P, std::string distribution, unsigne
 			}
 
 		}
-		if (type == RANDOM) {	
-			std::cout << "SAMPLING RANDOM DISTRIBUTION" << std::endl;					
+		if (type == RANDOM) {
+			std::cout << "SAMPLING RANDOM DISTRIBUTION" << std::endl;
 			//create n particles within a sphere of radius R around source and charge 1/n
 			P->create(count);
 			std::default_random_engine generator;
@@ -153,7 +153,7 @@ void createParticleDistribution(Particles & P, std::string distribution, unsigne
 		}
 
 		if (type == EVEN) {
-			std::cout << "SAMPLING EVEN DISTRIBUTION" << std::endl;					
+			std::cout << "SAMPLING EVEN DISTRIBUTION" << std::endl;
 			P->create(count);
 			std::default_random_engine generator;
 			//uniform distributed between 0 and 1
@@ -167,7 +167,7 @@ void createParticleDistribution(Particles & P, std::string distribution, unsigne
 
 			for (unsigned i = 0; i<count; ++i) {
 				Vektor<double, 3> X(uni(),uni(),uni());
-				Vektor<double, 3> pos = X;							
+				Vektor<double, 3> pos = X;
 				Vektor<double, 3> vel(normal(),normal(),normal());
 				//Vektor<double, 3> vel(0,0,0);
 				P->Q[index]=qi;
@@ -177,7 +177,7 @@ void createParticleDistribution(Particles & P, std::string distribution, unsigne
 
 		if (type == MANUAL) {
 
-			std::cout << "SAMPLING MANUAL DISTRIBUTION" << std::endl;					
+			std::cout << "SAMPLING MANUAL DISTRIBUTION" << std::endl;
 			for (unsigned i = 0; i<count; ++i) {
 				std::cout << "please give coordinates of particle " << i << std::endl;
 				double x,y,z;
@@ -195,11 +195,11 @@ void createParticleDistribution(Particles & P, std::string distribution, unsigne
 		}
 
 		if (type == LINE) {
-			std::cout << "SAMPLING LINE DISTRIBUTION" << std::endl;		
+			std::cout << "SAMPLING LINE DISTRIBUTION" << std::endl;
 			P->create(count);
 			std::default_random_engine generator;
 			//uniform distributed between 0 and 1
-			std::uniform_real_distribution<double> unidistribution(extend_l[0],extend_r[0]);    
+			std::uniform_real_distribution<double> unidistribution(extend_l[0],extend_r[0]);
 			std::normal_distribution<double> normaldist(1,.5);
 
 			auto uni = std::bind(unidistribution, generator);
@@ -208,7 +208,7 @@ void createParticleDistribution(Particles & P, std::string distribution, unsigne
 			for (unsigned i = 0; i<count; ++i) {
 				Vektor<double, 3> X(0,0,uni()); //place all particles on z axis
 				Vektor<double, 3> vel(0,0,normal()); //normal velocity distribution in z dir
-				Vektor<double, 3> pos = X;							
+				Vektor<double, 3> pos = X;
 				P->Q[index]=qi;
 				//P->v[index]=vel;
 				//P->ID[index]=i;
@@ -260,7 +260,7 @@ void createParticleDistributionTwoStream(Particles & P, Vektor<double,3> extend_
 								double f = (1./(30*M_PI))*exp(-0.5*v2)*(1.+alpha*cos(k*pos[2]))*(1.0 + 5.0*vel[2]*vel[2]);
 								//std::cout << "f = " << f << std::endl;
 								double m = hx[0]*hv[0]*hx[1]*hv[1]*hx[2]*hv[2]*f;
-								if(m>thresh){								
+								if(m>thresh){
 									double q =-m;
 									P->create(1);
 									P->Q[index] = q;
@@ -314,11 +314,11 @@ void createParticleDistributionLandau(Particles & P, Vektor<double,3> extend_l,V
 							for (int kv =0; kv<Nv[2]; ++kv) {
 								Vektor<double,3>vel = Vektor<double,3>(iv+.5,jv+.5,kv+.5)*hv+Vmin;
 								double v2 = vel[0]*vel[0]+vel[1]*vel[1]+vel[2]*vel[2];
-								
+
 								double f = (1./(2.*M_PI*sqrt(2.*M_PI)))*exp(-0.5*v2)*(1.+alpha*(cos(k*pos[2])+cos(k*pos[1])+cos(k*pos[0])));
-								
+
 								double m = hx[0]*hv[0]*hx[1]*hv[1]*hx[2]*hv[2]*f;
-								if(m>thresh){								
+								if(m>thresh){
 									double q = -m;
 									P->create(1);
 									P->Q[index] = q;
@@ -335,7 +335,7 @@ void createParticleDistributionLandau(Particles & P, Vektor<double,3> extend_l,V
 				}
 			}
 		}
-	}	
+	}
 	P->update();
 }
 
@@ -369,12 +369,12 @@ void createParticleDistributionRecurrence(Particles & P, Vektor<double,3> extend
 							for (int kv =0; kv<Nv[2]; ++kv) {
 								Vektor<double,3>vel = Vektor<double,3>(iv+.5,jv+.5,kv+.5)*hv+Vmin;
 								double v2 = vel[0]*vel[0]+vel[1]*vel[1]+vel[2]*vel[2];
-								
+
 								//Free-streaming:
 								double f = alpha*(1./(2.*M_PI*sqrt(2.*M_PI)))*exp(-0.5*v2)*(cos(k*pos[2])+cos(k*pos[1])+cos(k*pos[0]));
-								
+
 								double m = hx[0]*hv[0]*hx[1]*hv[1]*hx[2]*hv[2]*f;
-								if(m>thresh){								
+								if(m>thresh){
 									double q = -m;
 									P->create(1);
 									P->Q[index] = q;
@@ -391,7 +391,7 @@ void createParticleDistributionRecurrence(Particles & P, Vektor<double,3> extend
 				}
 			}
 		}
-	}	
+	}
 	P->update();
 }
 
@@ -401,17 +401,17 @@ void createParticleDistributionMicrobunching(Particles & P, unsigned seedID=0 )
 	std::cout << "Initializing Microbunching" << std::endl;
 	//generate seed sequence
 	std::seed_seq seq{1,2,3,4,5};
-    	std::vector<std::uint32_t> seeds(50);
-    	seq.generate(seeds.begin(), seeds.end());
+	std::vector<std::uint32_t> seeds(50);
+	seq.generate(seeds.begin(), seeds.end());
+
 
-		
 	std::default_random_engine generator(seeds[seedID]);
 	std::cout << "The seed value chosen is =" << seeds[seedID] << std::endl;
 	std::cout << std::setprecision(20);
 	P->total_charge=0;
 	//Number of particles is set fixed here, TODO change this!
 	//unsigned Nparticle = 2.49835e6;
-	
+
 	unsigned Nparticle=P->Npart;
 	std::cout << "charge per particle [e] = " << P->q << std::endl;
 	//spread of the second order moment
@@ -423,14 +423,14 @@ void createParticleDistributionMicrobunching(Particles & P, unsigned seedID=0 )
 	//the momenta are normally distributed with std deviation sigma_px
 	std::normal_distribution<double> normdistpx(0,sigmaPx);
 	std::normal_distribution<double> normdistpy(0,sigmaPx);
-	
+
 	//longitudinal momenta
 	std::cout << "gamma=" << P->gamma << std::endl;
 	std::cout << "deltagamma=" << P->deltagamma << std::endl;
 	std::cout << "sigmaP=" << P->deltagamma/P->gamma << std::endl;
 	//std::normal_distribution<double> normdistdeltagamma(0,P->deltagamma);
 	std::normal_distribution<double> normdistdeltagamma(0,P->deltagamma/P->gamma);
-		
+
 	//setup rng for uniform distributions of particles in x,y,z direction
 	std::uniform_real_distribution<double> unidistx(P->extend_l[0],P->extend_r[0]);
 	std::uniform_real_distribution<double> unidisty(P->extend_l[1],P->extend_r[1]);
@@ -462,12 +462,12 @@ std::cout<< P->beta0 << std::endl;
 /*
 			for (int j=0;j<10;++j){
 				//std::cout << std::exp(-imag*k) << P->b0[j] << std::endl;
-				P->b0[j]+=std::exp(-imag*k*(z+P->R[i][0]*sin(P->theta[j])));			
+				P->b0[j]+=std::exp(-imag*k*(z+P->R[i][0]*sin(P->theta[j])));
 			}
 */
 		}
 	}
-	//transform computational domain from lab to beamframe 
+	//transform computational domain from lab to beamframe
 //	for (int j=0;j<10;++j)
 //		P->b0[j]/=Nparticle;
 	P->extend_r[2]=P->gamma*P->extend_r[2];
@@ -480,11 +480,11 @@ template<typename Particles>
 void createParticleDistributionEquiPart(Particles & P, Vektor<double,3> extend_l, Vektor<double,3> extend_r, double beam_length, double part_density,double qi, double mi, int seed=0) {
 	std::cout << "Initializing Equipartitioning" << std::endl;
 	P->total_charge=0;
-	const double c = 299792458000;	
-	unsigned Nparticle = beam_length*beam_length*beam_length*part_density; 
+	const double c = 299792458000;
+	unsigned Nparticle = beam_length*beam_length*beam_length*part_density;
 	std::cout << "Number of particles = " << Nparticle << std::endl;
 	//the momenta are normally distributed with std deviation sigma_px
-		
+
 	std::default_random_engine generator(seed);
 	//setup rng for uniform distributions of particles in x,y,z direction
 	std::uniform_real_distribution<double> unidist_spacial(-beam_length/2.,beam_length/2.);
@@ -514,12 +514,12 @@ template<typename Particles>
 void createParticleDistributionEquiPartSphere(Particles & P, Vektor<double,3> extend_l, Vektor<double,3> extend_r, double beam_length, unsigned Nparts,double qi, double mi, int seed=0) {
 	std::cout << "Initializing Equipartitioning Sphere" << std::endl;
 	P->total_charge=0;
-	const double c = 299792458000;	
-	unsigned Nparticle = Nparts; 
+	const double c = 299792458000;
+	unsigned Nparticle = Nparts;
 	double sphere_radius=beam_length/2.;
 	std::cout << "Number of particles = " << Nparticle << std::endl;
 	//the momenta are normally distributed with std deviation sigma_px
-		
+
 	std::default_random_engine generator(seed);
 	std::normal_distribution<double> normdistribution(0,1.0);
 	auto normal = std::bind(normdistribution, generator);
@@ -557,13 +557,13 @@ void createParticleDistributionEquiPartSphere(Particles & P, Vektor<double,3> ex
 template<typename Particles>
 void createParticleDistributionHeating(Particles & P, Vektor<double,3> extend_l, Vektor<double,3> extend_r, double beam_radius, unsigned Nparts,double qi, double mi) {
     Inform msg("p3m3dHeating ");
-    
+
     msg << "Initializing Cold Sphere" << endl;
 	P->total_charge=0;
-	unsigned Nparticle = Nparts; 
+	unsigned Nparticle = Nparts;
 
 	//the momenta are normally distributed with std deviation sigma_px
-		
+
 	std::default_random_engine generator(0);
 	std::normal_distribution<double> normdistribution(0,1.0);
 	auto normal = std::bind(normdistribution, generator);
@@ -596,9 +596,9 @@ void createParticleDistributionHeating(Particles & P, Vektor<double,3> extend_l,
 template<typename Particles>
 void createParticleDistributionPerformance(Particles & P, Vektor<double,3> extend_l, Vektor<double,3> extend_r, unsigned Nparts,double qi, double mi, double vMin, double vMax) {
 	P->total_charge=0;
-	unsigned Nparticle = Nparts; 
+	unsigned Nparticle = Nparts;
 	//the momenta are normally distributed with std deviation sigma_px
-		
+
 	std::default_random_engine generator(0);
 	std::uniform_real_distribution<double> unidistributionVel(vMin,vMax);
 	std::uniform_real_distribution<double> unidistributionX(extend_l[0],extend_r[0]);
diff --git a/ippl/test/particle/PIC3d-timing-1.cpp b/ippl/test/particle/PIC3d-timing-1.cpp
index 2497b249df3e9a52af53c9d28940f8d2b85abe9b..aaaabb063a8ae0ae4c6c00e101a7097e05457291 100755
--- a/ippl/test/particle/PIC3d-timing-1.cpp
+++ b/ippl/test/particle/PIC3d-timing-1.cpp
@@ -2,9 +2,9 @@
 /***************************************************************************
  *
  * The IPPL Framework
- * 
- * This program was prepared by PSI. 
- * All rights in the program are reserved by PSI. 
+ *
+ * This program was prepared by PSI.
+ * All rights in the program are reserved by PSI.
  * Neither PSI nor the author(s)
  * makes any warranty, express or implied, or assumes any liability or
  * responsibility for the use of this software
@@ -15,14 +15,14 @@
 
 /***************************************************************************
 
- This test program sets up a simple sine-wave electric field in 3D, 
+ This test program sets up a simple sine-wave electric field in 3D,
    creates a population of particles with random q/m values (charge-to-mass
    ratio) and velocities, and then tracks their motions in the static
-   electric field using nearest-grid-point interpolation. 
+   electric field using nearest-grid-point interpolation.
 
 Usage:
 
- 
+
  $MYMPIRUN -np 2 PIC3d 128 128 128 10000 10 NGP OOP GUARDCELLS --processes 2 --commlib mpi
 
 ***************************************************************************/
@@ -39,7 +39,7 @@ Usage:
 // dimension of our positions
 const unsigned Dim = 3;
 
-// some typedefs 
+// some typedefs
 typedef ParticleSpatialLayout<double,Dim>::SingleParticlePos_t Vector_t;
 typedef ParticleSpatialLayout<double,Dim> playout_t;
 typedef UniformCartesian<Dim,double> Mesh_t;
@@ -68,7 +68,7 @@ public:
   typename PL::ParticlePos_t E;  // electric field at particle position
   typename PL::ParticlePos_t B;  // magnetic field at particle position
 
-  ChargedParticles(PL* pl, BC_t bc, InterPol_t interpol, e_dim_tag decomp[Dim], bool gCells) : 
+  ChargedParticles(PL* pl, BC_t bc, InterPol_t interpol, e_dim_tag decomp[Dim], bool gCells) :
     IpplParticleBase<PL>(pl),
     bco_m(bc),
     interpol_m(interpol),
@@ -92,7 +92,7 @@ public:
     particles as in the OOO case.
   */
 
-  ChargedParticles(PL* pl, BC_t bc, InterPol_t interpol, Vector_t hr, Vector_t rmin, Vector_t rmax, e_dim_tag decomp[Dim], bool gCells) : 
+  ChargedParticles(PL* pl, BC_t bc, InterPol_t interpol, Vector_t hr, Vector_t rmin, Vector_t rmax, e_dim_tag decomp[Dim], bool gCells) :
     IpplParticleBase<PL>(pl),
     bco_m(bc),
     interpol_m(interpol),
@@ -118,14 +118,14 @@ public:
       setBCAllOpen();
     else if (bco_m == PPP)
       setBCAllPeriodic();
-    else 
+    else
       setBCOOP();
-  } 
+  }
 
   inline const Mesh_t& getMesh() const { return this->getLayout().getLayout().getMesh(); }
-  
+
   inline Mesh_t& getMesh() { return this->getLayout().getLayout().getMesh(); }
-    
+
   inline const FieldLayout_t& getFieldLayout() const {
     return dynamic_cast<FieldLayout_t&>( this->getLayout().getLayout().getFieldLayout());
   }
@@ -148,12 +148,12 @@ public:
       scatterCIC();
     else
       scatterNGP();
-    
+
     /*
       now sum over all gridpoints ... a bit nasty !
 
     */
-    
+
     Field<double,Dim> tmpf;
     NDIndex<Dim> domain = getFieldLayout().getDomain();
 
@@ -176,7 +176,7 @@ public:
 		Q +=  tmpf.localElement(elem);
 	    }
         }
-	
+
     }
     reduce(Q,Q,OpAddAssign());
     m << "sum(qm)= " << initialQ << " sum(EFDMag)= " << sum(EFDMag_m) << endl;
@@ -184,21 +184,21 @@ public:
   }
   
   void myUpdate() {
-    
+
     double hz   = hr_m[2];
     double zmin = rmin_m[2];
     double zmax = rmax_m[2];
 
     if (bco_m != PPP) {
       bounds(this->R, rmin_m, rmax_m);
-                  
-      NDIndex<Dim> domain = this->getFieldLayout().getDomain(); 
-      
+
+      NDIndex<Dim> domain = this->getFieldLayout().getDomain();
+
       for(int i=0; i<Dim; i++)
 	nr_m[i] = domain[i].length();
-	
+
       for(int i=0; i<Dim; i++)
-	  hr_m[i] = (rmax_m[i] - rmin_m[i]) / (nr_m[i] - 1.0); 
+	  hr_m[i] = (rmax_m[i] - rmin_m[i]) / (nr_m[i] - 1.0);
 
       if (bco_m == OOP) {
 	rmin_m[2] = zmin;
@@ -217,7 +217,7 @@ public:
 	  EFD_m.initialize(getMesh(), getFieldLayout(), vbc_m);
 	  EFDMag_m.initialize(getMesh(), getFieldLayout(), bc_m);
       }
-    } 
+    }
     else {
       if(fieldNotInitialized_m) {
 	fieldNotInitialized_m=false;
@@ -244,14 +244,14 @@ public:
     double *globalPartPerNode = new double[Ippl::getNodes()];
     for (int i=0; i<Ippl::getNodes(); i++) {
       partPerNode[i] = globalPartPerNode[i] = 0.0;
-    
+
     }
     partPerNode[Ippl::myNode()] = this->getLocalNum();
 
     reduce(partPerNode,partPerNode+Ippl::getNodes(),globalPartPerNode,OpAddAssign());
-    
+
     for (int i=0; i<Ippl::getNodes(); i++)
-      m << "Node " << i << " has " 
+      m << "Node " << i << " has "
 	<<   globalPartPerNode[i]/this->getTotalNum()*100.0 << " \% of the total particles " << endl;
   }
 
@@ -260,29 +260,29 @@ public:
 
   void initFields() {
     Inform m("initFields ");
-    
+
     NDIndex<Dim> domain = getFieldLayout().getDomain();
-    
+
     for(int i=0; i<Dim; i++)
       nr_m[i] = domain[i].length();
-  
+
     int nx = nr_m[0];
     int ny = nr_m[1];
     int nz = nr_m[2];
 
-    double phi0 = 0.1*nx;            
+    double phi0 = 0.1*nx;
 
     m << "rmin= " << rmin_m << " rmax= " << rmax_m << " h= " << hr_m << " n= " << nr_m << endl;
-    
+
     Index I(nx), J(ny), K(nz);
-  
+
     assign(EFD_m[I][J][K](0), -2.0*pi*phi0/nx * cos(2.0*pi*(I+0.5)/nx) * cos(4.0*pi*(J+0.5)/ny) * cos(pi*(K+0.5)/nz));
 
     assign(EFD_m[I][J][K](1),  4.0*pi*phi0/ny * sin(2.0*pi*(I+0.5)/nx) * sin(4.0*pi*(J+0.5)/ny));
 
     assign(EFD_m[I][J][K](2),  4.0*pi*phi0/ny * sin(2.0*pi*(I+0.5)/nx) * sin(4.0*pi*(J+0.5)/ny));
 
-    assign(EFDMag_m[I][J][K], 
+    assign(EFDMag_m[I][J][K],
 	   EFD_m[I][J][K](0) * EFD_m[I][J][K](0) +
 	   EFD_m[I][J][K](1) * EFD_m[I][J][K](1) +
 	   EFD_m[I][J][K](2) * EFD_m[I][J][K](2));
@@ -311,29 +311,29 @@ public:
       tmp.push_back(this->P[i](1));
       tmp.push_back(this->P[i](2));
     }
-    
+
     if(Ippl::myNode() == 0) {
       ofstream ostr;
       string Fn;
       char numbuf[6];
-      sprintf(numbuf, "%05d", idx);  
+      sprintf(numbuf, "%05d", idx);
       Fn = fn  + string(numbuf) + ".dat";
       ostr.open(Fn.c_str(), ios::out );
       ostr.precision(15);
       ostr.setf(ios::scientific, ios::floatfield);
-  
+
       ostr << " x, px, y, py t, pt, id, node" << endl;
 
       unsigned int dataBlocks=0;
       double x,y,z,px,py,pz,id;
       unsigned  vn;
-      
+
       for (unsigned i=0; i < tmp.size(); i+=7)
 	ostr << tmp[i+1] << " " << tmp[i+4] << " " << tmp[i+2]  << " " \
 	     << tmp[i+5] << " " << tmp[i+3] << " " << tmp[i+6]  << " " \
 	     << tmp[i]   << " " << Ippl::myNode() << endl;
-      
-      int notReceived =  Ippl::getNodes() - 1; 
+
+      int notReceived =  Ippl::getNodes() - 1;
       while (notReceived > 0) {
 	int node = COMM_ANY_NODE;
 	Message* rmsg =  Ippl::Comm->receive_block(node, tag);
@@ -364,10 +364,10 @@ public:
       dataBlocks = tmp.size();
       smsg->put(dataBlocks);
       smsg->put(Ippl::myNode());
-      for (unsigned i=0; i < tmp.size(); i++) 
+      for (unsigned i=0; i < tmp.size(); i++)
 	smsg->put(tmp[i]);
-      bool res = Ippl::Comm->send(smsg, 0, tag);	
-      if (! res) 
+      bool res = Ippl::Comm->send(smsg, 0, tag);
+      if (! res)
 	ERRORMSG("Ippl::Comm->send(smsg, 0, tag) failed " << endl;);
     }
   }
@@ -381,13 +381,13 @@ private:
       vbc_m[i] = new ZeroFace<Vector_t,Dim,Mesh_t,Center_t>(i);
     }
   }
-  
+
   inline void setBCAllPeriodic() {
     for (int i=0; i < 2*Dim; i++) {
       this->getBConds()[i] = ParticlePeriodicBCond;
       bc_m[i]  = new PeriodicFace<double  ,Dim,Mesh_t,Center_t>(i);
       vbc_m[i] = new PeriodicFace<Vector_t,Dim,Mesh_t,Center_t>(i);
-    }  
+    }
   }
 
   inline void setBCOOP() {
@@ -399,8 +399,8 @@ private:
     for (int i= 2*Dim - 2; i < 2*Dim; i++) {
       bc_m[i]  = new PeriodicFace<double  ,Dim,Mesh_t,Center_t>(i);
       vbc_m[i] = new PeriodicFace<Vector_t,Dim,Mesh_t,Center_t>(i);
-      this->getBConds()[i] = ParticlePeriodicBCond;    
-    }  
+      this->getBConds()[i] = ParticlePeriodicBCond;
+    }
   }
 
   inline void gatherNGP() {
@@ -429,12 +429,12 @@ private:
 
   Field<Vektor<double,Dim>,Dim> EFD_m;
   Field<double,Dim> EFDMag_m;
-  
+
   BConds<double,Dim,Mesh_t,Center_t> bc_m;
   BConds<Vector_t,Dim,Mesh_t,Center_t> vbc_m;
 
   Vektor<int,Dim> nr_m;
-    
+
   Vector_t hr_m;
   Vector_t rmin_m;
   Vector_t rmax_m;
@@ -443,7 +443,7 @@ private:
   InterPol_t interpol_m;
   bool fieldNotInitialized_m;
   bool doRepart_m;
-  bool withGuardCells_m;  
+  bool withGuardCells_m;
   e_dim_tag decomp_m[Dim];
 
 };
@@ -462,7 +462,7 @@ int main(int argc, char *argv[]){
   Inform msg(argv[0]);
   Inform msg2all(argv[0],INFORM_ALL_NODES);
 
-  IpplTimings::startTimer(mainTimer); 
+  IpplTimings::startTimer(mainTimer);
   Vektor<int,Dim> nr(atoi(argv[1]),atoi(argv[2]),atoi(argv[3]));
 
   const unsigned int totalP = atoi(argv[4]);
@@ -473,26 +473,26 @@ int main(int argc, char *argv[]){
     myInterpol = CIC;
   else
     myInterpol = NGP;
-  
+
   bool gCells;
   gCells =  (string(argv[8])==string("GUARDCELLS"));
-  
+
   msg << "Particle test PIC3d " << endl;
   msg << "nt " << nt << " Np= " << totalP << " grid = " << nr <<endl;
-  
+
   if (myInterpol==CIC)
-    msg << "Cloud in cell (CIC) interpolation selected" << endl; 
+    msg << "Cloud in cell (CIC) interpolation selected" << endl;
   else
-    msg << "Nearest grid point (NGP) interpolation selected" << endl; 
-  
+    msg << "Nearest grid point (NGP) interpolation selected" << endl;
+
   if (gCells)
       msg << "Using guard cells" << endl;
   else
       msg << "Not using guard cells" << endl;
 
-  BC_t myBC;  
+  BC_t myBC;
   if (string(argv[7])==string("OOO")) {
-    myBC = OOO; // open boundary 
+    myBC = OOO; // open boundary
     msg << "BC == OOO" << endl;
   }
   else if (string(argv[7])==string("OOP")) {
@@ -500,7 +500,7 @@ int main(int argc, char *argv[]){
     msg << "BC == OOP" << endl;
   }
   else {
-    myBC = PPP; // all periodic 
+    myBC = PPP; // all periodic
     msg << "BC == PPP" << endl;
   }
 
@@ -525,7 +525,7 @@ int main(int argc, char *argv[]){
 
   for (int d=0; d < Dim; ++d)
       decomp[d] = (d == serialDim) ? SERIAL : PARALLEL;
-  
+
   // create mesh and layout objects for this problem domain
   mesh          = new Mesh_t(domain);
   FL            = new FieldLayout_t(*mesh, decomp);
@@ -548,28 +548,28 @@ int main(int argc, char *argv[]){
   // and distribute to others
 
   unsigned long int nloc = totalP / Ippl::getNodes();
-  
-  IpplTimings::startTimer(part_creation_timer); 
+
+  IpplTimings::startTimer(part_creation_timer);
   P->create(nloc);
   for (unsigned long int i = 0; i< nloc; i++) {
     for (int d = 0; d<3; d++)
       P->R[i](d) =  IpplRandom() * nr[d];
   }
-  IpplTimings::stopTimer(part_creation_timer);  
+  IpplTimings::stopTimer(part_creation_timer);
 
   double q = 1.0/totalP;
-  
+
   // random initialization for charge-to-mass ratio
 
   IpplTimings::startTimer(assign_timer);
   assign(P->qm,q);
   IpplTimings::stopTimer(assign_timer);
- 
+
   msg << "particles created and initial conditions assigned " << endl;
-  
+
   // redistribute particles based on spatial layout
   IpplTimings::startTimer(part_update_timer);
-  P->myUpdate(); 
+  P->myUpdate();
   IpplTimings::stopTimer(part_update_timer);
 
   msg << "initial update and initial mesh done .... Q= " << sum(P->qm) << endl;
@@ -615,7 +615,7 @@ int main(int argc, char *argv[]){
     msg << "Finished iteration " << it << " - min/max r and h " << P->getRMin() << P->getRMax() << P->getHr() << endl;
   }
   Ippl::Comm->barrier();
-  IpplTimings::stopTimer(mainTimer); 
+  IpplTimings::stopTimer(mainTimer);
   IpplTimings::print();
   msg << "Particle test PIC3d: End." << endl;
   return 0;
@@ -624,6 +624,5 @@ int main(int argc, char *argv[]){
 /***************************************************************************
  * $RCSfile: addheaderfooter,v $   $Author: adelmann $
  * $Revision: 1.1.1.1 $   $Date: 2003/01/23 07:40:17 $
- * IPPL_VERSION_ID: $Id: addheaderfooter,v 1.1.1.1 2003/01/23 07:40:17 adelmann Exp $ 
- ***************************************************************************/
-
+ * IPPL_VERSION_ID: $Id: addheaderfooter,v 1.1.1.1 2003/01/23 07:40:17 adelmann Exp $
+ ***************************************************************************/
\ No newline at end of file
diff --git a/ippl/test/particle/VTKFieldWriterParallel.hpp b/ippl/test/particle/VTKFieldWriterParallel.hpp
index 934d528be9f8334b8186c54fc1bf878cd384cfbe..4d9d60b936edb333134c84683c562477fa01bfac 100644
--- a/ippl/test/particle/VTKFieldWriterParallel.hpp
+++ b/ippl/test/particle/VTKFieldWriterParallel.hpp
@@ -28,8 +28,8 @@ void dumpVTKVector( FieldType & f, const ParticleType & p,int iteration = 0, std
 	vtkout << "DATASET STRUCTURED_POINTS" << std::endl;
 	vtkout << "DIMENSIONS " << nx << " " << ny << " " << nz << std::endl;
 	//vtkout << "ORIGIN 0 0 0" << std::endl;
-	//vtkout << "ORIGIN "<< p->extend_l[0]+.5*dx <<" " << p->extend_l[1]+.5*dy << " " << p->extend_l[2]+.5*dy << std::endl;			
-	vtkout << "ORIGIN "<< p->extend_l[0]+.5*dx+lDom[0].first()*dx <<" " << p->extend_l[1]+.5*dy+lDom[1].first()*dy << " " << p->extend_l[2]+.5*dy+lDom[2].first()*dz << std::endl;			
+	//vtkout << "ORIGIN "<< p->extend_l[0]+.5*dx <<" " << p->extend_l[1]+.5*dy << " " << p->extend_l[2]+.5*dy << std::endl;
+	vtkout << "ORIGIN "<< p->extend_l[0]+.5*dx+lDom[0].first()*dx <<" " << p->extend_l[1]+.5*dy+lDom[1].first()*dy << " " << p->extend_l[2]+.5*dy+lDom[2].first()*dz << std::endl;
 	vtkout << "SPACING " << dx << " " << dy << " " << dz << std::endl;
 	vtkout << "POINT_DATA " << nx*ny*nz << std::endl;
 	vtkout << "VECTORS Vector_Value float" << std::endl;
@@ -77,8 +77,8 @@ void dumpVTKScalar( FieldType & f, const ParticleType & p,int iteration = 0, std
 	vtkout << "DIMENSIONS " << nx << " " << ny << " " << nz << std::endl;
 	//vtkout << "DIMENSIONS " << lDom[0].length()  << " " <<  lDom[1].length()  << " " <<  lDom[2].length()  << std::endl;
 	//vtkout << "ORIGIN 0 0 0" << std::endl;
-	vtkout << "ORIGIN "<< p->extend_l[0]+.5*dx+lDom[0].first()*dx <<" " << p->extend_l[1]+.5*dy+lDom[1].first()*dy << " " << p->extend_l[2]+.5*dy+lDom[2].first()*dz << std::endl;			
-	//vtkout << "ORIGIN "<< p->rmin_m[0]<<" " << p->rmin_m[1] << " " << p->rmin_m[2] << std::endl;			
+	vtkout << "ORIGIN "<< p->extend_l[0]+.5*dx+lDom[0].first()*dx <<" " << p->extend_l[1]+.5*dy+lDom[1].first()*dy << " " << p->extend_l[2]+.5*dy+lDom[2].first()*dz << std::endl;
+	//vtkout << "ORIGIN "<< p->rmin_m[0]<<" " << p->rmin_m[1] << " " << p->rmin_m[2] << std::endl;
 	vtkout << "SPACING " << dx << " " << dy << " " << dz << std::endl;
 	vtkout << "POINT_DATA " << nx*ny*nz << std::endl;
 	vtkout << "SCALARS Scalar_Value float" << std::endl;
@@ -117,25 +117,25 @@ void dumpVTKScalar( FieldType & f, const ParticleType & p,int iteration = 0, std
 
 template<typename ParticleType>
 void dumpParticlesOPAL( const ParticleType & p, int iteration=0) {
-    
+
   //    std::cout <<" Node " << std::to_string(Ippl::myNode()) << " has cached particles : " << p->getGhostNum() << std::endl;
     std::ofstream csvout;
     csvout.precision(10);
     csvout.setf(std::ios::scientific, std::ios::floatfield);
-    
+
     std::stringstream fname;
     fname << "data/dist";
     fname << std::setw(1) << Ippl::myNode();
     fname << std::setw(5) << "_it_";
     fname << std::setw(4) << std::setfill('0') << iteration;
     fname << ".dat";
-    
+
     // open a new data file for this iteration
     // and start with header
     csvout.open(fname.str().c_str(), std::ios::out);
 
     csvout << p->getLocalNum() << std::endl;
-    
+
     for (unsigned i=0; i<p->getLocalNum()+p->getGhostNum(); ++i) {
         csvout << p->R[i][0] << "\t" << p->v[i][0] << "\t" << p->R[i][1] << "\t" << p->v[i][1]<< "\t" << p->R[i][2]<< "\t" << p->v[i][2] <<  std::endl;
     }
@@ -172,7 +172,7 @@ void dumpParticlesCSV( const ParticleType & p, int iteration=0) {
 
 		csvout << p->R[i][0] << "," << p->R[i][1] << "," << p->R[i][2] << "," << p->Q[i] << "," << sqrt(p->EF[i][0]*p->EF[i][0]+p->EF[i][1]*p->EF[i][1]+p->EF[i][2]*p->EF[i][2]) << "," << p->ID[i]<< "," << p->v[i][0]<< "," << p->v[i][1]<< "," << p->v[i][2] << "," << distributionf << std::endl;
 	}
-	csvout << std::endl;			
+	csvout << std::endl;
 
 	// close the output file for this iteration:
 	csvout.close();
@@ -206,11 +206,11 @@ void dumpParticlesCSVp( const ParticleType & p, int iteration=0) {
 			//if(p->R[i][0]>60*1e-6 && p->R[i][0]<120*1e-6 && p->R[i][1]>60*1e-6 && p->R[i][1]<120*1e-6){
 			double zlab=1./p->gamma*p->R[i][2];
 			double pz_lab = p->gamma*p->p[i][2];
-			double pz0=p->beta0*p->gamma*p->m0; 
+			double pz0=p->beta0*p->gamma*p->m0;
 			csvout << p->R[i][0] << "," << p->R[i][1] << "," << p->R[i][2] <<"," << zlab <<","<< zlab+p->R56*pz_lab/pz0 << "," << p->Q[i] << "," << sqrt(p->EF[i][0]*p->EF[i][0]+p->EF[i][1]*p->EF[i][1]+p->EF[i][2]*p->EF[i][2]) << "," << p->ID[i]<< "," << p->p[i][0]<< "," << p->p[i][1]<< "," << p->p[i][2] << ","<< pz_lab << std::endl;
 			//}
 		}
-		csvout << std::endl;			
+		csvout << std::endl;
 
 		// close the output file for this iteration:
 		csvout.close();
@@ -286,10 +286,10 @@ void dumpParticlesCSVp( const ParticleType & p, int iteration=0) {
 
 				for (unsigned i=0; i<p->getLocalNum(); ++i) {
 					csvout << p->R[i][2];
-					if (i!=p->getLocalNum()-1) 
+					if (i!=p->getLocalNum()-1)
 						csvout << ",";
 				}
-				csvout << std::endl;			
+				csvout << std::endl;
 
 				// close the output file for this iteration:
 				csvout.close();
@@ -312,10 +312,10 @@ void dumpParticlesCSVp( const ParticleType & p, int iteration=0) {
 
 				for (unsigned i=0; i<p->getLocalNum(); ++i) {
 					csvout << p->EF[i][2];
-					if (i!=p->getLocalNum()-1) 
+					if (i!=p->getLocalNum()-1)
 						csvout << ",";
 				}
-				csvout << std::endl;			
+				csvout << std::endl;
 
 				// close the output file for this iteration:
 				csvout.close();
diff --git a/ippl/test/particle/p3m3dHeating.cpp b/ippl/test/particle/p3m3dHeating.cpp
index ffc0b613144bb7b7628e1dc3021a7e7d3c220b94..2a4f50cc851e4f442eac89243f63b1eeed8c5853 100644
--- a/ippl/test/particle/p3m3dHeating.cpp
+++ b/ippl/test/particle/p3m3dHeating.cpp
@@ -106,7 +106,7 @@ public:
     ParticleAttrib<Vector_t> 	EF;
     ParticleAttrib<Vector_t>	v; //velocity of the particles
     ParticleAttrib<int>	ID; //velocity of the particles
-    
+
     ChargedParticles(PL* pl, Vektor<double,3> nr, e_dim_tag decomp[Dim],Vektor<double,3> extend_l_, Vektor<double,3> extend_r_) :
     IpplParticleBase<PL>(pl),
     nr_m(nr),
@@ -119,12 +119,12 @@ public:
         this->addAttribute(EF);
         this->addAttribute(v);
         this->addAttribute(ID);
-        
+
         for (unsigned int i = 0; i < 2 * Dim; ++i) {
             //use periodic boundary conditions for the particles
             this->getBConds()[i] = ParticlePeriodicBCond;
             //boundary conditions used for interpolation kernels allow writes to ghost cells
-            
+
             if (Ippl::getNodes()>1) {
                 bc_m[i] = new ParallelInterpolationFace<double, Dim, Mesh_t, Center_t>(i);
                 //std periodic boundary conditions for gradient computations etc.
@@ -138,36 +138,36 @@ public:
                 bcp_m[i] = new PeriodicFace<double, Dim, Mesh_t, Center_t>(i);
             }
         }
-        
+
         for (unsigned int d = 0;d<Dim;++d) {
             rmax_m[d] = extend_r[d];
             rmin_m[d] = extend_l[d];
         }
-        
+
         domain_m = this->getFieldLayout().getDomain();
         lDomain_m = this->getFieldLayout().getLocalNDIndex(); // local domain
-        
+
         //initialize the FFT
         bool compressTemps = true;
         fft_m = new FFT_t(domain_m,compressTemps);
-        
+
         fft_m->setDirectionName(+1, "forward");
         fft_m->setDirectionName(-1, "inverse");
         INFOMSG("INIT FFT DONE"<<endl);
     }
-    
+
     inline const Mesh_t& getMesh() const { return this->getLayout().getLayout().getMesh(); }
-    
+
     inline Mesh_t& getMesh() { return this->getLayout().getLayout().getMesh(); }
-    
+
     inline const FieldLayout_t& getFieldLayout() const {
         return dynamic_cast<FieldLayout_t&>( this->getLayout().getLayout().getFieldLayout());
     }
-    
+
     inline FieldLayout_t& getFieldLayout() {
         return dynamic_cast<FieldLayout_t&>(this->getLayout().getLayout().getFieldLayout());
     }
-    
+
     void update()
     {
         //should only be needed if meshspacing changes -----------
@@ -177,20 +177,20 @@ public:
         this->getMesh().set_meshSpacing(&(hr_m[0]));
         this->getMesh().set_origin(extend_l);
         //--------------------------------------------------------
-        
+
         //init resets the meshes to 0 ?!
         rhocmpl_m.initialize(getMesh(), getFieldLayout(), GuardCellSizes<Dim>(1));
         grncmpl_m.initialize(getMesh(), getFieldLayout(), GuardCellSizes<Dim>(1));
         rho_m.initialize(getMesh(), getFieldLayout(), GuardCellSizes<Dim>(1),bc_m);
         phi_m.initialize(getMesh(), getFieldLayout(), GuardCellSizes<Dim>(1),bcp_m);
         eg_m.initialize(getMesh(), getFieldLayout(), GuardCellSizes<Dim>(1), vbc_m);
-        
+
         domain_m = this->getFieldLayout().getDomain();
         lDomain_m = this->getFieldLayout().getLocalNDIndex();
-        
+
         IpplParticleBase<PL>::update();
     }
-    
+
     void compute_temperature() {
         Inform m("compute_temperature ");
         double loc_temp[Dim]={0.0,0.0,0.0};
@@ -208,9 +208,9 @@ public:
         avg_vel[0]=avg_vel[0]/N;
         avg_vel[1]=avg_vel[1]/N;
         avg_vel[2]=avg_vel[2]/N;
-        
+
         m << "avg_vel[0]= " << avg_vel[0] << " avg_vel[1]= " << avg_vel[1] << " avg_vel[2]= " << avg_vel[2] <<  endl;
-        
+
         for(unsigned long k = 0; k < this->getLocalNum(); ++k) {
 	  for(unsigned i = 0; i < Dim; i++) {
 	    loc_temp[i]   += (this->v[k](i)-avg_vel[i])*(this->v[k](i)-avg_vel[i]);
@@ -222,14 +222,14 @@ public:
         temperature[1]=temperature[1]/N;
         temperature[2]=temperature[2]/N;
     }
-    
+
     void calcMoments() {
         double part[2 * Dim];
-        
+
         double loc_centroid[2 * Dim]={};
         double loc_moment[2 * Dim][2 * Dim]={};
         double moments[2 * Dim][2 * Dim]={};
-        
+
         for(unsigned i = 0; i < 2 * Dim; i++) {
             loc_centroid[i] = 0.0;
             for(unsigned j = 0; j <= i; j++) {
@@ -237,7 +237,7 @@ public:
                 loc_moment[j][i] = loc_moment[i][j];
             }
         }
-        
+
         //double p0=m0*gamma*beta0;
         for(unsigned long k = 0; k < this->getLocalNum(); ++k) {
             part[1] = this->v[k](0);
@@ -246,7 +246,7 @@ public:
             part[0] = this->R[k](0);
             part[2] = this->R[k](1);
             part[4] = this->R[k](2);
-            
+
             for(unsigned i = 0; i < 2 * Dim; i++) {
                 loc_centroid[i]   += part[i];
                 for(unsigned j = 0; j <= i; j++) {
@@ -254,19 +254,19 @@ public:
                 }
             }
         }
-        
+
         for(unsigned i = 0; i < 2 * Dim; i++) {
             for(unsigned j = 0; j < i; j++) {
                 loc_moment[j][i] = loc_moment[i][j];
             }
         }
-        
+
         reduce(&(loc_moment[0][0]), &(loc_moment[0][0]) + 2 * Dim * 2 * Dim,
                &(moments[0][0]), OpAddAssign());
-        
+
         reduce(&(loc_centroid[0]), &(loc_centroid[0]) + 2 * Dim,
                &(centroid_m[0]), OpAddAssign());
-        
+
         for(unsigned i = 0; i < 2 * Dim; i++) {
             for(unsigned j = 0; j <= i; j++) {
                 moments_m[i][j] = moments[i][j];
@@ -274,13 +274,13 @@ public:
             }
         }
     }
-    
-    
+
+
     void computeBeamStatistics() {
         //const size_t locNp = this->getLocalNum();
         const double N =  static_cast<double>(this->getTotalNum());
         const double zero = 0.0;
-        
+
         Vector_t eps2, fac, rsqsum, vsqsum, rvsum;
         for(unsigned int i = 0 ; i < Dim; i++) {
             rmean_m(i) = centroid_m[2 * i] / N;
@@ -291,10 +291,10 @@ public:
                 vsqsum(i) = 0;
             rvsum(i) = moments_m[(2 * i)][(2 * i) + 1] - N * rmean_m(i) * vmean_m(i);
         }
-        
+
         eps2 = (rsqsum * vsqsum - rvsum * rvsum) / (N * N);
         rvsum /= N;
-        
+
         for(unsigned int i = 0 ; i < Dim; i++) {
             rrms_m(i) = sqrt(rsqsum(i) / N);
             vrms_m(i) = sqrt(vsqsum(i) / N);
@@ -303,9 +303,9 @@ public:
             fac(i) = (tmp == 0) ? zero : 1.0 / tmp;
         }
         rvrms_m = rvsum * fac;
-        
+
     }
-    
+
     void calc_kinetic_energy() {
         double loc_kinetic_energy=0;
         double v2;
@@ -315,35 +315,35 @@ public:
         }
         reduce(loc_kinetic_energy,kinetic_energy, OpAddAssign());
     }
-    
+
     void  calc_field_energy() {
         NDIndex<3> elem;
         double cell_volume = hr_m[0]*hr_m[1]*hr_m[2];
         field_energy=0;
         field_energy=0.5*cell_volume*sum(dot(eg_m,eg_m));
-        
+
         rhomax=max(abs(rho_m))/(hr_m[0]*hr_m[1]*hr_m[2]);
         //rhomax=max(rho_m);
         integral_phi_m=0.5*sum(rho_m*phi_m);
     }
-    
+
     void  calc_potential_energy() {
         potential_energy = 0;
         for (unsigned i=0; i<this->getLocalNum(); ++i) {
             potential_energy+=0.5*(Q[i])*Phi[i];
         }
     }
-    
+
     void calc_Amplitude_E(){
         //computes the maximum amplitude in the electric field
         AmplitudeEfield=max(sqrt(dot(eg_m,eg_m)));
         eg_m=eg_m*Vektor<double,3>(0,0,1);
         AmplitudeEFz=max(sqrt(dot(eg_m,eg_m)));
     }
-    
+
     void computeAvgSpaceChargeForces() {
         Inform m("computeAvgSpaceChargeForces ");
-        
+
         const double N =  static_cast<double>(this->getTotalNum());
         double locAvgEF[Dim]={};
         for (unsigned i=0; i<this->getLocalNum(); ++i) {
@@ -351,27 +351,27 @@ public:
             locAvgEF[1]+=fabs(EF[i](1));
             locAvgEF[2]+=fabs(EF[i](2));
         }
-        
+
         reduce(&(locAvgEF[0]), &(locAvgEF[0]) + Dim,
                &(globSumEF[0]), OpAddAssign());
-        
-        
+
+
         m << "globSumEF = " << globSumEF[0] << "\t" << globSumEF[1] << "\t" << globSumEF[2] << endl;
-        
+
         avgEF[0]=globSumEF[0]/N;
         avgEF[1]=globSumEF[1]/N;
         avgEF[2]=globSumEF[2]/N;
 
     }
-    
+
     void applyConstantFocusing(double f,double beam_radius) {
         double focusingForce=sqrt(dot(avgEF,avgEF));
         for (unsigned i=0; i<this->getLocalNum(); ++i) {
             EF[i]+=this->R[i]/beam_radius*f*focusingForce;
         }
     }
-    
-    
+
+
     void calculatePairForces(double interaction_radius, double eps, double alpha) {
         if (interaction_radius>0){
             if (Ippl::getNodes() > 1) {
@@ -384,7 +384,7 @@ public:
             }
         }
     }
-    
+
     void calculateGridForces(double interaction_radius, double alpha, double eps, int it=0, bool normalizeSphere=0) {
         // (1) scatter charge to charge density grid and transform to fourier space
         //this->Q.scatter(this->rho_m, this->R, IntrplTSC_t());
@@ -392,11 +392,11 @@ public:
         this->Q.scatter(this->rho_m, this->R, IntrplCIC_t());
         //this->Q.scatter(this->rho_m, this->R, IntrplNGP_t());
         //dumpVTKScalar(rho_m,this,it,"RhoInterpol");
-        
+
         //rhocmpl_m[domain_m] = rho_m[domain_m];
         rhocmpl_m[domain_m] = rho_m[domain_m]/(hr_m[0]*hr_m[1]*hr_m[2]);
         RhoSum=sum(real(rhocmpl_m));
-        
+
         //std::cout << "total charge in densitty field before ion subtraction is" << sum(real(rhocmpl_m))<< std::endl;
         //std::cout << "max total charge in densitty field before ion subtraction is" << max(real(rhocmpl_m)) << std::endl;
         //subtract the background charge of the ions
@@ -406,23 +406,23 @@ public:
          else
          rhocmpl_m[domain_m]=1.+rhocmpl_m[domain_m];
          */
-        
+
         //std::cout << "total charge in densitty field after ion subtraction is" << sum(real(rhocmpl_m)) << std::endl;
-        
+
         //compute rhoHat and store in rhocmpl_m
         fft_m->transform("inverse", rhocmpl_m);
-        
+
         // (2) compute Greens function in real space and transform to fourier space
         //calcGrealSpace(alpha,eps);
-        
+
         /////////compute G with Index Magic///////////////////
         // Fields used to eliminate excess calculation in greensFunction()
         IField_t grnIField_m[3];
-        
+
         // mesh and layout objects for rho_m
         Mesh_t *mesh_m = &(getMesh());
         FieldLayout_t *layout_m = &(getFieldLayout());
-        
+
         //This loop stores in grnIField_m[i] the index of the ith dimension mirrored at the central axis. e.g. grnIField_m[0]=[(0 1 2 3 ... 3 2 1) ; (0 1 2 3 ... 3 2 1; ...)]
         for (int i = 0; i < 3; ++i) {
             grnIField_m[i].initialize(*mesh_m, *layout_m);
@@ -434,62 +434,62 @@ public:
         Vector_t hrsq(hr_m * hr_m);
         SpecializedGreensFunction<3>::calculate(hrsq, grncmpl_m, grnIField_m, alpha,eps);
         /////////////////////////////////////////////////
-        
+
         //transform G -> Ghat and store in grncmpl_m
         fft_m->transform("inverse", grncmpl_m);
         //multiply in fourier space and obtain PhiHat in rhocmpl_m
         rhocmpl_m *= grncmpl_m;
-        
+
         // (3) Backtransformation: compute potential field in real space and E=-Grad Phi
         //compute electrostatic potential Phi in real space by FFT PhiHat -> Phi and store it in rhocmpl_m
         fft_m->transform("forward", rhocmpl_m);
-        
+
         //take only the real part and store in phi_m (has periodic bc instead of interpolation bc)
         phi_m = real(rhocmpl_m)*hr_m[0]*hr_m[1]*hr_m[2];
         //dumpVTKScalar( phi_m, this,it, "Phi_m") ;
-        
+
         //compute Electric field on the grid by -Grad(Phi) store in eg_m
         eg_m = -Grad1Ord(phi_m, eg_m);
-        
+
         //interpolate the electric field to the particle positions
         EF.gather(eg_m, this->R,  IntrplCIC_t());
         //interpolate electrostatic potenital to the particle positions
         Phi.gather(phi_m, this->R, IntrplCIC_t());
     }
-    
-    
+
+
     Vector_t getRmin() {
         return this->rmin_m;
     }
     Vector_t getRmax() {
         return this->rmax_m;
     }
-    
+
     Vector_t get_hr() { return hr_m;}
-    
+
     void closeH5(){
         H5CloseFile(H5f_m);
     }
-    
+
     void openH5(std::string fn){
         H5f_m = H5OpenFile(fn.c_str(), H5_FLUSH_STEP | H5_O_WRONLY, Ippl::getComm());
     }
-    
-    
-    
+
+
+
     //private:
     BConds<double, Dim, Mesh_t, Center_t> bc_m;
     BConds<double, Dim, Mesh_t, Center_t> bcp_m;
     BConds<Vector_t, Dim, Mesh_t, Center_t> vbc_m;
-    
+
     CxField_t rhocmpl_m;
     CxField_t grncmpl_m;
-    
+
     Field_t rho_m;
     Field_t phi_m;
-    
+
     VField_t eg_m;
-    
+
     Vektor<int,Dim> nr_m;
     Vector_t hr_m;
     Vector_t rmax_m;
@@ -500,7 +500,7 @@ public:
     FieldLayout_t *layout_m;
     NDIndex<Dim> domain_m;
     NDIndex<Dim> lDomain_m;
-    
+
     double kinetic_energy;
     double field_energy;
     double field_energy_gather;
@@ -510,11 +510,11 @@ public:
     double AmplitudeEFz;
     double total_charge;
     double rhomax;
-    
+
     FFT_t *fft_m;
-    
+
     e_dim_tag decomp_m[Dim];
-    
+
     Vektor<int,Dim> Nx;
     Vektor<int,Dim> Nv;
     Vektor<double,Dim> Vmax;
@@ -525,13 +525,13 @@ public:
     FieldLayout2d_t *layout2d_m;
     //TEMP debug variable
     double RhoSum=0;
-    
+
     h5_file_t *H5f_m;
-    
+
     double temperature[Dim];
     double avg_vel[Dim];
-    
-    
+
+
     //Moment calculations:
     /// 6x6 matrix of the moments of the beam
     //FMatrix<double, 2 * Dim, 2 * Dim> moments_m;
@@ -550,11 +550,11 @@ public:
     Vector_t eps_m;
     /// rms correlation
     Vector_t rvrms_m;
-    
-    
+
+
     Vektor<double,Dim> avgEF;
     double globSumEF[Dim];
-    
+
 };
 
 template<class T>
@@ -564,10 +564,10 @@ struct ApplyField {
     {
         Vector_t diff = P.R[i] - (P.R[j]+shift);
         double sqr = 0;
-        
+
         for (unsigned d = 0; d<Dim; ++d)
             sqr += diff[d]*diff[d];
-        
+
         //compute r with softening parameter, unsoftened r is obtained by sqrt(sqr)
         if(sqr!=0) {
             double r = std::sqrt(sqr+eps*eps);
@@ -575,10 +575,10 @@ struct ApplyField {
             if (P.Q[i]!=0 && P.Q[j]!=0) {
                 //compute potential energy
                 double phi =ke*(1.-erf(a*sqrt(sqr)))/r;
-                
+
                 //compute force
                 Vector_t Fij = ke*C*(diff/sqrt(sqr))*((2.*a*exp(-a*a*sqr))/(sqrt(M_PI)*r)+(1.-erf(a*sqrt(sqr)))/(r*r));
-                
+
                 //Actual Force is F_ij multiplied by Qi*Qj
                 //The electrical field on particle i is E=F/q_i and hence:
                 P.EF[i] -= P.Q[j]*Fij;
@@ -599,12 +599,12 @@ int main(int argc, char *argv[]){
     Ippl ippl(argc, argv);
     Inform msg(argv[0]);
     Inform msg2all(argv[0],INFORM_ALL_NODES);
-    
+
     IpplTimings::TimerRef allTimer = IpplTimings::getTimer("AllTimer");
     IpplTimings::startTimer(allTimer);
-    
+
     Vektor<int,Dim> nr;
-    
+
     nr = Vektor<int,Dim>(atoi(argv[1]),atoi(argv[2]),atoi(argv[3]));
     int param = 4;
     double beam_radius =atof(argv[param++]);
@@ -621,55 +621,55 @@ int main(int argc, char *argv[]){
     double mass_per_part =  atof(argv[param++]);
     double focusingForce =  atof(argv[param++]);
     int print_every =  atof(argv[param++]);
-    
-    
+
+
     ///////// setup the initial layout ///////////////////////////////////////
     e_dim_tag decomp[Dim];
     Mesh_t *mesh;
     FieldLayout_t *FL;
     ChargedParticles<playout_t>  *P;
-    
+
     NDIndex<Dim> domain;
     for (unsigned i=0; i<Dim; i++)
         domain[i] = domain[i] = Index(nr[i]+1);
-    
+
     for (unsigned d=0; d < Dim; ++d)
         decomp[d] = PARALLEL;
-    
+
     // create mesh and layout objects for this problem domain
     mesh          = new Mesh_t(domain);
     FL            = new FieldLayout_t(*mesh, decomp);
     playout_t* PL = new playout_t(*FL, *mesh);
-    
+
     PL->setAllCacheDimensions(interaction_radius);
     PL->enableCaching();
-    
+
     /////////// Create the particle distribution /////////////////////////////////////////////////////
     double L = box_length/2.;
     Vektor<double,Dim> extend_l(-L,-L,-L);
     Vektor<double,Dim> extend_r(L,L,L);
-    
+
     Vektor<double,Dim> Vmax(6,6,6);
     P = new ChargedParticles<playout_t>(PL, nr, decomp, extend_l, extend_r);
     createParticleDistributionHeating(P,extend_l,extend_r,beam_radius, Nparticle,charge_per_part,mass_per_part);
-    
+
     //COmpute and write temperature
     P->compute_temperature();
     writeTemperature(P,0);
     /////////////////////////////////////////////////////////////////////////////////////////////
-    
+
     /////// Print mesh informations ////////////////////////////////////////////////////////////
     INFOMSG(P->getMesh() << endl);
     INFOMSG(P->getFieldLayout() << endl);
     msg << endl << endl;
     Ippl::Comm->barrier();
-    
+
     //dumpParticlesCSV(P,0);
-    
+
     INFOMSG(P->getMesh() << endl);
     INFOMSG(P->getFieldLayout() << endl);
     msg << endl << endl;
-    
+
     msg<<"number of particles = " << P->getTotalNum() << endl;
     msg<<"Total charge Q      = " << P->total_charge << endl;
 
@@ -677,22 +677,22 @@ int main(int argc, char *argv[]){
     std::string fname;
     fname = "data/particleData";
     fname += ".h5part";
-    
+
     P->openH5(fname);
     dumpH5partVelocity(P,0);
     unsigned printid=1;
-    
+
     msg << "Starting iterations ..." << endl;
     P->compute_temperature();
-    // calculate initial space charge forces 
+    // calculate initial space charge forces
     P->calculateGridForces(interaction_radius,alpha,0,0,0);
     P->calculatePairForces(interaction_radius,eps,alpha);
-    
+
     //avg space charge forces for constant focusing
-    P->computeAvgSpaceChargeForces();	
+    P->computeAvgSpaceChargeForces();
 
     //dumpVTKVector(P->eg_m, P,0,"EFieldAfterPMandPP");
-    
+
     //compute quantities to check correctness:
     /*
      P->calc_field_energy();
@@ -700,41 +700,41 @@ int main(int argc, char *argv[]){
      P->calc_kinetic_energy();
      writeEnergy(P,0);
      */
-    
+
     IpplTimings::TimerRef gridTimer = IpplTimings::getTimer("GridTimer");
     IpplTimings::TimerRef particleTimer = IpplTimings::getTimer("ParticleTimer");
-    
+
     for (int it=0; it<iterations; it++) {
       /*
         P->calcMoments();
         P->computeBeamStatistics();
         writeBeamStatisticsVelocity(P,it);
-        
+
         P->calc_kinetic_energy();
         P->calc_field_energy();
         writeEnergy(P,it);
-      */        
+      */
         // advance the particle positions
         // basic leapfrogging timestep scheme.  velocities are offset
         // by half a timestep from the positions.
-        
+
         assign(P->R, P->R + dt * P->v);
         // update particle distribution across processors
         P->update();
-        
+
         // compute the electric field
-        
-        
+
+
         IpplTimings::startTimer(gridTimer);
         P->calculateGridForces(interaction_radius,alpha,0,it+1,0);
         IpplTimings::stopTimer(gridTimer);
-        
+
         IpplTimings::startTimer(particleTimer);
         P->calculatePairForces(interaction_radius,eps,alpha);
         IpplTimings::stopTimer(particleTimer);
-        
+
         //P->update();
-        
+
         //second part of leapfrog: advance velocitites
         //P->computeAvgSpaceChargeForces();
         //if (Ippl::myNode()==0)
@@ -743,7 +743,7 @@ int main(int argc, char *argv[]){
         P->applyConstantFocusing(focusingForce,beam_radius);
 
         assign(P->v, P->v + dt * P->Q/P->m * (P->EF));
-        
+
         P->compute_temperature();
 
         if (it%print_every==0){
@@ -754,28 +754,28 @@ int main(int argc, char *argv[]){
              P->calc_kinetic_energy();
              P->calc_potential_energy();
              writeEnergy(P,printid);
-             */	
+             */
             P->compute_temperature();
             writeTemperature(P,it+1);
-            
+
             dumpH5partVelocity(P,printid++);
         }
-        
+
         msg << "Finished iteration " << it << endl;
     }
     Ippl::Comm->barrier();
-    
+
     P->closeH5();
     Ippl::Comm->barrier();
-    
+
     IpplTimings::stopTimer(allTimer);
-    
+
     IpplTimings::print();
-    
-    
+
+
     delete P;
     delete FL;
     delete mesh;
-    
+
     return 0;
 }
diff --git a/ippl/test/particle/p3m3dMicrobunching.cpp b/ippl/test/particle/p3m3dMicrobunching.cpp
index 655334345136cad9cb4011cee06f4109fa083cb5..352b5a6ae1220fdb8afcaa16d2efcdf777bb087e 100644
--- a/ippl/test/particle/p3m3dMicrobunching.cpp
+++ b/ippl/test/particle/p3m3dMicrobunching.cpp
@@ -13,7 +13,7 @@
  *	mpirun -n 32 ./p3m3dMicrobunching ${Nx} ${Ny} ${Nz} ${r_cut} ${alpha} ${epsilon} ${Nsteps} $SeedID} ${printSteps}
  * 	Nx,Ny,Nx is the poisson solver grid size, r_cut is the cutoff for pp interaction, alpha is the splitting parameter,
  * 	epsilon is the softening parameter, printSteps=10 prints every tenth step
- *  
+ *
  *
  *************************************************************************************************************************************/
 #include "Ippl.h"
@@ -76,7 +76,7 @@ struct SpecializedGreensFunction<3> {
 			double r;
 			NDIndex<3> elem0=NDIndex<3>(Index(0,0), Index(0,0),Index(0,0));
 			grn = grnI[0] * hrsq[0] + grnI[1] * hrsq[1] + grnI[2] * hrsq[2];
-			NDIndex<3> lDomain_m = grn.getLayout().getLocalNDIndex(); 
+			NDIndex<3> lDomain_m = grn.getLayout().getLocalNDIndex();
 			NDIndex<3> elem;
 			for (int i=lDomain_m[0].min(); i<=lDomain_m[0].max(); ++i) {
 				elem[0]=Index(i,i);
@@ -135,7 +135,7 @@ class ChargedParticles : public IpplParticleBase<PL> {
 		this->addAttribute(ID);
 
 		//read beam parameters from input file:
-		
+
 		if(Ippl::myNode()==0) {
 		std::cout << "we are reading the following beam parameters" << std::endl;
 		}
@@ -156,15 +156,15 @@ class ChargedParticles : public IpplParticleBase<PL> {
 		m0 = readNextBeamParamValue(input);
 		ke = readNextBeamParamValue(input);
 		c = readNextBeamParamValue(input);
-		
-		double NpartTotal = extend_r[2]*I/(c*1.6e-19); 
+
+		double NpartTotal = extend_r[2]*I/(c*1.6e-19);
 		std::cout << "total number of particles is = " << NpartTotal << std::endl;
 		double particleDensity =NpartTotal/extend_r[2]*1/(2*M_PI*sigmaX*sigmaX);
 		std::cout << "particle density = " << particleDensity << std::endl;
 		Npart=particleDensity*extend_r[0]*extend_r[1]*extend_r[2];
 		std::cout << "number of particles in simulation domain is = " << Npart << std::endl;
 		//q=I*extend_r[2]/double(Npart);
-		
+
 		//wavelength of interest
 		lambda = 0.5e-6;
 
@@ -199,12 +199,12 @@ class ChargedParticles : public IpplParticleBase<PL> {
 		for (unsigned int d = 0;d<Dim;++d) {
 			rmax_m[d] = extend_r[d];
 			rmin_m[d] = extend_l[d];
-		}  
+		}
 
 		domain_m = this->getFieldLayout().getDomain();
-		lDomain_m = this->getFieldLayout().getLocalNDIndex(); // local domain 
+		lDomain_m = this->getFieldLayout().getLocalNDIndex(); // local domain
 
-		//initialize the FFT 
+		//initialize the FFT
 		bool compressTemps = true;
 		fft_m = new FFT_t(domain_m,compressTemps);
 
@@ -242,7 +242,7 @@ class ChargedParticles : public IpplParticleBase<PL> {
 			eg_m.initialize(getMesh(), getFieldLayout(), GuardCellSizes<Dim>(1), vbc_m);
 
 			domain_m = this->getFieldLayout().getDomain();
-			lDomain_m = this->getFieldLayout().getLocalNDIndex(); 
+			lDomain_m = this->getFieldLayout().getLocalNDIndex();
 
 			IpplParticleBase<PL>::update();
 		}
@@ -305,15 +305,15 @@ class ChargedParticles : public IpplParticleBase<PL> {
 		double det(int n, double mat[2*Dim][2*Dim]) {
 			double d=0;
 			int c, subi, i, j, subj;
-			double submat[2*Dim][2*Dim];  
-			if (n == 2) 
+			double submat[2*Dim][2*Dim];
+			if (n == 2)
 				return( (mat[0][0] * mat[1][1]) - (mat[1][0] * mat[0][1]));
-			else {  
-				for(c = 0; c < n; c++) {  
-					subi = 0;  
-					for(i = 1; i < n; i++) {  
+			else {
+				for(c = 0; c < n; c++) {
+					subi = 0;
+					for(i = 1; i < n; i++) {
 						subj = 0;
-						for(j = 0; j < n; j++){    
+						for(j = 0; j < n; j++){
 							if (j == c)
 								continue;
 							submat[subi][subj] = mat[i][j];
@@ -372,7 +372,7 @@ class ChargedParticles : public IpplParticleBase<PL> {
 			}
 			rprms_m = rpsum * fac;
 
-			// Find normalized emittance.	
+			// Find normalized emittance.
 			double actual_gamma = 0.0;
 			for(size_t i = 0; i < locNp; i++)
 				actual_gamma += sqrt(1.0 + (gamma*p[i](2)+m0*gamma*beta0)*(gamma*p[i](2)+m0*gamma*beta0)/m0/m0 + p[i](1)*p[i](1)/m0/m0+p[i](0)*p[i](0)/m0/m0) ;
@@ -386,7 +386,7 @@ class ChargedParticles : public IpplParticleBase<PL> {
 			eps6x6_normalized_m = eps6x6_m*actual_gamma*beta0;
 		}
 
-		void calculatePairForces(double interaction_radius, double eps, double alpha) {	
+		void calculatePairForces(double interaction_radius, double eps, double alpha) {
 			if (interaction_radius>0){
 				if (Ippl::getNodes() > 1) {
 					HashPairBuilderPeriodicParallel< ChargedParticles<playout_t> > HPB(*this);
@@ -418,7 +418,7 @@ class ChargedParticles : public IpplParticleBase<PL> {
 
 			//compute rhoHat and store in rhocmpl_m
 			fft_m->transform("inverse", rhocmpl_m);
-			// (2) compute Greens function in real space and transform to fourier space 
+			// (2) compute Greens function in real space and transform to fourier space
 			/////////compute G with Index Magic///////////////////
 			// Fields used to eliminate excess calculation in greensFunction()
 			IField_t grnIField_m[3];
@@ -450,7 +450,7 @@ class ChargedParticles : public IpplParticleBase<PL> {
 
 			//take only the real part and store in phi_m (has periodic bc instead of interpolation bc)
 			phi_m = real(rhocmpl_m)*hr_m[0]*hr_m[1]*hr_m[2];
-			//dumpVTKScalar( phi_m, this,it, "Phi_m") ;	
+			//dumpVTKScalar( phi_m, this,it, "Phi_m") ;
 
 			//compute Electric field on the grid by -Grad(Phi) store in eg_m
 			eg_m = -Grad1Ord(phi_m, eg_m);
@@ -461,11 +461,11 @@ class ChargedParticles : public IpplParticleBase<PL> {
 			Phi.gather(phi_m, this->R, IntrplCIC_t());
 		}
 
-		void closeH5(){ 
+		void closeH5(){
 			H5CloseFile(H5f_m);
 		}
 
-		void openH5(std::string fn){ 
+		void openH5(std::string fn){
 			H5f_m = H5OpenFile(fn.c_str(), H5_FLUSH_STEP | H5_O_WRONLY, Ippl::getComm());
 		}
 
@@ -532,7 +532,7 @@ class ChargedParticles : public IpplParticleBase<PL> {
 		unsigned seedID;
 
 
-		//Moment calculations:  
+		//Moment calculations:
 		/// 6x6 matrix of the moments of the beam
 		//FMatrix<double, 2 * Dim, 2 * Dim> moments_m;
 		double moments_m[2*Dim][2*Dim];
@@ -648,12 +648,12 @@ int main(int argc, char *argv[]){
 	msg << endl << endl;
 
 	double tend = P->Ld/(P->beta0);
-	std::cout << "tend = "<< tend << std::endl; 
+	std::cout << "tend = "<< tend << std::endl;
 	//lorentz transform to beam frame:
-	//////// TODO check lorentz transformation of time 
+	//////// TODO check lorentz transformation of time
 	//tend = P->gamma*(tend-P->beta0*P->Ld);
 	tend /= P->gamma;
-	std::cout << "tend' = "<< tend << std::endl; 
+	std::cout << "tend' = "<< tend << std::endl;
 	double dt=tend/iterations;
 	std::cout << "TIMESTEP dt = " << dt << std::endl;
 	createParticleDistributionMicrobunching(P, myseedID);
@@ -684,7 +684,7 @@ int main(int argc, char *argv[]){
 	unsigned printid=1;
 	msg << "Starting iterations ..." << endl;
 
-	// calculate initial grid forces 
+	// calculate initial grid forces
 	P->calculateGridForces(interaction_radius,alpha,eps,0);
 	//dumpVTKVector(P->eg_m, P,0,"EFieldAfterPMandPP");
 
@@ -705,7 +705,7 @@ int main(int argc, char *argv[]){
 		//assign(P->R, P->R + dt * P->p/(P->gamma*P->m0)+rearrangez*1./P->gamma*(1.-sqrt(1.+dot(P->p,P->p)/(P->m0*P->m0*P->c*P->c)))*P->R56);
 		assign(P->R, P->R + dt * P->p/P->m0);
 		//shift particle due to longitudinal dispersion
-		//assign(P->R, P->R + kHat*P->gamma*P->R56*P->p/(P->beta0*P->m0));		
+		//assign(P->R, P->R + kHat*P->gamma*P->R56*P->p/(P->beta0*P->m0));
 		/*
 		   for (unsigned i=0; i<P->getLocalNum(); ++i) {
 		   P->R[i][2]+=(sqrt(P->p[i][2]+P->m0*P->m0)/(P->m0)-1.)*1./P->gamma*P->R56;
diff --git a/ippl/test/particle/salman-1.cpp b/ippl/test/particle/salman-1.cpp
index 24d7a82ea2e6e5c3f379480f126b53cb40062808..2828e517703ea9a9d391a0e54d4153a05c2c6ba6 100644
--- a/ippl/test/particle/salman-1.cpp
+++ b/ippl/test/particle/salman-1.cpp
@@ -2,27 +2,27 @@
 /***********************************************************************************
  *
  * The IPPL Framework
- * 
- * This program was prepared by PSI. 
- * All rights in the program are reserved by PSI. 
+ *
+ * This program was prepared by PSI.
+ * All rights in the program are reserved by PSI.
  * Neither PSI nor the author(s)
  * makes any warranty, express or implied, or assumes any liability or
  * responsibility for the use of this software
  *
  * Visit http://www.
  *
- * This test program sets up a simple sine-wave electric field in 3D, 
+ * This test program sets up a simple sine-wave electric field in 3D,
  * creates a population of particles with random q/m values (charge-to-mass
  * ratio) and velocities, and then tracks their motions in the static
- * electric field using nearest-grid-point interpolation. 
+ * electric field using nearest-grid-point interpolation.
  *
  * Usage:
  *
  * $MYMPIRUN -np 2 salman-1 128 128 ??? 10000 10 NGP initialx initialy --commlib mpi
  *
  *          nx,ny xx  xxx NP NTstep  Interp  xini yini dx  dy  meshorgx meshorgy hx  hy
- *          |     |       |  |       |       |    |    |   |   |        |        |   |  
- * salman-1 4     xx  xxx 1  7       NGP     1.0  1.0  1.0 1.0 1.0      1.0      1.0 1.0 --commlib mpi 
+ *          |     |       |  |       |       |    |    |   |   |        |        |   |
+ * salman-1 4     xx  xxx 1  7       NGP     1.0  1.0  1.0 1.0 1.0      1.0      1.0 1.0 --commlib mpi
  *
  *
  *          nx,ny Interp  meshorgx meshorgy hx  hy  domplus steps
@@ -40,7 +40,7 @@
 // dimension of our positions
 const unsigned Dim = 2;
 
-// some typedefs 
+// some typedefs
 typedef ParticleSpatialLayout<double,Dim>::SingleParticlePos_t Vector_t;
 typedef ParticleSpatialLayout<double,Dim> playout_t;
 typedef UniformCartesian<Dim,double> Mesh_t;
@@ -68,7 +68,7 @@ public:
   typename PL::ParticlePos_t E;  // electric field at particle position
   typename PL::ParticlePos_t B;  // magnetic field at particle position
 
-  ChargedParticles(PL* pl, InterPol_t interpol, Vector_t hr, e_dim_tag decomp[Dim], Vector_t mesh_org) : 
+  ChargedParticles(PL* pl, InterPol_t interpol, Vector_t hr, e_dim_tag decomp[Dim], Vector_t mesh_org) :
     IpplParticleBase<PL>(pl),
     interpol_m(interpol),
     hr_m(hr),
@@ -78,25 +78,25 @@ public:
     // register the particle attributes
     this->addAttribute(qm);
 
-    NDIndex<Dim> domain = getFieldLayout().getDomain(); 
+    NDIndex<Dim> domain = getFieldLayout().getDomain();
 
     for(int i=0; i<Dim; i++)
       nr_m[i] = domain[i].length();
-    
-    hr_m = hr; 
+
+    hr_m = hr;
     getMesh().set_meshSpacing(&(hr_m[0]));
     getMesh().set_origin(mesh_org);
-    
+
     for(int i=0; i<Dim; i++)
       decomp_m[i]=decomp[i];
 
-    setBCAllPeriodic();  
+    setBCAllPeriodic();
   }
   
   inline const Mesh_t& getMesh() const { return this->getLayout().getLayout().getMesh(); }
-  
+
   inline Mesh_t& getMesh() { return this->getLayout().getLayout().getMesh(); }
-    
+
   inline const FieldLayout_t& getFieldLayout() const {
     return dynamic_cast<FieldLayout_t&>( this->getLayout().getLayout().getFieldLayout());
   }
@@ -112,12 +112,12 @@ public:
       scatterCIC();
     else
       scatterNGP();
-    
+
     /*
       now sum over all gridpoints ... a bit nasty !
 
-   
-    
+
+
     Field<double,Dim> tmpf;
     NDIndex<Dim> domain = getFieldLayout().getDomain();
 
@@ -140,7 +140,7 @@ public:
 		Q +=  tmpf.localElement(elem);
 	    }
         }
-	
+
     }
     reduce(Q,Q,OpAddAssign());
     m << "sum(qm)= " << initialQ << " sum(rho_m)= " << sum(rho_m) << endl;
@@ -152,16 +152,16 @@ public:
     bounds(this->R, rmin_m, rmax_m);
     if(fieldNotInitialized_m) {
 
-      // rescale mesh 
+      // rescale mesh
       // getMesh().set_meshSpacing(&(hr_m[0]));
-      // getMesh().set_origin( -hr_m/2.0 ); 
+      // getMesh().set_origin( -hr_m/2.0 );
       // getMesh().set_origin(Vector_t(1.0));
       rho_m.initialize(getMesh(), getFieldLayout(), GuardCellSizes<Dim>(GUARDCELL), bc_m);
       fieldNotInitialized_m=false;
     }
     this->update();
   }
-  
+
   void myUpdate() {
     bounds(this->R, rmin_m, rmax_m);
     this->update();
@@ -178,24 +178,24 @@ public:
   void savePhaseSpace(string fn, int idx) {
   }
 
-  inline void setBCAllPeriodic() {    
+  inline void setBCAllPeriodic() {
     for (int i=0; i < 2*Dim; i++) {
       this->getBConds()[i] = ParticlePeriodicBCond;
       bc_m[i]  = new PeriodicFace<double  ,Dim,Mesh_t,Center_t>(i);
       vbc_m[i] = new PeriodicFace<Vector_t,Dim,Mesh_t,Center_t>(i);
-    }  
+    }
   }
 
   void printField(Inform& m, Field<double,Dim>& f)
   {
-    NDIndex<Dim> domain = getFieldLayout().getDomain();   
+    NDIndex<Dim> domain = getFieldLayout().getDomain();
     NDIndex<Dim> loop;
-    
+
     m << "sum(rho)= "<< sum(rho_m) << endl;
-    for (int j=domain[1].min(); j<=domain[1].max(); ++j) 
-      m << "\t" << j;    
+    for (int j=domain[1].min(); j<=domain[1].max(); ++j)
+      m << "\t" << j;
     m << endl << endl;
-    
+
     for (int i=domain[0].min(); i<=domain[0].max(); ++i) {
       loop[0]=Index(i,i);
       	m << i ;
@@ -207,7 +207,7 @@ public:
     }
     m << endl;
   }
-  
+
   Field<double,Dim> rho_m;
 
 private:
@@ -229,7 +229,7 @@ private:
   BConds<Vector_t,Dim,Mesh_t,Center_t> vbc_m;
 
   Vektor<int,Dim> nr_m;
-    
+
   Vector_t hr_m;
   Vector_t rmin_m;
   Vector_t rmax_m;
@@ -265,16 +265,16 @@ int main(int argc, char *argv[]){
     myInterpol = CIC;
   else
     myInterpol = NGP;
-  
+
   msg << "Np= " << totalP << " grid = " << nr <<endl;
   msg << "0 <= x <= " << nx-1 << " 0 <= y <= " << ny-1 << endl;
-  
+
   if (myInterpol==CIC)
-    msg << "Cloud in cell (CIC) interpolation selected" << endl; 
+    msg << "Cloud in cell (CIC) interpolation selected" << endl;
   else
-    msg << "Nearest grid point (NGP) interpolation selected" << endl; 
-  
-  msg << "BC: periodic in all dimensions" << endl; 
+    msg << "Nearest grid point (NGP) interpolation selected" << endl;
+
+  msg << "BC: periodic in all dimensions" << endl;
 
   e_dim_tag decomp[Dim];
   int serialDim = Dim-1;
@@ -288,61 +288,61 @@ int main(int argc, char *argv[]){
   NDIndex<Dim> domain;
   for(int i=0; i<Dim; i++) {
     domain[i] = domain[i] = Index(nr[i] + domplus);
-    decomp[i] = (i == serialDim) ? SERIAL : PARALLEL; 
+    decomp[i] = (i == serialDim) ? SERIAL : PARALLEL;
   }
 
   // create mesh and layout objects for this problem domain
   mesh          = new Mesh_t(domain);
   FL            = new FieldLayout_t(*mesh, decomp);
   playout_t* PL = new playout_t(*FL, *mesh);
-  
+
   P = new ChargedParticles<playout_t>(PL,myInterpol,hr,decomp,mesh_org);
-  
-  P->create(totalP);  
- 
+
+  P->create(totalP);
+
   size_t k = 0;
   for (int i=0; i<nx; i++)
     for (int j=0; j<ny; j++) {
       P->R[k]  = Vector_t(i,j);
       k++;
     }
-  
+
   double q = 1.0;
   assign(P->qm,q);
   P->update();
 
   // redistribute particles based on spatial layout
-  P->myInitialUpdate(); 
-  
+  P->myInitialUpdate();
+
   msg << P->getMesh() << endl;
   msg << P->getFieldLayout() << endl;
   msg << "particles created and initial conditions assigned Q=" << sum(P->qm) << endl;
 
   size_t loc = (nx*ny) - 1;
-  
-  
-  P->scatter();     
+
+
+  P->scatter();
   P->printField(msg, P->rho_m);
-  P->myUpdate(); 
+  P->myUpdate();
 
 
   for (int n=0; n<steps; n++) {
     P->rho_m= 0.0;
     P->R[loc] += Vector_t(0.0,0.1);
     P->update();
-  
+
     k = 0;
     for (int i=0; i<nx; i++) {
       msg << endl;
       for (int j=0; j<ny; j++) {
-	msg << P->R[k] << " "; 
+	msg << P->R[k] << " ";
 	k++;
       }
     }
     msg << endl << endl;
-  
-    P->scatter();     
-    P->myUpdate(); 
+
+    P->scatter();
+    P->myUpdate();
     P->printField(msg, P->rho_m);
   }
   Ippl::Comm->barrier();
@@ -353,7 +353,7 @@ int main(int argc, char *argv[]){
 /***************************************************************************
  * $RCSfile: addheaderfooter,v $   $Author: adelmann $
  * $Revision: 1.1.1.1 $   $Date: 2003/01/23 07:40:17 $
- * IPPL_VERSION_ID: $Id: addheaderfooter,v 1.1.1.1 2003/01/23 07:40:17 adelmann Exp $ 
+ * IPPL_VERSION_ID: $Id: addheaderfooter,v 1.1.1.1 2003/01/23 07:40:17 adelmann Exp $
  ***************************************************************************/
 
 
@@ -363,7 +363,7 @@ int main(int argc, char *argv[]){
       }
 
 
-  msg << "Particle at " << xi << " beign pushed by dL= " << hr[0] << endl;   
+  msg << "Particle at " << xi << " beign pushed by dL= " << hr[0] << endl;
 
   P->R[0]  = xi;
   Vector_t xf = xi;
@@ -386,5 +386,4 @@ int main(int argc, char *argv[]){
 
 
 
-  */
-
+  */
\ No newline at end of file
diff --git a/ippl/test/poissonsolvers/femmgTest.cpp b/ippl/test/poissonsolvers/femmgTest.cpp
index a418a92760376ed8e1f7c5b2015e7d5f6dce7cf3..c3596419605b4fb9379e60280cf0589b8e78a25e 100644
--- a/ippl/test/poissonsolvers/femmgTest.cpp
+++ b/ippl/test/poissonsolvers/femmgTest.cpp
@@ -285,7 +285,7 @@ int main(int argc, char *argv[]) {
   IpplTimings::stopTimer(mainTimer); 
   IpplTimings::print();
   
-  delete bunch;  // No "delete layout;" already done in IpplParticleBase::~IpplParticleBase()
+  delete bunch;  // No "delete layout;" already done in ParticleBase::~ParticleBase()
   delete grid;
   delete geom_domain;
   return 0;
diff --git a/ippl/test/simple-new/memcheck-1.cpp b/ippl/test/simple-new/memcheck-1.cpp
index 4b019cddf90232aac80813e0a5e9d930c96add66..e6879235660ef8faa4239ccf343afc61e61baca5 100644
--- a/ippl/test/simple-new/memcheck-1.cpp
+++ b/ippl/test/simple-new/memcheck-1.cpp
@@ -2,9 +2,9 @@
 /***************************************************************************
  *
  * The IPPL Framework
- * 
- * This program was prepared by PSI. 
- * All rights in the program are reserved by PSI. 
+ *
+ * This program was prepared by PSI.
+ * All rights in the program are reserved by PSI.
  * Neither PSI nor the author(s)
  * makes any warranty, express or implied, or assumes any liability or
  * responsibility for the use of this software
@@ -15,14 +15,14 @@
 
 /***************************************************************************
 
- This test program sets up a simple sine-wave electric field in 3D, 
+ This test program sets up a simple sine-wave electric field in 3D,
    creates a population of particles with random q/m values (charge-to-mass
    ratio) and velocities, and then tracks their motions in the static
-   electric field using nearest-grid-point interpolation. 
+   electric field using nearest-grid-point interpolation.
 
 Usage:
 
- 
+
  $MYMPIRUN -np 2 memcheck-1 128 128 128 10000 10 --processes 2 --commlib mpi
 
 ***************************************************************************/
@@ -37,7 +37,7 @@ Usage:
 // dimension of our positions
 const unsigned Dim = 3;
 
-// some typedefs 
+// some typedefs
 typedef ParticleSpatialLayout<double,Dim>::SingleParticlePos_t Vector_t;
 typedef ParticleSpatialLayout<double,Dim> playout_t;
 typedef UniformCartesian<Dim,double> Mesh_t;
@@ -66,7 +66,7 @@ public:
   typename PL::ParticlePos_t E;  // electric field at particle position
   typename PL::ParticlePos_t B;  // magnetic field at particle position
 
-  ChargedParticles(PL* pl, BC_t bc, InterPol_t interpol, e_dim_tag decomp[Dim], bool gCells) : 
+  ChargedParticles(PL* pl, BC_t bc, InterPol_t interpol, e_dim_tag decomp[Dim], bool gCells) :
     IpplParticleBase<PL>(pl),
     bco_m(bc),
     interpol_m(interpol),
@@ -90,7 +90,7 @@ public:
     particles as in the OOO case.
   */
 
-  ChargedParticles(PL* pl, BC_t bc, InterPol_t interpol, Vector_t hr, Vector_t rmin, Vector_t rmax, e_dim_tag decomp[Dim], bool gCells) : 
+  ChargedParticles(PL* pl, BC_t bc, InterPol_t interpol, Vector_t hr, Vector_t rmin, Vector_t rmax, e_dim_tag decomp[Dim], bool gCells) :
     IpplParticleBase<PL>(pl),
     bco_m(bc),
     interpol_m(interpol),
@@ -116,14 +116,14 @@ public:
       setBCAllOpen();
     else if (bco_m == PPP)
       setBCAllPeriodic();
-    else 
+    else
       setBCOOP();
-  } 
+  }
 
   inline const Mesh_t& getMesh() const { return this->getLayout().getLayout().getMesh(); }
-  
+
   inline Mesh_t& getMesh() { return this->getLayout().getLayout().getMesh(); }
-    
+
   inline const FieldLayout_t& getFieldLayout() const {
     return dynamic_cast<FieldLayout_t&>( this->getLayout().getLayout().getFieldLayout());
   }
@@ -146,12 +146,12 @@ public:
       scatterCIC();
     else
       scatterNGP();
-    
+
     /*
       now sum over all gridpoints ... a bit nasty !
 
     */
-    
+
     Field<double,Dim> tmpf;
     NDIndex<Dim> domain = getFieldLayout().getDomain();
 
@@ -174,7 +174,7 @@ public:
 		Q +=  tmpf.localElement(elem);
 	    }
         }
-	
+
     }
     reduce(Q,Q,OpAddAssign());
     m << "sum(qm)= " << initialQ << " sum(EFDMag)= " << sum(EFDMag_m) << endl;
@@ -182,21 +182,21 @@ public:
   }
   
   void myUpdate() {
-    
+
     double hz   = hr_m[2];
     double zmin = rmin_m[2];
     double zmax = rmax_m[2];
 
     if (bco_m != PPP) {
       bounds(this->R, rmin_m, rmax_m);
-                  
-      NDIndex<Dim> domain = this->getFieldLayout().getDomain(); 
-      
+
+      NDIndex<Dim> domain = this->getFieldLayout().getDomain();
+
       for(int i=0; i<Dim; i++)
 	nr_m[i] = domain[i].length();
-	
+
       for(int i=0; i<Dim; i++)
-	  hr_m[i] = (rmax_m[i] - rmin_m[i]) / (nr_m[i] - 1.0); 
+	  hr_m[i] = (rmax_m[i] - rmin_m[i]) / (nr_m[i] - 1.0);
 
       if (bco_m == OOP) {
 	rmin_m[2] = zmin;
@@ -215,7 +215,7 @@ public:
 	  EFD_m.initialize(getMesh(), getFieldLayout(), vbc_m);
 	  EFDMag_m.initialize(getMesh(), getFieldLayout(), bc_m);
       }
-    } 
+    }
     else {
       if(fieldNotInitialized_m) {
 	fieldNotInitialized_m=false;
@@ -242,14 +242,14 @@ public:
     double *globalPartPerNode = new double[Ippl::getNodes()];
     for (int i=0; i<Ippl::getNodes(); i++) {
       partPerNode[i] = globalPartPerNode[i] = 0.0;
-    
+
     }
     partPerNode[Ippl::myNode()] = this->getLocalNum();
 
     reduce(partPerNode,partPerNode+Ippl::getNodes(),globalPartPerNode,OpAddAssign());
-    
+
     for (int i=0; i<Ippl::getNodes(); i++)
-      m << "Node " << i << " has " 
+      m << "Node " << i << " has "
 	<<   globalPartPerNode[i]/this->getTotalNum()*100.0 << " % of the total particles " << endl;
   }
 
@@ -258,29 +258,29 @@ public:
 
   void initFields() {
     Inform m("initFields ");
-    
+
     NDIndex<Dim> domain = getFieldLayout().getDomain();
-    
+
     for(int i=0; i<Dim; i++)
       nr_m[i] = domain[i].length();
-  
+
     int nx = nr_m[0];
     int ny = nr_m[1];
     int nz = nr_m[2];
 
-    double phi0 = 0.1*nx;            
+    double phi0 = 0.1*nx;
 
     m << "rmin= " << rmin_m << " rmax= " << rmax_m << " h= " << hr_m << " n= " << nr_m << endl;
-    
+
     Index I(nx), J(ny), K(nz);
-  
+
     assign(EFD_m[I][J][K](0), -2.0*pi*phi0/nx * cos(2.0*pi*(I+0.5)/nx) * cos(4.0*pi*(J+0.5)/ny) * cos(pi*(K+0.5)/nz));
 
     assign(EFD_m[I][J][K](1),  4.0*pi*phi0/ny * sin(2.0*pi*(I+0.5)/nx) * sin(4.0*pi*(J+0.5)/ny));
 
     assign(EFD_m[I][J][K](2),  4.0*pi*phi0/ny * sin(2.0*pi*(I+0.5)/nx) * sin(4.0*pi*(J+0.5)/ny));
 
-    assign(EFDMag_m[I][J][K], 
+    assign(EFDMag_m[I][J][K],
 	   EFD_m[I][J][K](0) * EFD_m[I][J][K](0) +
 	   EFD_m[I][J][K](1) * EFD_m[I][J][K](1) +
 	   EFD_m[I][J][K](2) * EFD_m[I][J][K](2));
@@ -309,29 +309,29 @@ public:
       tmp.push_back(this->P[i](1));
       tmp.push_back(this->P[i](2));
     }
-    
+
     if(Ippl::myNode() == 0) {
       ofstream ostr;
       string Fn;
       char numbuf[6];
-      sprintf(numbuf, "%05d", idx);  
+      sprintf(numbuf, "%05d", idx);
       Fn = fn  + string(numbuf) + ".dat";
       ostr.open(Fn.c_str(), ios::out );
       ostr.precision(15);
       ostr.setf(ios::scientific, ios::floatfield);
-  
+
       ostr << " x, px, y, py t, pt, id, node" << endl;
 
       unsigned int dataBlocks=0;
       double x,y,z,px,py,pz,id;
       unsigned  vn;
-      
+
       for (unsigned i=0; i < tmp.size(); i+=7)
 	ostr << tmp[i+1] << " " << tmp[i+4] << " " << tmp[i+2]  << " " \
 	     << tmp[i+5] << " " << tmp[i+3] << " " << tmp[i+6]  << " " \
 	     << tmp[i]   << " " << Ippl::myNode() << endl;
-      
-      int notReceived =  Ippl::getNodes() - 1; 
+
+      int notReceived =  Ippl::getNodes() - 1;
       while (notReceived > 0) {
 	int node = COMM_ANY_NODE;
 	Message* rmsg =  Ippl::Comm->receive_block(node, tag);
@@ -362,10 +362,10 @@ public:
       dataBlocks = tmp.size();
       smsg->put(dataBlocks);
       smsg->put(Ippl::myNode());
-      for (unsigned i=0; i < tmp.size(); i++) 
+      for (unsigned i=0; i < tmp.size(); i++)
 	smsg->put(tmp[i]);
-      bool res = Ippl::Comm->send(smsg, 0, tag);	
-      if (! res) 
+      bool res = Ippl::Comm->send(smsg, 0, tag);
+      if (! res)
 	ERRORMSG("Ippl::Comm->send(smsg, 0, tag) failed " << endl;);
     }
   }
@@ -379,13 +379,13 @@ private:
       vbc_m[i] = new ZeroFace<Vector_t,Dim,Mesh_t,Center_t>(i);
     }
   }
-  
+
   inline void setBCAllPeriodic() {
     for (int i=0; i < 2*Dim; i++) {
       this->getBConds()[i] = ParticlePeriodicBCond;
       bc_m[i]  = new PeriodicFace<double  ,Dim,Mesh_t,Center_t>(i);
       vbc_m[i] = new PeriodicFace<Vector_t,Dim,Mesh_t,Center_t>(i);
-    }  
+    }
   }
 
   inline void setBCOOP() {
@@ -397,8 +397,8 @@ private:
     for (int i= 2*Dim - 2; i < 2*Dim; i++) {
       bc_m[i]  = new PeriodicFace<double  ,Dim,Mesh_t,Center_t>(i);
       vbc_m[i] = new PeriodicFace<Vector_t,Dim,Mesh_t,Center_t>(i);
-      this->getBConds()[i] = ParticlePeriodicBCond;    
-    }  
+      this->getBConds()[i] = ParticlePeriodicBCond;
+    }
   }
 
   inline void gatherNGP() {
@@ -427,12 +427,12 @@ private:
 
   Field<Vektor<double,Dim>,Dim> EFD_m;
   Field<double,Dim> EFDMag_m;
-  
+
   BConds<double,Dim,Mesh_t,Center_t> bc_m;
   BConds<Vector_t,Dim,Mesh_t,Center_t> vbc_m;
 
   Vektor<int,Dim> nr_m;
-    
+
   Vector_t hr_m;
   Vector_t rmin_m;
   Vector_t rmax_m;
@@ -441,7 +441,7 @@ private:
   InterPol_t interpol_m;
   bool fieldNotInitialized_m;
   bool doRepart_m;
-  bool withGuardCells_m;  
+  bool withGuardCells_m;
   e_dim_tag decomp_m[Dim];
 
 };
@@ -452,12 +452,12 @@ int main(int argc, char *argv[]){
   Inform msg2all(argv[0],INFORM_ALL_NODES);
 
   Vektor<int,Dim> nr(atoi(argv[1]),atoi(argv[2]),atoi(argv[3]));
-  double memoryPerNode = 2; // GB 
+  double memoryPerNode = 2; // GB
   static IpplMemoryUsage::MemRef mainMemWatch = IpplMemoryUsage::getMemObserver("main", memoryPerNode);
   static IpplMemoryUsage::MemRef meshMemWatch = IpplMemoryUsage::getMemObserver("aftermesh", memoryPerNode);
   static IpplMemoryUsage::MemRef PMemWatch = IpplMemoryUsage::getMemObserver("chargedparts", memoryPerNode);
   static IpplMemoryUsage::MemRef PartsMemWatch = IpplMemoryUsage::getMemObserver("creapart", memoryPerNode);
- 
+
   IpplMemoryUsage::sample(mainMemWatch,"main");
 
   const unsigned int totalP = atoi(argv[4]);
@@ -465,13 +465,13 @@ int main(int argc, char *argv[]){
 
   InterPol_t myInterpol = CIC;
 
-  
+
   bool gCells = true;
-  
+
   msg << "nt " << nt << " Np= " << totalP << " grid = " << nr <<endl;
-  
+
   msg << "Cloud in cell (CIC) interpolation selected, using guard cells BC == OOO" << endl;
-  
+
   BC_t myBC = OOO;
 
   e_dim_tag decomp[Dim];
@@ -495,7 +495,7 @@ int main(int argc, char *argv[]){
 
   for (int d=0; d < Dim; ++d)
       decomp[d] = (d == serialDim) ? SERIAL : PARALLEL;
-  
+
   // create mesh and layout objects for this problem domain
   mesh          = new Mesh_t(domain);
   FL            = new FieldLayout_t(*mesh, decomp);
@@ -504,30 +504,30 @@ int main(int argc, char *argv[]){
   IpplMemoryUsage::sample(meshMemWatch,"mesh");
 
   P = new ChargedParticles<playout_t>(PL,myBC,myInterpol,decomp,gCells);
-  
+
   IpplMemoryUsage::sample(PMemWatch,"mesh");
 
   // initialize the particle object: do all initialization on one node,
   // and distribute to others
 
   unsigned long int nloc = totalP / Ippl::getNodes();
-  
+
   P->create(nloc);
   for (unsigned long int i = 0; i< nloc; i++) {
     for (int d = 0; d<3; d++)
       P->R[i](d) =  IpplRandom() * nr[d];
   }
-  
+
   double q = 1.0/totalP;
-  
+
   // random initialization for charge-to-mass ratio
   assign(P->qm,q);
-  
+
 
   msg << "particles created and initial conditions assigned " << endl;
-  
+
   // redistribute particles based on spatial layout
-  P->myUpdate(); 
+  P->myUpdate();
 
   IpplMemoryUsage::sample(PartsMemWatch,"mesh");
 
@@ -536,7 +536,7 @@ int main(int argc, char *argv[]){
   msg << P->getFieldLayout() << endl;
 
   msg << "scatter test done delta= " <<  P->scatter() << endl;
-    
+
   P->initFields();
   msg << "P->initField() done " << endl;
 
@@ -548,16 +548,16 @@ int main(int argc, char *argv[]){
     // basic leapfrogging timestep scheme.  velocities are offset
     // by half a timestep from the positions.
     assign(P->R, P->R + dt * P->P);
-    
+
     // update particle distribution across processors
     P->myUpdate();
-    
+
     // gather the local value of the E field
     P->gather();
-    
+
     // advance the particle velocities
     assign(P->P, P->P + dt * P->qm * P->E);
-    msg << "Finished iteration " << it << " - min/max r and h " << P->getRMin() 
+    msg << "Finished iteration " << it << " - min/max r and h " << P->getRMin()
 	<< P->getRMax() << P->getHr() << endl;
   }
   IpplMemoryUsage::print();
@@ -569,6 +569,5 @@ int main(int argc, char *argv[]){
 /***************************************************************************
  * $RCSfile: addheaderfooter,v $   $Author: adelmann $
  * $Revision: 1.1.1.1 $   $Date: 2003/01/23 07:40:17 $
- * IPPL_VERSION_ID: $Id: addheaderfooter,v 1.1.1.1 2003/01/23 07:40:17 adelmann Exp $ 
- ***************************************************************************/
-
+ * IPPL_VERSION_ID: $Id: addheaderfooter,v 1.1.1.1 2003/01/23 07:40:17 adelmann Exp $
+ ***************************************************************************/
\ No newline at end of file
diff --git a/ippl/test/simple-new/memcheck-2.cpp b/ippl/test/simple-new/memcheck-2.cpp
index 2220ee3e59796d6b90239bb422e5033f15553715..8e97a85f8f6064f1855f96290fb813a2213995d3 100755
--- a/ippl/test/simple-new/memcheck-2.cpp
+++ b/ippl/test/simple-new/memcheck-2.cpp
@@ -2,9 +2,9 @@
 /***************************************************************************
  *
  * The IPPL Framework
- * 
- * This program was prepared by PSI. 
- * All rights in the program are reserved by PSI. 
+ *
+ * This program was prepared by PSI.
+ * All rights in the program are reserved by PSI.
  * Neither PSI nor the author(s)
  * makes any warranty, express or implied, or assumes any liability or
  * responsibility for the use of this software
@@ -15,14 +15,14 @@
 
 /***************************************************************************
 
- This test program sets up a simple sine-wave electric field in 3D, 
+ This test program sets up a simple sine-wave electric field in 3D,
    creates a population of particles with random q/m values (charge-to-mass
    ratio) and velocities, and then tracks their motions in the static
-   electric field using nearest-grid-point interpolation. 
+   electric field using nearest-grid-point interpolation.
 
 Usage:
 
- 
+
  $MYMPIRUN -np 2 memcheck-1 128 128 128 10000 10 --processes 2 --commlib mpi
 
 ***************************************************************************/
@@ -37,7 +37,7 @@ Usage:
 // dimension of our positions
 const unsigned Dim = 3;
 
-// some typedefs 
+// some typedefs
 typedef ParticleSpatialLayout<double,Dim>::SingleParticlePos_t Vector_t;
 typedef ParticleSpatialLayout<double,Dim> playout_t;
 typedef UniformCartesian<Dim,double> Mesh_t;
@@ -66,7 +66,7 @@ public:
   typename PL::ParticlePos_t E;  // electric field at particle position
   typename PL::ParticlePos_t B;  // magnetic field at particle position
 
-  ChargedParticles(PL* pl, BC_t bc, InterPol_t interpol, e_dim_tag decomp[Dim], bool gCells) : 
+  ChargedParticles(PL* pl, BC_t bc, InterPol_t interpol, e_dim_tag decomp[Dim], bool gCells) :
     IpplParticleBase<PL>(pl),
     bco_m(bc),
     interpol_m(interpol),
@@ -90,7 +90,7 @@ public:
     particles as in the OOO case.
   */
 
-  ChargedParticles(PL* pl, BC_t bc, InterPol_t interpol, Vector_t hr, Vector_t rmin, Vector_t rmax, e_dim_tag decomp[Dim], bool gCells) : 
+  ChargedParticles(PL* pl, BC_t bc, InterPol_t interpol, Vector_t hr, Vector_t rmin, Vector_t rmax, e_dim_tag decomp[Dim], bool gCells) :
     IpplParticleBase<PL>(pl),
     bco_m(bc),
     interpol_m(interpol),
@@ -116,14 +116,14 @@ public:
       setBCAllOpen();
     else if (bco_m == PPP)
       setBCAllPeriodic();
-    else 
+    else
       setBCOOP();
-  } 
+  }
 
   inline const Mesh_t& getMesh() const { return this->getLayout().getLayout().getMesh(); }
-  
+
   inline Mesh_t& getMesh() { return this->getLayout().getLayout().getMesh(); }
-    
+
   inline const FieldLayout_t& getFieldLayout() const {
     return dynamic_cast<FieldLayout_t&>( this->getLayout().getLayout().getFieldLayout());
   }
@@ -146,12 +146,12 @@ public:
       scatterCIC();
     else
       scatterNGP();
-    
+
     /*
       now sum over all gridpoints ... a bit nasty !
 
     */
-    
+
     Field<double,Dim> tmpf;
     NDIndex<Dim> domain = getFieldLayout().getDomain();
 
@@ -174,7 +174,7 @@ public:
 		Q +=  tmpf.localElement(elem);
 	    }
         }
-	
+
     }
     reduce(Q,Q,OpAddAssign());
     m << "sum(qm)= " << initialQ << " sum(EFDMag)= " << sum(EFDMag_m) << endl;
@@ -182,21 +182,21 @@ public:
   }
   
   void myUpdate() {
-    
+
     double hz   = hr_m[2];
     double zmin = rmin_m[2];
     double zmax = rmax_m[2];
 
     if (bco_m != PPP) {
       bounds(this->R, rmin_m, rmax_m);
-                  
-      NDIndex<Dim> domain = this->getFieldLayout().getDomain(); 
-      
+
+      NDIndex<Dim> domain = this->getFieldLayout().getDomain();
+
       for(int i=0; i<Dim; i++)
 	nr_m[i] = domain[i].length();
-	
+
       for(int i=0; i<Dim; i++)
-	  hr_m[i] = (rmax_m[i] - rmin_m[i]) / (nr_m[i] - 1.0); 
+	  hr_m[i] = (rmax_m[i] - rmin_m[i]) / (nr_m[i] - 1.0);
 
       if (bco_m == OOP) {
 	rmin_m[2] = zmin;
@@ -215,7 +215,7 @@ public:
 	  EFD_m.initialize(getMesh(), getFieldLayout(), vbc_m);
 	  EFDMag_m.initialize(getMesh(), getFieldLayout(), bc_m);
       }
-    } 
+    }
     else {
       if(fieldNotInitialized_m) {
 	fieldNotInitialized_m=false;
@@ -242,14 +242,14 @@ public:
     double *globalPartPerNode = new double[Ippl::getNodes()];
     for (int i=0; i<Ippl::getNodes(); i++) {
       partPerNode[i] = globalPartPerNode[i] = 0.0;
-    
+
     }
     partPerNode[Ippl::myNode()] = this->getLocalNum();
 
     reduce(partPerNode,partPerNode+Ippl::getNodes(),globalPartPerNode,OpAddAssign());
-    
+
     for (int i=0; i<Ippl::getNodes(); i++)
-      m << "Node " << i << " has " 
+      m << "Node " << i << " has "
 	<<   globalPartPerNode[i]/this->getTotalNum()*100.0 << " % of the total particles " << endl;
   }
 
@@ -258,29 +258,29 @@ public:
 
   void initFields() {
     Inform m("initFields ");
-    
+
     NDIndex<Dim> domain = getFieldLayout().getDomain();
-    
+
     for(int i=0; i<Dim; i++)
       nr_m[i] = domain[i].length();
-  
+
     int nx = nr_m[0];
     int ny = nr_m[1];
     int nz = nr_m[2];
 
-    double phi0 = 0.1*nx;            
+    double phi0 = 0.1*nx;
 
     m << "rmin= " << rmin_m << " rmax= " << rmax_m << " h= " << hr_m << " n= " << nr_m << endl;
-    
+
     Index I(nx), J(ny), K(nz);
-  
+
     assign(EFD_m[I][J][K](0), -2.0*pi*phi0/nx * cos(2.0*pi*(I+0.5)/nx) * cos(4.0*pi*(J+0.5)/ny) * cos(pi*(K+0.5)/nz));
 
     assign(EFD_m[I][J][K](1),  4.0*pi*phi0/ny * sin(2.0*pi*(I+0.5)/nx) * sin(4.0*pi*(J+0.5)/ny));
 
     assign(EFD_m[I][J][K](2),  4.0*pi*phi0/ny * sin(2.0*pi*(I+0.5)/nx) * sin(4.0*pi*(J+0.5)/ny));
 
-    assign(EFDMag_m[I][J][K], 
+    assign(EFDMag_m[I][J][K],
 	   EFD_m[I][J][K](0) * EFD_m[I][J][K](0) +
 	   EFD_m[I][J][K](1) * EFD_m[I][J][K](1) +
 	   EFD_m[I][J][K](2) * EFD_m[I][J][K](2));
@@ -309,29 +309,29 @@ public:
       tmp.push_back(this->P[i](1));
       tmp.push_back(this->P[i](2));
     }
-    
+
     if(Ippl::myNode() == 0) {
       ofstream ostr;
       string Fn;
       char numbuf[6];
-      sprintf(numbuf, "%05d", idx);  
+      sprintf(numbuf, "%05d", idx);
       Fn = fn  + string(numbuf) + ".dat";
       ostr.open(Fn.c_str(), ios::out );
       ostr.precision(15);
       ostr.setf(ios::scientific, ios::floatfield);
-  
+
       ostr << " x, px, y, py t, pt, id, node" << endl;
 
       unsigned int dataBlocks=0;
       double x,y,z,px,py,pz,id;
       unsigned  vn;
-      
+
       for (unsigned i=0; i < tmp.size(); i+=7)
 	ostr << tmp[i+1] << " " << tmp[i+4] << " " << tmp[i+2]  << " " \
 	     << tmp[i+5] << " " << tmp[i+3] << " " << tmp[i+6]  << " " \
 	     << tmp[i]   << " " << Ippl::myNode() << endl;
-      
-      int notReceived =  Ippl::getNodes() - 1; 
+
+      int notReceived =  Ippl::getNodes() - 1;
       while (notReceived > 0) {
 	int node = COMM_ANY_NODE;
 	Message* rmsg =  Ippl::Comm->receive_block(node, tag);
@@ -362,10 +362,10 @@ public:
       dataBlocks = tmp.size();
       smsg->put(dataBlocks);
       smsg->put(Ippl::myNode());
-      for (unsigned i=0; i < tmp.size(); i++) 
+      for (unsigned i=0; i < tmp.size(); i++)
 	smsg->put(tmp[i]);
-      bool res = Ippl::Comm->send(smsg, 0, tag);	
-      if (! res) 
+      bool res = Ippl::Comm->send(smsg, 0, tag);
+      if (! res)
 	ERRORMSG("Ippl::Comm->send(smsg, 0, tag) failed " << endl;);
     }
   }
@@ -379,13 +379,13 @@ private:
       vbc_m[i] = new ZeroFace<Vector_t,Dim,Mesh_t,Center_t>(i);
     }
   }
-  
+
   inline void setBCAllPeriodic() {
     for (int i=0; i < 2*Dim; i++) {
       this->getBConds()[i] = ParticlePeriodicBCond;
       bc_m[i]  = new PeriodicFace<double  ,Dim,Mesh_t,Center_t>(i);
       vbc_m[i] = new PeriodicFace<Vector_t,Dim,Mesh_t,Center_t>(i);
-    }  
+    }
   }
 
   inline void setBCOOP() {
@@ -397,8 +397,8 @@ private:
     for (int i= 2*Dim - 2; i < 2*Dim; i++) {
       bc_m[i]  = new PeriodicFace<double  ,Dim,Mesh_t,Center_t>(i);
       vbc_m[i] = new PeriodicFace<Vector_t,Dim,Mesh_t,Center_t>(i);
-      this->getBConds()[i] = ParticlePeriodicBCond;    
-    }  
+      this->getBConds()[i] = ParticlePeriodicBCond;
+    }
   }
 
   inline void gatherNGP() {
@@ -427,12 +427,12 @@ private:
 
   Field<Vektor<double,Dim>,Dim> EFD_m;
   Field<double,Dim> EFDMag_m;
-  
+
   BConds<double,Dim,Mesh_t,Center_t> bc_m;
   BConds<Vector_t,Dim,Mesh_t,Center_t> vbc_m;
 
   Vektor<int,Dim> nr_m;
-    
+
   Vector_t hr_m;
   Vector_t rmin_m;
   Vector_t rmax_m;
@@ -441,7 +441,7 @@ private:
   InterPol_t interpol_m;
   bool fieldNotInitialized_m;
   bool doRepart_m;
-  bool withGuardCells_m;  
+  bool withGuardCells_m;
   e_dim_tag decomp_m[Dim];
 
 };
@@ -449,21 +449,21 @@ private:
 int main(int argc, char *argv[]){
   Ippl ippl(argc, argv);
   Inform msg(argv[0]);
-  
-  double memoryPerNode = 2; // GB 
+
+  double memoryPerNode = 2; // GB
   static IpplMemoryUsage::MemRef mainMemWatch = IpplMemoryUsage::getMemObserver("main", memoryPerNode);
   static IpplMemoryUsage::MemRef mallocMemWatch = IpplMemoryUsage::getMemObserver("aftermalloc", memoryPerNode);
 
   IpplMemoryUsage::sample(mainMemWatch,"");
 
   msg << "allocate " << atoi(argv[1]) << " double " << endl;
- 
+
   double *data = (double *)malloc(atoi(argv[1])*sizeof(double));
-  
+
   size_t i = 0;
   for (i=0; i<atoi(argv[1]);i++)
       data[i] = i/3000.;
-  
+
   IpplMemoryUsage::sample(mallocMemWatch,"");
   IpplMemoryUsage::print();
   Ippl::Comm->barrier();
@@ -473,6 +473,5 @@ int main(int argc, char *argv[]){
 /***************************************************************************
  * $RCSfile: addheaderfooter,v $   $Author: adelmann $
  * $Revision: 1.1.1.1 $   $Date: 2003/01/23 07:40:17 $
- * IPPL_VERSION_ID: $Id: addheaderfooter,v 1.1.1.1 2003/01/23 07:40:17 adelmann Exp $ 
- ***************************************************************************/
-
+ * IPPL_VERSION_ID: $Id: addheaderfooter,v 1.1.1.1 2003/01/23 07:40:17 adelmann Exp $
+ ***************************************************************************/
\ No newline at end of file
diff --git a/ippl/test/simple/TestParticleDebug.cpp b/ippl/test/simple/TestParticleDebug.cpp
index 947f4af9e8a4a7d478db70ec78c8cd5ef086015a..692a14eab4345abadf09c287490999f0d1b0de06 100644
--- a/ippl/test/simple/TestParticleDebug.cpp
+++ b/ippl/test/simple/TestParticleDebug.cpp
@@ -2,8 +2,8 @@
 /***************************************************************************
  *
  * The IPPL Framework
- * 
- * This program was prepared by PSI. 
+ *
+ * This program was prepared by PSI.
  * All rights in the program are reserved by PSI.
  * Neither PSI nor the author(s)
  * makes any warranty, express or implied, or assumes any liability or
@@ -17,7 +17,7 @@
 /***************************************************************************
  *
  * The IPPL Framework
- * 
+ *
  *
  * Visit http://people.web.psi.ch/adelmann/ for more details
  *
@@ -62,8 +62,8 @@ class Particles: public IpplParticleBase< ParticleSpatialLayout<double, 3> > {
 public:
   //tjwdebug: add a scalar attribute:
   ParticleAttrib<double> sa;
-  // Constructor: 
-  Particles(ParticleSpatialLayout<double,3>* psl) : 
+  // Constructor:
+  Particles(ParticleSpatialLayout<double,3>* psl) :
     IpplParticleBase<ParticleSpatialLayout<double, 3> >(psl) {
       //tjwdebug: add a scalar attribute:
       addAttribute(sa);
@@ -88,7 +88,7 @@ void  dpap(ParticleAttrib<double>& pattr, bool docomm) {
 void depap(ParticleAttrib<double>& pattr, int i, bool docomm) {
   epap(pattr, i, docomm);
 }
-void dspap(ParticleAttrib<double>& pattr, int base, int bnd, int stride, 
+void dspap(ParticleAttrib<double>& pattr, int base, int bnd, int stride,
 	   bool docomm) {
   spap(pattr, base, bnd, stride, docomm);
 }
@@ -99,7 +99,7 @@ void  dv3pap(ParticleAttrib<Vektor<double,3> >& pattr, bool docomm) {
 void dv3epap(ParticleAttrib<Vektor<double,3> >& pattr, int i, bool docomm) {
   epap(pattr, i, docomm);
 }
-void dv3spap(ParticleAttrib<Vektor<double,3> >& pattr, int base, int bnd, 
+void dv3spap(ParticleAttrib<Vektor<double,3> >& pattr, int base, int bnd,
 	     int stride, bool docomm) {
   spap(pattr, base, bnd, stride, docomm);
 }
@@ -153,7 +153,7 @@ int main(int argc, char *argv[])
   parts.update();
 
   // Inform output objects for test output:
-  Inform* fdip = 
+  Inform* fdip =
     new Inform(NULL,"text.test.TestParticleDebug",Inform::OVERWRITE,0);
   Inform& fdi = *fdip;
 
@@ -222,7 +222,7 @@ int main(int argc, char *argv[])
 
   // Compare the two files by mocking up the Unix "diff" command:
   delete fdip;
-  passed = 
+  passed =
     thediff("text.test.TestParticleDebug","text.correct.TestParticleDebug");
 
   testmsg << ( (passed) ? "PASSED" : "FAILED" ) << endl;
@@ -261,7 +261,7 @@ bool thediff(char* filename1, char* filename2)
 void hardCodedOutput(char* filename)
 {
   ofstream of(filename);
-  of << endl 
+  of << endl
      << "--------pap(parts.ID, true)-------" << endl
      << "....PE = 0 GLOBAL ptcle index subrange (0 : 15 : 1)...." << endl
      << "0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 " << endl
@@ -360,5 +360,5 @@ void hardCodedOutput(char* filename)
 /***************************************************************************
  * $RCSfile: TestParticleDebug.cpp,v $   $Author: adelmann $
  * $Revision: 1.1.1.1 $   $Date: 2003/01/23 07:40:39 $
- * IPPL_VERSION_ID: $Id: TestParticleDebug.cpp,v 1.1.1.1 2003/01/23 07:40:39 adelmann Exp $ 
- ***************************************************************************/
+ * IPPL_VERSION_ID: $Id: TestParticleDebug.cpp,v 1.1.1.1 2003/01/23 07:40:39 adelmann Exp $
+ ***************************************************************************/
\ No newline at end of file
diff --git a/ippl/test/simple/TestParticleDebugParallel.cpp b/ippl/test/simple/TestParticleDebugParallel.cpp
index ed5c399d5b9d322ba67dd0fa992f5d717a915ee2..0a1a2157b32215d532c4139231a9d8eb1a692aa0 100644
--- a/ippl/test/simple/TestParticleDebugParallel.cpp
+++ b/ippl/test/simple/TestParticleDebugParallel.cpp
@@ -2,8 +2,8 @@
 /***************************************************************************
  *
  * The IPPL Framework
- * 
- * This program was prepared by PSI. 
+ *
+ * This program was prepared by PSI.
  * All rights in the program are reserved by PSI.
  * Neither PSI nor the author(s)
  * makes any warranty, express or implied, or assumes any liability or
@@ -17,7 +17,7 @@
 /***************************************************************************
  *
  * The IPPL Framework
- * 
+ *
  *
  * Visit http://people.web.psi.ch/adelmann/ for more details
  *
@@ -35,7 +35,7 @@
 // object that writes into a file makes it easy to do the comparson with
 // correct output.
 
-// JCC: Note that the definitions of the declared functions 
+// JCC: Note that the definitions of the declared functions
 // hardCodedOutput and thediff are not present, so this test
 // code will not compile!
 
@@ -63,8 +63,8 @@ using namespace std;
 // Simple user Particles class definition
 class Particles: public IpplParticleBase< ParticleSpatialLayout<double, 3> > {
 public:
-  // Constructor: 
-  Particles(ParticleSpatialLayout<double,3>* psl) : 
+  // Constructor:
+  Particles(ParticleSpatialLayout<double,3>* psl) :
     IpplParticleBase<ParticleSpatialLayout<double, 3> >(psl) {
   }
   // Destructor.
@@ -87,7 +87,7 @@ void  dpap(ParticleAttrib<double>& pattr, bool docomm) {
 void depap(ParticleAttrib<double>& pattr, int i, bool docomm) {
   epap(pattr, i, docomm);
 }
-void dspap(ParticleAttrib<double>& pattr, int base, int bnd, int stride, 
+void dspap(ParticleAttrib<double>& pattr, int base, int bnd, int stride,
 	   bool docomm) {
   spap(pattr, base, bnd, stride, docomm);
 }
@@ -98,7 +98,7 @@ void  dv3pap(ParticleAttrib<Vektor<double,3> >& pattr, bool docomm) {
 void dv3epap(ParticleAttrib<Vektor<double,3> >& pattr, int i, bool docomm) {
   epap(pattr, i, docomm);
 }
-void dv3spap(ParticleAttrib<Vektor<double,3> >& pattr, int base, int bnd, 
+void dv3spap(ParticleAttrib<Vektor<double,3> >& pattr, int base, int bnd,
 	     int stride, bool docomm) {
   spap(pattr, base, bnd, stride, docomm);
 }
@@ -245,5 +245,5 @@ int main(int argc, char *argv[])
 /***************************************************************************
  * $RCSfile: TestParticleDebugParallel.cpp,v $   $Author: adelmann $
  * $Revision: 1.1.1.1 $   $Date: 2003/01/23 07:40:39 $
- * IPPL_VERSION_ID: $Id: TestParticleDebugParallel.cpp,v 1.1.1.1 2003/01/23 07:40:39 adelmann Exp $ 
- ***************************************************************************/
+ * IPPL_VERSION_ID: $Id: TestParticleDebugParallel.cpp,v 1.1.1.1 2003/01/23 07:40:39 adelmann Exp $
+ ***************************************************************************/
\ No newline at end of file
diff --git a/ippl/test/ttrack/GTChargedParticles/GTChargedParticles.hh b/ippl/test/ttrack/GTChargedParticles/GTChargedParticles.hh
index 4ec0c6af3fc60ef8dbe5753681a99cf4d19862b9..704959502f9030b6b01dfa3baaf90ac1c52c01e0 100644
--- a/ippl/test/ttrack/GTChargedParticles/GTChargedParticles.hh
+++ b/ippl/test/ttrack/GTChargedParticles/GTChargedParticles.hh
@@ -14,7 +14,7 @@ typedef ParticleInteractLayout<double, 3> playout_t;
 template<class PL>
 class ChargedParticles : public IpplParticleBase<PL> {
 
-  
+
   typedef UniformCartesian<3,double>               Mesh_t;
   typedef Cell                                     Center_t;
   typedef CenteredFieldLayout<3, Mesh_t, Center_t> FieldLayout_t;
@@ -30,7 +30,7 @@ class ChargedParticles : public IpplParticleBase<PL> {
 
 
  private:
-    
+
   Field_t  rho_m;
   BConds<double,3,Mesh_t,Center_t> bc_m;
 
@@ -47,7 +47,7 @@ class ChargedParticles : public IpplParticleBase<PL> {
   Vector_t rmean_m, pmean_m;
   Vector_t rrms_m, prms_m, eps_m, rprms_m;
   Vector_t csbeta_m,csgamma_m,csalpha_m;
-  
+
   // macroparticle charge in Cb
   double q_m;
   double spos_m;
@@ -77,10 +77,10 @@ class ChargedParticles : public IpplParticleBase<PL> {
   double deltau_analytic;
   double deltau_semianalytic;
   unsigned events;
-  
+
 public:
 
-  // the attributes for this set of particles (atoms).  
+  // the attributes for this set of particles (atoms).
 
   ParticleInteractAttrib< Vektor<double,3> > P;
   ParticleInteractAttrib< double > Q;
@@ -101,45 +101,45 @@ public:
     Inform msg("ChargedParticles ");
 
     IpplRandom.SetSeed(static_cast<unsigned long>(23131719));
-	
+
     Mesh_t *mesh;
     FieldLayout_t *FL;
     NDIndex<3> domain;
     e_dim_tag decomp[3];
 
     Vektor<int,3> nr(simCfg.nx,simCfg.ny,simCfg.nz);
-    
+
     for(int i=0; i<3; i++)
       domain[i] = domain[i] = Index(nr[i] + 1);
-  
-    for (int d=0; d < 3; ++d) 
-      decomp[d] = (d == parallelDim) ? PARALLEL : SERIAL; 
-  
+
+    for (int d=0; d < 3; ++d)
+      decomp[d] = (d == parallelDim) ? PARALLEL : SERIAL;
+
     // create mesh and layout objects for this problem domain
-    
+
     mesh = new Mesh_t(domain);
     FL   = new FieldLayout_t(*mesh, decomp);
 
     initialize(new PL(*FL,*mesh));
-    
+
     // register our attributes with the base class
     addAttribute(P);
     addAttribute(Q);
     addAttribute(collided);
-    
+
     // set the interaction radius for the atoms.
     getLayout().setInteractionRadius(interrad_m);
-    
+
     lost_num = 0;
     lost2_num = 0;
-    
+
     for (int i=0; i < 2*3; ++i) {
       bc_m[i] = new ZeroFace<double,3,Mesh_t,Center_t>(i);
       getBConds()[i] = ParticleNoBCond;
     }
-    
+
     rho_m.initialize(getMesh(), getFieldLayout(), GuardCellSizes<Dim>(1), bc_m);
-    
+
     msg << " Field and domain construction done = " << domain << endl;
 
     deltau = 0;
@@ -149,28 +149,28 @@ public:
     deltau_semianalytic = 0;
     events = 0;
   }
-  
-  /** 
+
+  /**
    * Interpolates the charge in Q onto a grid rho_m
    * @param none
    * @return none
-   */  
+   */
   void scatterQ() {
-    rho_m = 0.0;                                  
-    Q.scatter(rho_m, this->R, IntrplNGP_t());                             
+    rho_m = 0.0;
+    Q.scatter(rho_m, this->R, IntrplNGP_t());
   }
-  
-  /** 
-   * Shows how to work with fields and validated the 
+
+  /**
+   * Shows how to work with fields and validated the
    * charge deposition method. Is used if FIELDCHEK
    * is defined
    * @param none
    * @return none
-   */  
+   */
   void checkScatteredQ() {
-    
+
     Inform m("checkScatteredQ ");
-    
+
     NDIndex<Dim> idx = getFieldLayout().getLocalNDIndex();
     NDIndex<Dim> elem;
     double lQ = 0.0;
@@ -179,12 +179,12 @@ public:
     double gV = 0.0;
 
     for (int i=idx[0].min(); i<=idx[0].max(); ++i) {
-      elem[0]=Index(i,i); 
+      elem[0]=Index(i,i);
       for (int j=idx[1].min(); j<=idx[1].max(); ++j) {
 	elem[1]=Index(j,j);
 	for (int k=idx[2].min(); k<=idx[2].max(); ++k) {
-	  elem[2]=Index(k,k);	
-	  lQ += rho_m.localElement(elem);	
+	  elem[2]=Index(k,k);
+	  lQ += rho_m.localElement(elem);
 	  lV += getMesh().getCellVolume(elem);
 	}
       }
@@ -197,7 +197,7 @@ public:
     m << "gQ= " << gQ << " gV= " << gV << " hr= " << hr_m << endl;
     m << "s1Q= " << s1Q << " s2Q= " << s2Q << " delta= " << abs(s1Q-s2Q) << endl;
   }
-    
+
 
   double getLocalVolumes(Vector_t r) {
     double ret=0;
@@ -205,7 +205,7 @@ public:
     NDIndex<Dim> elem = getMesh().getCellContaining(r);
     if (lIdx.contains(elem)) {
       ret = getMesh().getCellVolume(elem);
-    }    
+    }
     return ret;
   }
 
@@ -216,18 +216,18 @@ public:
     NDIndex<Dim> elem = getMesh().getCellContaining(r);
     if (lIdx.contains(elem)) {
       ret = rho_m.localElement(elem);
-    }    
+    }
     return ret;
   }
 
 
 
 
-  /** 
+  /**
    * Calculats the local density at a given particle position r
-   * @param r position of the particle 
-   * @return local density in [Q m**-3] 
-   */  
+   * @param r position of the particle
+   * @return local density in [Q m**-3]
+   */
   double getLocalDensity(Vector_t r) {
     double den=0;
     NDIndex<Dim> lIdx = getFieldLayout().getLocalNDIndex();
@@ -236,16 +236,16 @@ public:
       double lDen = rho_m.localElement(elem);
       double lVol = getMesh().getCellVolume(elem);
       den = lDen/lVol;
-    }    
+    }
     return den;
   }
 
-  /** 
+  /**
    * Calculats the analytic local density at a given particle position r
-   * @param r position of the particle 
-   * @param p momentum of the particle 
-   * @return local density in [Q m**-3] 
-   */  
+   * @param r position of the particle
+   * @param p momentum of the particle
+   * @return local density in [Q m**-3]
+   */
   double getLocalDensityAnalytic(Vector_t r, Vector_t p) {
     Vector_t e = get_emit();
     Vector_t a = get_csalpha();
@@ -256,7 +256,7 @@ public:
 
     for(unsigned i = 0; i < 3; i++)
       rho(i) = 1 / (2 * Physics::pi * e(i)) * exp(- abs(1/(2 * e(i)) * (g(i) * r(i) * r(i) + (i == 2 ? 2 * a(i) * r(i) * p(i) : 0) + b(i) * p(i) * p(i))));
-    
+
     return rho(0) * rho(1) * rho(2);
   }
 
@@ -268,13 +268,13 @@ public:
     return Physics::pi * 4 / 3 * pow(5.0,3.0) * get_rrms()(0) * get_rrms()(1) * get_rrms()(2);
   }
 
- /** 
+ /**
    * Prototypes implemented in GTChargedParticles.cpp
-   * 
-   * 
-   * 
-   */   
-  
+   *
+   *
+   *
+   */
+
   void openFiles(string baseFn, string title,bool restartMode);
   void closeFiles();
   void calcBeamParameters();
@@ -286,12 +286,12 @@ public:
   void writePhaseSpaceSDDS(string baseName);
   void writePartSDDSHeader(string title, unsigned int N, double qTot);
 
- /** 
+ /**
    * Sets the interaction radius. This is the sphere in which getPairList
    * will be looking for particles
    * @param r radius of tghe sphere
-   * 
-   */  
+   *
+   */
   void setInteractionRadius(double r) {getLayout().setInteractionRadius(r);}
 
   /**
@@ -313,7 +313,7 @@ public:
     collided[i] = 1;
     collided[j] = 1;
   }
-  
+
   inline const Mesh_t& getMesh() const { return getLayout().getLayout().getMesh(); }
   inline       Mesh_t& getMesh() { return getLayout().getLayout().getMesh(); }
   inline const FieldLayout_t& getFieldLayout() const {
@@ -326,19 +326,19 @@ public:
   inline bool isRoot() { return Ippl::myNode()==0; }
 
   void boundp() {
-    
+
     bounds(R,rmin_m,rmax_m);
     bounds(P,pmin_m,pmax_m);
-    
+
     NDIndex<3> domain = getFieldLayout().getDomain();
     for(int i=0; i<3; i++)
       nr_m[i] = domain[i].length();
-    
+
     Vektor<double,3> len = (rmax_m - rmin_m);
-      
+
     for(int i=0; i<3; i++)
       hr_m[i]    = (len[i] / (nr_m[i]-1));
-      
+
     // rescale mesh
     getMesh().set_meshSpacing(&(hr_m[0]));
     getMesh().set_origin( rmin_m );
@@ -346,117 +346,117 @@ public:
     //    BinaryRepartition(*this);
     update();
 
-    rho_m.initialize(getMesh(), getFieldLayout(), GuardCellSizes<Dim>(1), bc_m);                     
+    rho_m.initialize(getMesh(), getFieldLayout(), GuardCellSizes<Dim>(1), bc_m);
   }
 
- /** 
-   * 
-   * 
-   * 
+ /**
+   *
+   *
+   *
    * @return the macroparticle charge in Cb
-   */  
+   */
   inline double getMoment(int i, int j) {return moments_m[i][j];}
 
 
- /** 
-   * 
-   * 
-   * 
+ /**
+   *
+   *
+   *
    * @return the macroparticle charge in Cb
-   */  
+   */
   //void writePartSDDSHeader(string title, unsigned int N, double qTot);
 
 
- /** 
-   * 
-   * 
-   * 
+ /**
+   *
+   *
+   *
    * @return the macroparticle charge in Cb
-   */  
+   */
   inline double getQ()    { return q_m;}
-  
-  
-  /** 
-   * 
-   * 
-   * 
+
+
+  /**
+   *
+   *
+   *
    * @return the actual simulation time [s]
-   */    
+   */
   inline double getTime()  { return spos_m; }
-  
 
-  /** 
-   * 
-   * 
-   * 
+
+  /**
+   *
+   *
+   *
    * @return increment the simulation time [s]
-   */  
+   */
   inline void incTime(double tInc) { actTime_m += tInc;}
- 
 
-  /** 
-   * 
-   * 
-   * 
+
+  /**
+   *
+   *
+   *
    * @return the relativistic factor []
-   */  
+   */
   inline double getGamma() {return pdata_m.getGamma();}
 
 
-  /** 
-   * 
-   * 
-   * 
+  /**
+   *
+   *
+   *
    * @return beta v/c []
-   */  
+   */
   inline double getBeta()  {return pdata_m.getBeta();}
-  
-  
-  /** 
-   * 
-   * 
-   * 
+
+
+  /**
+   *
+   *
+   *
    * @return get the actual position along the design orbit [m]
-   */  
+   */
   inline double set_spos(double s) { spos_m = s; }
- 
-  /** 
-   * 
-   * 
-   * 
+
+  /**
+   *
+   *
+   *
    * @return get the actual position along the design orbit [m]
-   */  
+   */
   inline double get_spos() { return spos_m; }
 
 
 
-  /** 
-   * 
-   * 
-   * 
+  /**
+   *
+   *
+   *
    * @return get the total charge of the bunch [Cb]
-   */  
+   */
   inline double getQTot() { return getTotalNum()*q_m; }
 
 
 
-  /** 
+  /**
    *    * --------- max
    *    *     0/0
    *    * --------- *
    *
    * @return get the maximal (max) extent of the bunch [m]
-   */  
+   */
   inline Vector_t get_maxExtend() { return rmax_m; }
 
-  
-  /** 
+
+  /**
    *    * --------- *
    *    *     0/0
    *  min --------- *
    *
    * @return get the minimal (min) extent of the bunch [m]
-   */  
+   */
   inline Vector_t get_origin() { return rmin_m; }
 
 
@@ -469,7 +469,7 @@ public:
   inline Vector_t get_csbeta() const { return csbeta_m; }
   inline Vector_t get_csgamma() const { return csgamma_m; }
   inline Vector_t get_csalpha() const { return csalpha_m; }
- 
+
   inline Vector_t get_rmean() const { return rmean_m; }
   inline Vector_t get_pmean() const { return pmean_m; }
   inline Vector_t get_rrms() const { return rrms_m; }
@@ -488,19 +488,19 @@ public:
 
   /**
    * @param the number of collisions during the computation
-   */  
+   */
   inline void set_collisionnum(unsigned n) {collision_num = n;}
-  /** 
+  /**
    * add_lost increases the number of particles lost by touschek scattering in the
    * longitudinal directions
    * @param i number of lost particles
    */
   inline void add_lost(int i) {lost_num+=i;}
-  /** 
+  /**
    * add_lost2 increases the number of particles lost by touschek scattering in the
    * transversal directions
    * @param i number of lost particles
-   */  
+   */
   inline void add_lost2(int i) {lost2_num =+ i;}
   /**
    * @return the number of particles lost due to longitudinal scattering
@@ -558,27 +558,27 @@ public:
   void writeRestartInfo(string basename, unsigned turn);
 
   void getInbalance(string fn, bool first) {
-  
+
     unsigned long int locN = getLocalNum();
     unsigned long int idealN = getTotalNum()/Ippl::getNodes();
     ofstream of;
- 
-    /* 
+
+    /*
        Get the particle inbalance from all the nodes
     */
     double  *locBal  = (double*) malloc(Ippl::getNodes()*sizeof(double));
     double  *globBal = (double*) malloc(Ippl::getNodes()*sizeof(double));
-  
-    for(int i=0; i<Ippl::getNodes(); i++) 
+
+    for(int i=0; i<Ippl::getNodes(); i++)
       locBal[i]=globBal[i]=0.0;
-  
+
     locBal[Ippl::myNode()] = locN;
-    
+
     reduce(locBal, locBal + Ippl::getNodes(), globBal, OpAddAssign());
-    
+
     if (first && isRoot()) {
       of.open(fn.c_str(),ios::out);
-      of << "# inbalance N_i, i=1.." << Ippl::getNodes() << " and Ntotal " << endl;  
+      of << "# inbalance N_i, i=1.." << Ippl::getNodes() << " and Ntotal " << endl;
       for(int i=0; i<Ippl::getNodes(); i++)
 	of << globBal[i] << "\t";
       of << getTotalNum() << endl;
@@ -598,4 +598,4 @@ public:
   }
 };
 #include "GTChargedParticles.cpp"
-#endif
+#endif
\ No newline at end of file
diff --git a/src/AbstractObjects/Attribute.cpp b/src/AbstractObjects/Attribute.cpp
index 679918d60b7fe213bdb3b95f553ef18ca5bd377d..b32ff9e2be07db1a2ca7a81a274664252cd5275e 100644
--- a/src/AbstractObjects/Attribute.cpp
+++ b/src/AbstractObjects/Attribute.cpp
@@ -30,17 +30,23 @@ extern Inform *gmsg;
 // ------------------------------------------------------------------------
 
 Attribute::Attribute():
-    base(), handler()
+    base(),
+    handler(),
+    isDefault(true)
 {}
 
 
 Attribute::Attribute(const Attribute &rhs):
-    base(rhs.base), handler(rhs.handler)
+    base(rhs.base),
+    handler(rhs.handler),
+    isDefault(rhs.isDefault)
 {}
 
 
 Attribute::Attribute(AttributeHandler *h, AttributeBase *b):
-    base(b), handler(h)
+    base(b),
+    handler(h),
+    isDefault(true)
 {}
 
 
@@ -118,21 +124,25 @@ void Attribute::setReadOnly(bool flag) {
 
 void Attribute::parse(Statement &stat, bool eval) {
     handler->parse(*this, stat, eval);
+    isDefault = false;
 }
 
 
 void Attribute::parseComponent(Statement &stat, bool eval, int index) {
     handler->parseComponent(*this, stat, eval, index);
+    isDefault = false;
 }
 
 
 void Attribute::set(AttributeBase *newBase) {
     base = newBase;
+    isDefault = false;
 }
 
 
 void Attribute::setDefault() {
     base = handler->getDefault();
+    isDefault = true;
 }
 
 
@@ -162,4 +172,4 @@ std::ostream &operator<<(std::ostream &os, const Attribute &attr) {
     }
 
     return os;
-}
+}
\ No newline at end of file
diff --git a/src/AbstractObjects/Attribute.h b/src/AbstractObjects/Attribute.h
index be0f67f946171ff596f13b9ef7b9ab16eca1c5d4..b2547e93734fc1989ed551c8e145f406b6e9fa27 100644
--- a/src/AbstractObjects/Attribute.h
+++ b/src/AbstractObjects/Attribute.h
@@ -153,6 +153,7 @@ public:
     //  Print the attribute name, followed by an equals sign and its value.
     void print(int &len) const;
 
+    bool defaultUsed() const;
 private:
 
     // Pointer to the value.  The value can be shared for several objects.
@@ -160,6 +161,8 @@ private:
 
     // Pointer to the shared attribute parser.
     Pointer<AttributeHandler> handler;
+
+    bool isDefault;
 };
 
 
@@ -170,7 +173,10 @@ inline Attribute::operator bool() const {
     return base != 0;
 }
 
+inline bool Attribute::defaultUsed() const {
+    return isDefault;
+}
 
 extern std::ostream &operator<<(std::ostream &os, const Attribute &attr);
 
-#endif // OPAL_Attribute_HH
+#endif // OPAL_Attribute_HH
\ No newline at end of file
diff --git a/src/AbstractObjects/CMakeLists.txt b/src/AbstractObjects/CMakeLists.txt
index 7cf2000139ec3eb45096fe455859e18b0d78ed18..82abf02bb4eb79ca99c925bc378c206db1599760 100644
--- a/src/AbstractObjects/CMakeLists.txt
+++ b/src/AbstractObjects/CMakeLists.txt
@@ -23,4 +23,28 @@ include_directories (
   ${CMAKE_CURRENT_SOURCE_DIR}
 )
 
-add_sources(${_SRCS})
+add_opal_sources(${_SRCS})
+
+set (HDRS
+    Action.h
+    AttributeBase.h
+    Attribute.h
+    AttributeHandler.h
+    BeamSequence.h
+    Definition.h
+    Directory.h
+    Editor.h
+    Element.h
+    Expressions.h
+    Invalidator.h
+    ObjectFunction.h
+    Object.h
+    OpalData.h
+    PlaceRep.h
+    RangeRep.h
+    Table.h
+    TableRowRep.h
+    ValueDefinition.h
+)
+
+install (FILES ${HDRS} DESTINATION "${CMAKE_INSTALL_PREFIX}/include/AbstractObjects")
\ No newline at end of file
diff --git a/src/AbstractObjects/Object.h b/src/AbstractObjects/Object.h
index 2511e637078ad5d4e3df37cdebb58c573a8cc25e..2bf55e829e04fe37e7ccfcec7557b80b652dbb03 100644
--- a/src/AbstractObjects/Object.h
+++ b/src/AbstractObjects/Object.h
@@ -117,6 +117,8 @@ public:
     //  Print a OPAL-readable image of [b]this[/b] on the given output stream.
     virtual void print(std::ostream &) const;
 
+    virtual void printValue(std::ostream &) const;
+
     /// Print help.
     //  Print help information for [b]this[/b] on the given output stream.
     virtual void printHelp(std::ostream &) const;
@@ -270,4 +272,9 @@ private:
 // ------------------------------------------------------------------------
 extern std::ostream &operator<<(std::ostream &os, const Object &object);
 
-#endif // OPAL_Object_HH
+inline
+void Object::printValue(std::ostream &os) const {
+    print(os);
+}
+
+#endif // OPAL_Object_HH
\ No newline at end of file
diff --git a/src/AbstractObjects/OpalData.cpp b/src/AbstractObjects/OpalData.cpp
index 1390dffe6a9aa0b7f725d4475dc2c16345258ee2..8a7ad44d109e25f4e0a511bc7d3c9647878851ce 100644
--- a/src/AbstractObjects/OpalData.cpp
+++ b/src/AbstractObjects/OpalData.cpp
@@ -45,6 +45,7 @@
 #include "Algorithms/bet/EnvelopeBunch.h"
 // /DTA
 
+#define MAX_NUM_INSTANCES 10
 using namespace std;
 
 // Class OpalData::ClearReference
@@ -80,19 +81,21 @@ struct OpalDataImpl {
     typedef std::set<AttributeBase *>::iterator exprIterator;
 
     // The page title from the latest TITLE command.
-    std::string itsTitle;
+    std::string itsTitle_m;
+
+    bool hasPriorRun_m;
 
     // true if we restart a simulation
-    bool isRestart;
+    bool isRestart_m;
 
     // Input file name
-    std::string inputFn;
+    std::string inputFn_m;
 
     // Where to resume in a restart run
-    int restartStep;
+    int restartStep_m;
 
     // Where to resume in a restart run
-    std::string restartFn;
+    std::string restartFn_m;
 
     // true if the name of a restartFile is specified
     bool hasRestartFile_m;
@@ -136,21 +139,23 @@ struct OpalDataImpl {
     Layout_t *PL_m;
 
     // the accumulated (over all TRACKs) number of steps
-    unsigned long long maxTrackSteps;
+    unsigned long long maxTrackSteps_m;
 
     bool isInOPALCyclMode_m;
     bool isInOPALTMode_m;
     bool isInOPALEnvMode_m;
 
+    bool isInPrepState_m;
 };
 
 
 OpalDataImpl::OpalDataImpl():
-    mainDirectory(), referenceMomentum(0), modified(false), itsTitle(),
+    mainDirectory(), referenceMomentum(0), modified(false), itsTitle_m(),
     restart_dump_freq_m(1), last_step_m(0),
     isInOPALCyclMode_m(false),
     isInOPALTMode_m(false),
-    isInOPALEnvMode_m(false)
+    isInOPALEnvMode_m(false),
+    isInPrepState_m(false)
 {
     bunch_m = 0;
     slbunch_m = 0;
@@ -183,13 +188,14 @@ OpalDataImpl::~OpalDataImpl() {
 // Class OpalData
 // ------------------------------------------------------------------------
 
-bool OpalData::isInstatiated = false;
+bool OpalData::isInstantiated = false;
 OpalData *OpalData::instance = 0;
+std::stack<OpalData*> OpalData::stashedInstances;
 
 OpalData *OpalData::getInstance() {
-    if(!isInstatiated) {
+    if(!isInstantiated) {
         instance = new OpalData();
-        isInstatiated = true;
+        isInstantiated = true;
         return instance;
     } else {
         return instance;
@@ -199,35 +205,61 @@ OpalData *OpalData::getInstance() {
 void OpalData::deleteInstance() {
     delete instance;
     instance = 0;
-    isInstatiated = false;
+    isInstantiated = false;
+}
+
+void OpalData::stashInstance() {
+    if (!isInstantiated) return;
+    if (stashedInstances.size() + 1 > MAX_NUM_INSTANCES) {
+        throw OpalException("OpalData::stashInstance()",
+                            "too many OpalData instances stashed");
+    }
+    stashedInstances.push(instance);
+    instance = 0;
+    isInstantiated = false;
+}
+
+OpalData *OpalData::popInstance() {
+    if (stashedInstances.size() == 0) {
+        throw OpalException("OpalData::popInstance()",
+                            "no OpalData instances stashed");
+    }
+    if (isInstantiated) deleteInstance();
+    instance = stashedInstances.top();
+    isInstantiated = true;
+    stashedInstances.pop();
+
+    return instance;
 }
 
 unsigned long long OpalData::getMaxTrackSteps() {
-    return p->maxTrackSteps;
+    return p->maxTrackSteps_m;
 }
 
 void OpalData::setMaxTrackSteps(unsigned long long s) {
-    p->maxTrackSteps = s;
+    p->maxTrackSteps_m = s;
 }
 
 void OpalData::incMaxTrackSteps(unsigned long long s) {
-    p->maxTrackSteps += s;
+    p->maxTrackSteps_m += s;
 }
 
 
 OpalData::OpalData() {
     p = new OpalDataImpl();
-    p->isRestart = false;
+    p->hasPriorRun_m = false;
+    p->isRestart_m = false;
     p->hasRestartFile_m = false;
     p->hasBunchAllocated_m = false;
     p->hasDataSinkAllocated_m = false;
     p->hasSLBunchAllocated_m = false;
     p->gPhaseShift_m = 0.0;
     p->maxPhases_m.clear();
-    p->maxTrackSteps = 0;
+    p->maxTrackSteps_m = 0;
     p->isInOPALCyclMode_m = false;
     p->isInOPALTMode_m = false;
     p->isInOPALEnvMode_m = false;
+    p->isInPrepState_m = false;
 }
 
 OpalData::~OpalData() {
@@ -237,7 +269,8 @@ OpalData::~OpalData() {
 void OpalData::reset() {
     delete p;
     p = new OpalDataImpl();
-    p->isRestart = false;
+    p->hasPriorRun_m = false;
+    p->isRestart_m = false;
     p->hasRestartFile_m = false;
     p->hasBunchAllocated_m = false;
     p->hasDataSinkAllocated_m = false;
@@ -247,56 +280,73 @@ void OpalData::reset() {
     p->isInOPALCyclMode_m = false;
     p->isInOPALTMode_m = false;
     p->isInOPALEnvMode_m = false;
+    p->isInPrepState_m = false;
 }
 
 bool OpalData::isInOPALCyclMode() {
-  return p->isInOPALCyclMode_m;
+    return p->isInOPALCyclMode_m;
 }
 
 bool OpalData::isInOPALTMode() {
-  return  p->isInOPALTMode_m;
+    return  p->isInOPALTMode_m;
 }
 bool OpalData::isInOPALEnvMode() {
-  return p->isInOPALEnvMode_m;
+    return p->isInOPALEnvMode_m;
 }
 
 void OpalData::setInOPALCyclMode() {
-  p->isInOPALCyclMode_m = true;
+    p->isInOPALCyclMode_m = true;
 }
 
 void OpalData::setInOPALTMode() {
-  p->isInOPALTMode_m = true;
+    p->isInOPALTMode_m = true;
 }
 
 void OpalData::setInOPALEnvMode() {
-  p->isInOPALEnvMode_m = true;
+    p->isInOPALEnvMode_m = true;
+}
+
+bool OpalData::isInPrepState() {
+    return p->isInPrepState_m;
+}
+
+void OpalData::setInPrepState(bool state) {
+    p->isInPrepState_m = state;
+}
+
+bool OpalData::hasPriorTrack() {
+    return p->hasPriorRun_m;
+}
+
+void OpalData::setPriorTrack(const bool &value) {
+    p->hasPriorRun_m = value;
 }
 
 bool OpalData::inRestartRun() {
-    return p->isRestart;
+    return p->isRestart_m;
 }
 
 void OpalData::setRestartRun(const bool &value) {
-    p->isRestart = value;
+    p->isRestart_m = value;
 }
 
 
 void OpalData::setRestartStep(int s) {
-    p->restartStep = s;
+    p->restartStep_m = s;
 }
 
 int OpalData::getRestartStep() {
-    return p->restartStep;
+    return p->restartStep_m;
 }
 
 
 std::string OpalData::getRestartFileName() {
-    return p->restartFn;
+    return p->restartFn_m;
 }
 
 
 void OpalData::setRestartFileName(std::string s) {
-    p->restartFn = s;
+    p->restartFn_m = s;
     p->hasRestartFile_m = true;
 }
 
@@ -625,28 +675,28 @@ void OpalData::setP0(ValueDefinition *p0) {
 
 
 void OpalData::storeTitle(const std::string &title) {
-    p->itsTitle = title;
+    p->itsTitle_m = title;
 }
 
 void OpalData::storeInputFn(const std::string &fn) {
-    p->inputFn = fn;
+    p->inputFn_m = fn;
 }
 
 
 void OpalData::printTitle(std::ostream &os) {
-    os << p->itsTitle;
+    os << p->itsTitle_m;
 }
 
 std::string OpalData::getTitle() {
-    return p->itsTitle;
+    return p->itsTitle_m;
 }
 
 std::string OpalData::getInputFn() {
-    return p->inputFn;
+    return p->inputFn_m;
 }
 
 std::string OpalData::getInputBasename() {
-    std::string & fn = p->inputFn;
+    std::string & fn = p->inputFn_m;
     int const pdot = fn.rfind(".");
     return fn.substr(0, pdot);
 }
@@ -744,4 +794,4 @@ std::vector<std::string> OpalData::getAllNames() {
     //// /DTA
 
     return result;
-}
\ No newline at end of file
+}
diff --git a/src/AbstractObjects/OpalData.h b/src/AbstractObjects/OpalData.h
index 61b163f92c1073cb12b7eaa3d5372a0441785308..481f4766395e5d8c04a608cb45607a4b00424c1c 100644
--- a/src/AbstractObjects/OpalData.h
+++ b/src/AbstractObjects/OpalData.h
@@ -23,6 +23,7 @@
 #include <string>
 #include <vector>
 #include <map>
+#include <stack>
 
 class PartBunch;
 class EnvelopeBunch;
@@ -56,6 +57,10 @@ public:
 
     static void deleteInstance();
 
+    static void stashInstance();
+
+    static OpalData *popInstance();
+
     ~OpalData();
 
     /// reset object for consecutive runs
@@ -147,6 +152,15 @@ public:
     void setInOPALTMode();
     void setInOPALEnvMode();
 
+    bool isInPrepState();
+    void setInPrepState(bool state);
+
+    /// true if in follow-up track
+    bool hasPriorTrack();
+
+    /// true if in follow-up track
+    void setPriorTrack(const bool &value = true);
+
     /// true if we do a restart run
     bool inRestartRun();
 
@@ -243,8 +257,9 @@ public:
 
 private:
 
-    static bool isInstatiated;
+    static bool isInstantiated;
     static OpalData *instance;
+    static std::stack<OpalData*> stashedInstances;
 
     OpalData();
 
@@ -258,4 +273,4 @@ private:
 
 //extern OpalData OPAL;
 
-#endif // OPAL_OpalData_HH
\ No newline at end of file
+#endif // OPAL_OpalData_HH
diff --git a/src/Algebra/CMakeLists.txt b/src/Algebra/CMakeLists.txt
index e4ecad8661412fdd28b3f08d7deac9ba06cda1f8..4e11a5d35b49b57e25359c8ccdd026e8c4982386 100644
--- a/src/Algebra/CMakeLists.txt
+++ b/src/Algebra/CMakeLists.txt
@@ -6,4 +6,10 @@ include_directories (
   ${CMAKE_CURRENT_SOURCE_DIR}
 )
 
-add_sources(${_SRCS})
+add_opal_sources(${_SRCS})
+
+set (HDRS
+    QRSolver.h
+)
+
+install (FILES ${HDRS} DESTINATION "${CMAKE_INSTALL_PREFIX}/include/Algebra")
\ No newline at end of file
diff --git a/src/Algorithms/AutophaseTracker.cpp b/src/Algorithms/AutophaseTracker.cpp
index b08d57fe438568805218f54c7cb96389763c38e9..cf957dbbc7c8c66ec25b528f67c22c9facb6c2c8 100644
--- a/src/Algorithms/AutophaseTracker.cpp
+++ b/src/Algorithms/AutophaseTracker.cpp
@@ -35,7 +35,6 @@ AutophaseTracker::AutophaseTracker(const Beamline &beamline,
         itsBunch_m.Bin[0] = 0;
         itsBunch_m.Q[0] = itsBunch_m.getChargePerParticle();
         itsBunch_m.PType[0] = ParticleType::REGULAR;
-        itsBunch_m.LastSection[0] = 0;
     }
 
     visitBeamline(beamline);
@@ -63,15 +62,13 @@ void AutophaseTracker::execute(const std::queue<double> &dtAllTracks,
     std::queue<double> maxSPosAutoPhasing(maxZ);
     std::queue<unsigned long long> maxStepsAutoPhasing(maxTrackSteps);
 
-    maxSPosAutoPhasing.back() = itsOpalBeamline_m.calcBeamlineLenght();
+    maxSPosAutoPhasing.back() = itsOpalBeamline_m.calcBeamlineLength();
 
     size_t step = 0;
     const int dtfraction = DTFRACTION;
     double newDt = dtAutoPhasing.front() / dtfraction;
     double scaleFactor = newDt * Physics::c;
 
-    itsBunch_m.LastSection[0] -= 1;
-    itsOpalBeamline_m.getSectionIndexAt(refR, itsBunch_m.LastSection[0]);
     itsOpalBeamline_m.print(*gmsg);
 
     itsOpalBeamline_m.switchAllElements();
@@ -398,10 +395,6 @@ void AutophaseTracker::evaluateField() {
     itsBunch_m.Ef = Vector_t(0.0);
     itsBunch_m.Bf = Vector_t(0.0);
 
-    long ls = itsBunch_m.LastSection[0];
-    itsOpalBeamline_m.getSectionIndexAt(refR, ls);
-    itsBunch_m.LastSection[0] = ls;
-
     Vector_t externalE, externalB;
     itsOpalBeamline_m.getFieldAt(0, refR, ls, itsBunch_m.getT() + itsBunch_m.dt[0] / 2., externalE, externalB);
 
@@ -576,4 +569,4 @@ void AutophaseTracker::save(const std::string &fname) {
     }
 
     out.close();
-}
\ No newline at end of file
+}
diff --git a/src/Algorithms/CMakeLists.txt b/src/Algorithms/CMakeLists.txt
index c7a20b1840624ee4515f5121a4f71fa019820cad..87df74b089213f270de0d5a6f3997c0c84a4a398 100644
--- a/src/Algorithms/CMakeLists.txt
+++ b/src/Algorithms/CMakeLists.txt
@@ -1,13 +1,19 @@
 set (_SRCS
+  IndexMap.cpp
+  OrbitThreader.cpp
   BeamBeam3D.cpp
   LieMapper.cpp
+  NilTracker.cpp
   MPSplitIntegrator.cpp
   ThickMapper.cpp
   ThickTracker.cpp
-  AutophaseTracker.cpp
+  # AutophaseTracker.cpp
+  CavityAutophaser.cpp
   ParallelTTracker.cpp
   ParallelCyclotronTracker.cpp
-  ParallelSliceTracker.cpp
+  # ParallelSliceTracker.cpp
+  StatisticalErrors.cpp
+  StatisticalErrorsUtilities.cpp
   TransportMapper.cpp
   bet/EnvelopeSlice.cpp
   bet/EnvelopeBunch.cpp
@@ -28,4 +34,43 @@ include_directories (
   ${CMAKE_CURRENT_SOURCE_DIR}
 )
 
-add_sources(${_SRCS})
\ No newline at end of file
+add_opal_sources(${_SRCS})
+
+set (HDRS
+    AutophaseTracker.h
+    BeamBeam3D.h
+    CavityAutophaser.h
+    Ctunes.h
+    Ctunes.hpp
+    IndexMap.h
+    LieMapper.h
+    lomb.h
+    lomb.hpp
+    MPSplitIntegrator.h
+    NilTracker.h
+    OrbitThreader.h
+    ParallelCyclotronTracker.h
+    ParallelSliceTracker.h
+    ParallelTTracker.h
+    StatisticalErrors.h
+    StatisticalErrorsUtilities.h
+    ThickMapper.h
+    ThickTracker.h
+    TransportMapper.h
+    bet/BetError.h
+    bet/EnvelopeBunch.h
+    bet/EnvelopeSlice.h
+    bet/error.h
+    bet/profile.h
+    bet/math/functions.h
+    bet/math/integrate.h
+    bet/math/interpol.h
+    bet/math/linfit.h
+    bet/math/rk.h
+    bet/math/root.h
+    bet/math/savgol.h
+    bet/math/sort.h
+    bet/math/svdfit.h
+)
+
+install (FILES ${HDRS} DESTINATION "${CMAKE_INSTALL_PREFIX}/include/Algorithms")
\ No newline at end of file
diff --git a/src/Algorithms/Ctunes.h b/src/Algorithms/Ctunes.h
index 847a7f4bd0a6dfa1d4e2671f340b0cbed80d4256..1a3016582a095c361978778751c9469ed84546f8 100644
--- a/src/Algorithms/Ctunes.h
+++ b/src/Algorithms/Ctunes.h
@@ -21,8 +21,8 @@ public:
     TUNE_class(); //constructor
     virtual ~TUNE_class(void);       //destructor
 
-    int LombAnalysis(double *x, double *y, int Ndat, int nhis);
-    int LombAnalysis(std::vector<double> &x, std::vector<double> &y, int nhis, double Norm);
+    int lombAnalysis(double *x, double *y, int Ndat, int nhis);
+    int lombAnalysis(std::vector<double> &x, std::vector<double> &y, int nhis, double Norm);
 
 
 };
diff --git a/src/Algorithms/Ctunes.hpp b/src/Algorithms/Ctunes.hpp
index 53d83bffa9d4e618863c1f514d8714af693c9445..d2dbc089d990947f4b98578c0746b95d33b759e2 100644
--- a/src/Algorithms/Ctunes.hpp
+++ b/src/Algorithms/Ctunes.hpp
@@ -46,7 +46,7 @@ TUNE_class::~TUNE_class(void)
 
 }
 
-int TUNE_class::LombAnalysis(std::vector<double> &x, std::vector<double> &y, int nhis, double Norm)
+int TUNE_class::lombAnalysis(std::vector<double> &x, std::vector<double> &y, int nhis, double Norm)
 /*-----------------------------------------------------------------------------
  *  Launch Lomb analysis and plot results
  *  =======================================
@@ -124,7 +124,7 @@ int TUNE_class::LombAnalysis(std::vector<double> &x, std::vector<double> &y, int
             pairy[pairc] = lodata2[i].y;
             if((pairy[pairc] > pairy[pairc-1]) &&
                (pairy[pairc] > lodata2[i+1].y)) {
-                probi = la->Signi(&pairy[pairc], &nout, &tofac);
+                probi = la->signi(&pairy[pairc], &nout, &tofac);
                 if(pairy[pairc] > 4.) {
                     memset(mess, '\0', sizeof(mess));
                     sprintf(mess, "%12.8f %8.2f %8.3f %d", pairx[pairc]*Norm, pairy[pairc], probi, i);
@@ -145,7 +145,7 @@ int TUNE_class::LombAnalysis(std::vector<double> &x, std::vector<double> &y, int
 }
 
 
-int TUNE_class::LombAnalysis(double *x, double *y, int Ndat, int nhis)
+int TUNE_class::lombAnalysis(double *x, double *y, int Ndat, int nhis)
 /*-----------------------------------------------------------------------------
  *  Launch Lomb analysis and plot results
  *  =======================================
@@ -242,7 +242,7 @@ int TUNE_class::LombAnalysis(double *x, double *y, int Ndat, int nhis)
             pairy[pairc] = lodata2[i].y;
             if((pairy[pairc] > pairy[pairc-1]) &&
                (pairy[pairc] > lodata2[i+1].y)) {
-                probi = la->Signi(&pairy[pairc], &nout, &tofac);
+                probi = la->signi(&pairy[pairc], &nout, &tofac);
                 if(pairy[pairc] > 4.) {
                     memset(mess, '\0', sizeof(mess));
                     sprintf(mess, "%12.8f %8.2f %8.3f %d", pairx[pairc], pairy[pairc],
diff --git a/src/Algorithms/ParallelCyclotronTracker.cpp b/src/Algorithms/ParallelCyclotronTracker.cpp
index e21c6ec18528bb451183234d243d53f506b9d142..f94686b5c45eb3673ee216356ade610a23753835 100644
--- a/src/Algorithms/ParallelCyclotronTracker.cpp
+++ b/src/Algorithms/ParallelCyclotronTracker.cpp
@@ -20,6 +20,7 @@
 #include "Algorithms/ParallelCyclotronTracker.h"
 #include "Algorithms/PolynomialTimeDependence.h"
 #include "Elements/OpalPolynomialTimeDependence.h"
+
 #include <cfloat>
 #include <iostream>
 #include <fstream>
@@ -227,7 +228,7 @@ void ParallelCyclotronTracker::bgf_main_collision_test() {
   int triId = 0;
   size_t Nimpact = 0;
   for(size_t i = 0; i < itsBunch->getLocalNum(); i++) {
-    int res = bgf_m->PartInside(itsBunch->R[i]*1.0e-3, itsBunch->P[i], dtime, itsBunch->PType[i], itsBunch->Q[i], intecoords, triId);
+    int res = bgf_m->partInside(itsBunch->R[i]*1.0e-3, itsBunch->P[i], dtime, itsBunch->PType[i], itsBunch->Q[i], intecoords, triId);
     if(res >= 0) {
       itsBunch->Bin[i] = -1;
       Nimpact++;
@@ -359,21 +360,21 @@ void ParallelCyclotronTracker::visitCyclotron(const Cyclotron &cycl) {
     Cyclotron *elptr = dynamic_cast<Cyclotron *>(cycl.clone());
     myElements.push_back(elptr);
 
-    // Is this a Spiral Inflector Simulation? If yes, we'll give the user some 
+    // Is this a Spiral Inflector Simulation? If yes, we'll give the user some
     // useful information
     spiral_flag = elptr->getSpiralFlag();
 
     if(spiral_flag) {
 
         *gmsg << endl << "* This is a Spiral Inflector Simulation! This means the following:" << endl;
-        *gmsg         << "* 1.) It is up to the user to provide appropriate geometry, electric and magnetic fields!" << endl;        
+        *gmsg         << "* 1.) It is up to the user to provide appropriate geometry, electric and magnetic fields!" << endl;
         *gmsg         << "*     (Use BANDRF type cyclotron and use RFMAPFN to load both magnetic" << endl;
         *gmsg         << "*     and electric fields, setting SUPERPOSE to an array of TRUE values.)" << endl;
-        *gmsg         << "* 2.) It is strongly recommended to use the SAAMG fieldsolver," << endl; 
+        *gmsg         << "* 2.) It is strongly recommended to use the SAAMG fieldsolver," << endl;
         *gmsg         << "*     FFT does not give the correct results (boundaty conditions are missing)." << endl;
         *gmsg         << "* 3.) The whole geometry will be meshed and used for the fieldsolve." << endl;
-        *gmsg         << "*     There will be no transformations of the bunch into a local frame und consequently," << endl; 
-        *gmsg         << "*     the problem will be treated non-relativistically!" << endl; 
+        *gmsg         << "*     There will be no transformations of the bunch into a local frame und consequently," << endl;
+        *gmsg         << "*     the problem will be treated non-relativistically!" << endl;
         *gmsg         << "*     (This is not an issue for spiral inflectors as they are typically < 100 keV/amu.)" << endl;
         *gmsg << endl << "* Note: For now, multi-bunch mode (MBM) needs to be de-activated for spiral inflector" << endl;
         *gmsg         << "* and space charge needs to be solved every time-step. numBunch_m and scSolveFreq are reset." << endl;
@@ -510,6 +511,7 @@ void ParallelCyclotronTracker::visitCyclotron(const Cyclotron &cycl) {
     double h = elptr->getCyclHarm();
     *gmsg << "* Number of trimcoils = " << elptr->getNumberOfTrimcoils() << endl;
     *gmsg << "* Harmonic number h = " << h << " " << endl;
+
     /**
     if (elptr->getSuperpose())
         *gmsg << "* Fields are superposed " << endl;
@@ -599,7 +601,7 @@ void ParallelCyclotronTracker::visitCollimator(const Collimator &coll) {
     double width = elptr->getWidth();
     *gmsg << "* Width= " << width << " [mm]" << endl;
 
-    elptr->initialise(itsBunch, 1.0);
+    elptr->initialise(itsBunch);
 
     double BcParameter[8];
     for(int i = 0; i < 8; i++)
@@ -736,7 +738,7 @@ void ParallelCyclotronTracker::visitProbe(const Probe &prob) {
 
 
     // initialise, do nothing
-    elptr->initialise(itsBunch, 1.0);
+    elptr->initialise(itsBunch);
 
     double BcParameter[8];
     for(int i = 0; i < 8; i++)
@@ -836,7 +838,7 @@ void ParallelCyclotronTracker::visitRFCavity(const RFCavity &as) {
     unityVec.push_back(0.);
     unityVec.push_back(0.);
     unityVec.push_back(0.);
-    
+
     if (elptr->getFrequencyModelName() != "") {
       freq_atd = AbstractTimeDependence::getTimeDependence(elptr->getFrequencyModelName());
       *gmsg << "* Variable frequency RF Model name " << elptr->getFrequencyModelName() << endl;
@@ -859,9 +861,7 @@ void ParallelCyclotronTracker::visitRFCavity(const RFCavity &as) {
         phase_atd = std::shared_ptr<AbstractTimeDependence>(new PolynomialTimeDependence(unityVec));
 
     // read cavity voltage profile data from file.
-    elptr->initialise(itsBunch, 1.0, freq_atd, ampl_atd, phase_atd);
-
-//    elptr->initialise(itsBunch, 1.0); 
+    elptr->initialise(itsBunch, freq_atd, ampl_atd, phase_atd);
 
     double BcParameter[8];
     for(int i = 0; i < 8; i++)
@@ -934,7 +934,7 @@ void ParallelCyclotronTracker::visitSeptum(const Septum &sept) {
 
 
     // initialise, do nothing
-    elptr->initialise(itsBunch, 1.0);
+    elptr->initialise(itsBunch);
 
     double BcParameter[8];
     for(int i = 0; i < 8; i++)
@@ -1032,7 +1032,7 @@ void ParallelCyclotronTracker::visitStripper(const Stripper &stripper) {
     double opmass = elptr->getOPMass();
     *gmsg << "* Mass of the outcoming particle = " << opmass << " [GeV/c^2]" << endl;
 
-    elptr->initialise(itsBunch, 1.0);
+    elptr->initialise(itsBunch);
 
     double BcParameter[8];
     for(int i = 0; i < 8; i++)
@@ -1656,7 +1656,6 @@ void ParallelCyclotronTracker::Tracker_LF() {
 
             // Write Phase Space and Statistics Data to h5 and dat files
             bunchDumpPhaseSpaceData();
-
             IpplTimings::stopTimer(DumpTimer_m);
         }
     }
@@ -2704,7 +2703,7 @@ void ParallelCyclotronTracker::Tracker_Generic() {
     int scSolveFreq;
 
     if (spiral_flag)
-	scSolveFreq = 1;	    
+	scSolveFreq = 1;
     else
         scSolveFreq = Options::scSolveFreq;
 
@@ -3019,8 +3018,8 @@ void ParallelCyclotronTracker::Tracker_Generic() {
 
                     } else {
                         // --- Single bunch mode --- //
-			
-			// If we are doing a spiral inflector simulation and are using the SAAMG solver 
+
+			// If we are doing a spiral inflector simulation and are using the SAAMG solver
                         // we don't rotate or translate the bunch and gamma is 1.0 (non-relativistic).
 			if (spiral_flag and itsBunch->getFieldSolverType() == "SAAMG") {
 
@@ -3031,11 +3030,11 @@ void ParallelCyclotronTracker::Tracker_Generic() {
 				itsBunch->setGlobalMeanR(Vector_t(0.0, 0.0, 0.0));
 				itsBunch->setGlobalToLocalQuaternion(Quaternion_t(1.0, 0.0, 0.0, 0.0));
 
-				itsBunch->computeSelfFields_cycl(1.0);	
+				itsBunch->computeSelfFields_cycl(1.0);
 
 				IpplTimings::startTimer(TransformTimer_m);
 
-				itsBunch->R *= Vector_t(1000.0); // m --> mm			
+				itsBunch->R *= Vector_t(1000.0); // m --> mm
 
 			} else {
 				double temp_meangamma = sqrt(1.0 + dot(PreviousMeanP, PreviousMeanP));
@@ -3956,7 +3955,7 @@ bool ParallelCyclotronTracker::getTunes(std::vector<double> &t, std::vector<doub
     int  stat = 0;
     // book tune class
     tune = new TUNE_class();
-    stat = tune->LombAnalysis(t, r, nhis_lomb, T / lastTurn);
+    stat = tune->lombAnalysis(t, r, nhis_lomb, T / lastTurn);
     if(stat != 0)
         *gmsg << "* TUNE: Lomb analysis failed" << endl;
     *gmsg << "* ************************************************************************************* *" << endl;
@@ -3974,7 +3973,7 @@ bool ParallelCyclotronTracker::getTunes(std::vector<double> &t, std::vector<doub
 
         // book tune class
         tune = new TUNE_class();
-        stat = tune->LombAnalysis(t, z, nhis_lomb, T / lastTurn);
+        stat = tune->lombAnalysis(t, z, nhis_lomb, T / lastTurn);
         if(stat != 0)
             *gmsg << "* TUNE: Lomb analysis failed" << endl;
         *gmsg << "* ************************************************************************************* *" << endl;
@@ -5363,7 +5362,7 @@ void ParallelCyclotronTracker::bunchDumpStatData(){
     IpplTimings::startTimer(DumpTimer_m);
 
     // --------------------------------- Get some Values ---------------------------------------- //
-    double const E = itsBunch->get_meanEnergy();
+    double const E = itsBunch->get_meanKineticEnergy();
     double const temp_t = itsBunch->getT() * 1e9; // s -> ns
     Vector_t const meanR = calcMeanR();
     Vector_t const meanP = calcMeanP();
@@ -5375,7 +5374,7 @@ void ParallelCyclotronTracker::bunchDumpStatData(){
     extE_m = Vector_t(0.0, 0.0, 0.0);
     extB_m = Vector_t(0.0, 0.0, 0.0);
 
-    (((*DumpSindex)->second).second)->apply(meanR, Vector_t(0.0), temp_t, extE_m, extB_m);
+    (((*DumpSindex)->second).second)->apply(meanR, meanP, temp_t, extE_m, extB_m);
 
     // If we are saving in local frame, bunch and fields at the bunch center have to be rotated
     // TODO: Make decision if we maybe want to always save statistics data in local frame? -DW
@@ -5397,16 +5396,15 @@ void ParallelCyclotronTracker::bunchDumpStatData(){
         globalToLocal(itsBunch->P, phi, psi);
     }
 
-
-    itsBunch->R *= Vector_t(0.001); // mm --> m
+    itsBunch->R *= Vector_t(0.001); // mm -> m
 
     FDext_m[0] = extB_m / 10.0; // kgauss --> T
     FDext_m[1] = extE_m;
 
     // Save the stat file
-    itsDataSink->writeStatData(*itsBunch, FDext_m ,0.0, 0.0, 0.0, E);
+    itsDataSink->writeStatData(*itsBunch, FDext_m, E);
 
-    itsBunch->R *= Vector_t(1000.0); // mm --> m
+    itsBunch->R *= Vector_t(1000.0); // m -> mm
 
     // If we are in local mode, transform back after saving
     if(Options::psDumpLocalFrame) {
@@ -5434,7 +5432,7 @@ void ParallelCyclotronTracker::bunchDumpPhaseSpaceData() {
     Vector_t const meanP = calcMeanP();
 
     double const betagamma_temp = sqrt(dot(meanP, meanP));
-    double const E = itsBunch->get_meanEnergy();
+    double const E = itsBunch->get_meanKineticEnergy();
 
     // Bunch (global) angle w.r.t. x-axis (cylinder coordinates)
     double const theta = atan2(meanR(1), meanR(0));
@@ -5464,7 +5462,7 @@ void ParallelCyclotronTracker::bunchDumpPhaseSpaceData() {
     extE_m = Vector_t(0.0, 0.0, 0.0);
     extB_m = Vector_t(0.0, 0.0, 0.0);
 
-    (((*DumpSindex)->second).second)->apply(meanR, Vector_t(0.0), temp_t, extE_m, extB_m);
+    (((*DumpSindex)->second).second)->apply(meanR, meanP, temp_t, extE_m, extB_m);
     FDext_m[0] = extB_m * 0.1; // kgauss --> T
     FDext_m[1] = extE_m;
 
@@ -5583,4 +5581,4 @@ void ParallelCyclotronTracker::evaluateSpaceChargeField() {
         localToGlobal(itsBunch->Bf, phi);
         localToGlobal(itsBunch->R, phi, meanR);
     }
-}
+}
\ No newline at end of file
diff --git a/src/Algorithms/ParallelSliceTracker.cpp b/src/Algorithms/ParallelSliceTracker.cpp
index fb3ca8f5e419220efbc4b4cde36059440ac8a924..7676920162e90ba3a90211a687cec9fcbca65426 100644
--- a/src/Algorithms/ParallelSliceTracker.cpp
+++ b/src/Algorithms/ParallelSliceTracker.cpp
@@ -212,8 +212,6 @@ void ParallelSliceTracker::prepareSections() {
     itsOpalBeamline_m->print(msg);
 
     for (int i = 0; i < itsBunch_m->getLocalNum(); i++) {
-        auto &l = itsBunch_m->LastSection[i];
-        l = -1;
         Vector_t pos = Vector_t(itsBunch_m->getX(i),
                 itsBunch_m->getY(i), itsBunch_m->getZ(i));
         itsOpalBeamline_m->getSectionIndexAt(pos, l);
@@ -239,12 +237,6 @@ void ParallelSliceTracker::computeExternalFields() {
         Vector_t pos = Vector_t(itsBunch_m->getX(i),
                 itsBunch_m->getY(i), itsBunch_m->getZ(i));
 
-        auto &ls = itsBunch_m->LastSection[i];
-        itsOpalBeamline_m->getSectionIndexAt(pos, ls);
-
-        if (ls != itsBunch_m->LastSection[i])
-            itsBunch_m->LastSection[i] = ls;
-
         unsigned long rtv = itsOpalBeamline_m->getFieldAt(i, pos, ls,
                 currentSimulationTime_m , externalE, externalB);
 
@@ -334,4 +326,4 @@ void ParallelSliceTracker::dumpPhaseSpaceOnScan() {
 
 bool ParallelSliceTracker::hasEndOfLineReached() {
     return (itsBunch_m->get_sPos() > zstop_m || !(itsBunch_m->isValid_m));
-}
\ No newline at end of file
+}
diff --git a/src/Algorithms/ParallelTTracker.cpp b/src/Algorithms/ParallelTTracker.cpp
index 33e0d6b7a86d63a9f37b38b01177d17b0fdcd876..ea34d983269b301dc66f1858303c941a83f384b5 100644
--- a/src/Algorithms/ParallelTTracker.cpp
+++ b/src/Algorithms/ParallelTTracker.cpp
@@ -29,38 +29,18 @@
 #include <cmath>
 
 #include "Algorithms/PartPusher.h"
-#include "AbsBeamline/AlignWrapper.h"
-#include "AbsBeamline/BeamBeam.h"
-#include "AbsBeamline/Collimator.h"
-#include "AbsBeamline/Corrector.h"
-#include "AbsBeamline/Diagnostic.h"
-#include "AbsBeamline/Drift.h"
-#include "AbsBeamline/ElementBase.h"
-#include "AbsBeamline/Lambertson.h"
-#include "AbsBeamline/Marker.h"
-#include "AbsBeamline/Monitor.h"
-#include "AbsBeamline/Multipole.h"
-#include "AbsBeamline/Probe.h"
-#include "AbsBeamline/RBend.h"
-#include "AbsBeamline/RFCavity.h"
-#include "AbsBeamline/TravelingWave.h"
-#include "AbsBeamline/RFQuadrupole.h"
-#include "AbsBeamline/SBend.h"
-#include "AbsBeamline/Separator.h"
-#include "AbsBeamline/Septum.h"
-#include "AbsBeamline/Solenoid.h"
-#include "AbsBeamline/ParallelPlate.h"
-#include "AbsBeamline/CyclotronValley.h"
+#include "Algorithms/OrbitThreader.h"
+#include "Algorithms/CavityAutophaser.h"
 #include "Beamlines/Beamline.h"
 #include "Lines/Sequence.h"
-//--------- Added by Xiaoying Pang 04/22/2014 ---------------
+
 #include "Solvers/CSRWakeFunction.hh"
 
 #include "AbstractObjects/OpalData.h"
 
 #include "BasicActions/Option.h"
 #include "Utilities/Options.h"
-#include "Utilities/Options.h"
+#include "Utilities/Util.h"
 
 #include "Distribution/Distribution.h"
 #include "ValueDefinitions/RealVariable.h"
@@ -68,7 +48,8 @@
 #include "Utilities/OpalException.h"
 #include "Solvers/SurfacePhysicsHandler.hh"
 #include "Structure/BoundaryGeometry.h"
-#define EPS 10e-10
+#include "Structure/LossDataSink.h"
+
 class PartData;
 
 using namespace std;
@@ -76,59 +57,38 @@ using namespace std;
 ParallelTTracker::ParallelTTracker(const Beamline &beamline,
                                    const PartData &reference,
                                    bool revBeam,
-                                   bool revTrack,
-				   size_t N):
-Tracker(beamline, reference, revBeam, revTrack),
-itsBunch(NULL),
-itsDataSink_m(NULL),
-bgf_m(NULL),
-itsOpalBeamline_m(),
-lineDensity_m(),
-RefPartR_zxy_m(0.0),
-RefPartP_zxy_m(0.0),
-RefPartR_suv_m(0.0),
-RefPartP_suv_m(0.0),
-globalEOL_m(false),
-wakeStatus_m(false),
-//--------- Added by Xiaoying Pang 04/22/2014 ---------------
-wakeFunction_m(NULL),
-surfaceStatus_m(false),
-secondaryFlg_m(false),
-mpacflg_m(true),
-nEmissionMode_m(false),
-zStop_m(),
-scaleFactor_m(1.0),
-vscaleFactor_m(scaleFactor_m),
-recpGamma_m(1.0),
-rescale_coeff_m(1.0),
-dtCurrentTrack_m(0.0),
-dtAllTracks_m(),
-surfaceEmissionStop_m(-1),
-specifiedNPart_m(N),
-minStepforReBin_m(-1),
-minBinEmitted_m(std::numeric_limits<size_t>::max()),
-repartFreq_m(-1),
-lastVisited_m(-1),
-numRefs_m(-1),
-gunSubTimeSteps_m(-1),
-emissionSteps_m(std::numeric_limits<unsigned int>::max()),
-localTrackSteps_m(),
-maxNparts_m(0),
-numberOfFieldEmittedParticles_m(std::numeric_limits<size_t>::max()),
-bends_m(0),
-numParticlesInSimulation_m(0),
-totalParticlesInSimulation_m(0),
-space_orientation_m(1.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 1.0),
-timeIntegrationTimer1_m(IpplTimings::getTimer("TIntegration1")),
-timeIntegrationTimer2_m(IpplTimings::getTimer("TIntegration2")),
-timeFieldEvaluation_m(IpplTimings::getTimer("Fieldeval")),
-BinRepartTimer_m(IpplTimings::getTimer("Binaryrepart")),
-WakeFieldTimer_m(IpplTimings::getTimer("WakeField")),
-Nimpact_m(0),
-SeyNum_m(0.0),
-timeIntegrationTimer1Push_m(IpplTimings::getTimer("TIntegration1Push")),
-timeIntegrationTimer2Push_m(IpplTimings::getTimer("TIntegration2Push"))
+                                   bool revTrack):
+    Tracker(beamline, reference, revBeam, revTrack),
+    itsBunch_m(NULL),
+    itsDataSink_m(NULL),
+    itsOpalBeamline_m(beamline.getOrigin3D(), beamline.getCoordTransformationTo()),
+    RefPartR_m(0.0),
+    RefPartP_m(0.0),
+    globalEOL_m(false),
+    wakeStatus_m(false),
+    wakeFunction_m(NULL),
+    pathLength_m(0.0),
+    zstart_m(0.0),
+    zStop_m(),
+    dtCurrentTrack_m(0.0),
+    dtAllTracks_m(),
+    localTrackSteps_m(),
+    minStepforReBin_m(-1),
+    minBinEmitted_m(std::numeric_limits<size_t>::max()),
+    repartFreq_m(-1),
+    emissionSteps_m(std::numeric_limits<unsigned int>::max()),
+    numParticlesInSimulation_m(0),
+    timeIntegrationTimer1_m(IpplTimings::getTimer("TIntegration1")),
+    timeIntegrationTimer2_m(IpplTimings::getTimer("TIntegration2")),
+    fieldEvaluationTimer_m(IpplTimings::getTimer("External field eval")),
+    BinRepartTimer_m(IpplTimings::getTimer("Binaryrepart")),
+    WakeFieldTimer_m(IpplTimings::getTimer("WakeField"))
+    // , logger_m("designPath_" + std::to_string(Ippl::myNode()) + ".dat")
 {
+
+    CoordinateSystemTrafo labToRef(beamline.getOrigin3D(),
+                                   beamline.getCoordTransformationTo().conjugate());
+    referenceToLabCSTrafo_m = labToRef.inverted();
 }
 
 ParallelTTracker::ParallelTTracker(const Beamline &beamline,
@@ -138,58 +98,38 @@ ParallelTTracker::ParallelTTracker(const Beamline &beamline,
                                    bool revBeam,
                                    bool revTrack,
                                    const std::vector<unsigned long long> &maxSteps,
+                                   double zstart,
                                    const std::vector<double> &zstop,
-                                   int timeIntegrator,
-                                   const std::vector<double> &dt,
-				   size_t N):
-Tracker(beamline, reference, revBeam, revTrack),
-itsBunch(&bunch),
-itsDataSink_m(&ds),
-bgf_m(NULL),
-itsOpalBeamline_m(),
-lineDensity_m(),
-RefPartR_zxy_m(0.0),
-RefPartP_zxy_m(0.0),
-RefPartR_suv_m(0.0),
-RefPartP_suv_m(0.0),
-globalEOL_m(false),
-wakeStatus_m(false),
-surfaceStatus_m(false),
-secondaryFlg_m(false),
-mpacflg_m(true),
-nEmissionMode_m(false),
-scaleFactor_m(itsBunch->getdT() * Physics::c),
-vscaleFactor_m(scaleFactor_m),
-recpGamma_m(1.0),
-rescale_coeff_m(1.0),
-dtCurrentTrack_m(0.0),
-surfaceEmissionStop_m(-1),
-specifiedNPart_m(N),
-minStepforReBin_m(-1),
-minBinEmitted_m(std::numeric_limits<size_t>::max()),
-repartFreq_m(-1),
-lastVisited_m(-1),
-numRefs_m(-1),
-gunSubTimeSteps_m(-1),
-emissionSteps_m(numeric_limits<unsigned int>::max()),
-maxNparts_m(0),
-numberOfFieldEmittedParticles_m(numeric_limits<size_t>::max()),
-bends_m(0),
-numParticlesInSimulation_m(0),
-totalParticlesInSimulation_m(0),
-space_orientation_m(1.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 1.0),
-timeIntegrationTimer1_m(IpplTimings::getTimer("TIntegration1")),
-timeIntegrationTimer2_m(IpplTimings::getTimer("TIntegration2")),
-timeFieldEvaluation_m(IpplTimings::getTimer("Fieldeval")),
-BinRepartTimer_m(IpplTimings::getTimer("Binaryrepart")),
-WakeFieldTimer_m(IpplTimings::getTimer("WakeField")),
-timeIntegrator_m(timeIntegrator),
-Nimpact_m(0),
-SeyNum_m(0.0),
-timeIntegrationTimer1Push_m(IpplTimings::getTimer("TIntegration1Push")),
-timeIntegrationTimer2Push_m(IpplTimings::getTimer("TIntegration2Push"))
+                                   const std::vector<double> &dt):
+    Tracker(beamline, reference, revBeam, revTrack),
+    itsBunch_m(&bunch),
+    itsDataSink_m(&ds),
+    itsOpalBeamline_m(beamline.getOrigin3D(), beamline.getCoordTransformationTo()),
+    RefPartR_m(0.0),
+    RefPartP_m(0.0),
+    globalEOL_m(false),
+    wakeStatus_m(false),
+    wakeFunction_m(NULL),
+    pathLength_m(0.0),
+    zstart_m(zstart),
+    dtCurrentTrack_m(0.0),
+    minStepforReBin_m(-1),
+    minBinEmitted_m(std::numeric_limits<size_t>::max()),
+    repartFreq_m(-1),
+    emissionSteps_m(numeric_limits<unsigned int>::max()),
+    numParticlesInSimulation_m(0),
+    timeIntegrationTimer1_m(IpplTimings::getTimer("TIntegration1")),
+    timeIntegrationTimer2_m(IpplTimings::getTimer("TIntegration2")),
+    fieldEvaluationTimer_m(IpplTimings::getTimer("External field eval")),
+    BinRepartTimer_m(IpplTimings::getTimer("Binaryrepart")),
+    WakeFieldTimer_m(IpplTimings::getTimer("WakeField"))
+    // , logger_m("designPath_" + std::to_string(Ippl::myNode()) + ".dat")
 {
 
+    CoordinateSystemTrafo labToRef(beamline.getOrigin3D(),
+                                   beamline.getCoordTransformationTo());
+    referenceToLabCSTrafo_m = labToRef.inverted();
+
     for (std::vector<unsigned long long>::const_iterator it = maxSteps.begin(); it != maxSteps.end(); ++ it) {
         localTrackSteps_m.push(*it);
     }
@@ -199,1865 +139,577 @@ timeIntegrationTimer2Push_m(IpplTimings::getTimer("TIntegration2Push"))
     for (std::vector<double>::const_iterator it = zstop.begin(); it != zstop.end(); ++ it) {
         zStop_m.push(*it);
     }
-
-    //    itsBeamline = dynamic_cast<Beamline*>(beamline.clone());
-
-#ifdef OPAL_DKS
-    if (IpplInfo::DKSEnabled) {
-        dksbase.setAPI("Cuda", 4);
-        dksbase.setDevice("-gpu", 4);
-        dksbase.initDevice();
-    }
-#endif
-
 }
 
-
 ParallelTTracker::~ParallelTTracker() {
 
 }
 
-void ParallelTTracker::applyEntranceFringe(double angle, double curve,
-                                           const BMultipoleField &field, double scale) {
-}
-
-
-void ParallelTTracker::applyExitFringe(double angle, double curve,
-                                       const BMultipoleField &field, double scale) {
+void ParallelTTracker::visitBeamline(const Beamline &bl) {
+    const FlaggedBeamline* fbl = static_cast<const FlaggedBeamline*>(&bl);
+    if (fbl->getRelativeFlag()) {
+        OpalBeamline stash(fbl->getOrigin3D(), fbl->getCoordTransformationTo());
+        stash.swap(itsOpalBeamline_m);
+        fbl->iterate(*this, false);
+        itsOpalBeamline_m.prepareSections();
+        itsOpalBeamline_m.compute3DLattice();
+        stash.merge(itsOpalBeamline_m);
+        stash.swap(itsOpalBeamline_m);
+    } else {
+        fbl->iterate(*this, false);
+    }
 }
 
 void ParallelTTracker::updateRFElement(std::string elName, double maxPhase) {
     /**
-     The maximum phase is added to the nominal phase of
-     the element. This is done on all nodes except node 0 where
-     the Autophase took place.
-     */
-    double phase = 0.0;
-    double frequency = 0.0;
-    double globalTimeShift = OpalData::getInstance()->getGlobalPhaseShift();
-    for (FieldList::iterator fit = cavities_m.begin(); fit != cavities_m.end(); ++fit) {
+       The maximum phase is added to the nominal phase of
+       the element. This is done on all nodes except node 0 where
+       the Autophase took place.
+    */
+    FieldList cavities = itsOpalBeamline_m.getElementByType(ElementBase::RFCAVITY);
+    FieldList travelingwaves = itsOpalBeamline_m.getElementByType(ElementBase::TRAVELINGWAVE);
+
+    for (FieldList::iterator fit = cavities.begin(); fit != cavities.end(); ++ fit) {
         if ((*fit).getElement()->getName() == elName) {
-            if ((*fit).getElement()->getType() == ElementBase::TRAVELINGWAVE) {
-                phase  =  static_cast<TravelingWave *>((*fit).getElement().get())->getPhasem();
-                frequency = static_cast<TravelingWave *>((*fit).getElement().get())->getFrequencym();
-                maxPhase -= frequency * globalTimeShift;
 
-                static_cast<TravelingWave *>((*fit).getElement().get())->updatePhasem(phase + maxPhase);
-            } else {
-                phase  = static_cast<RFCavity *>((*fit).getElement().get())->getPhasem();
-                frequency = static_cast<RFCavity *>((*fit).getElement().get())->getFrequencym();
-                maxPhase -= frequency * globalTimeShift;
+            RFCavity *element = static_cast<RFCavity *>((*fit).getElement().get());
+            double phase  =  element->getPhasem();
 
-                static_cast<RFCavity *>((*fit).getElement().get())->updatePhasem(phase + maxPhase);
-            }
+            element->setPhasem(phase + maxPhase);
+            element->setAutophaseVeto();
 
-            break;
+            INFOMSG("Restored cavity phase from the h5 file. Name: " << element->getName() << ", phase: " << maxPhase << " rad" << endl);
+            return;
         }
     }
-}
-
-void ParallelTTracker::handleAutoPhasing() {
-    typedef std::vector<MaxPhasesT>::iterator iterator_t;
+    for (FieldList::iterator fit = travelingwaves.begin(); fit != travelingwaves.end(); ++ fit) {
+        if ((*fit).getElement()->getName() == elName) {
 
-    if(Options::autoPhase == 0) return;
+            TravelingWave *element = static_cast<TravelingWave *>((*fit).getElement().get());
+            double phase  =  element->getPhasem();
 
-    if(!OpalData::getInstance()->inRestartRun()) {
-        itsDataSink_m->storeCavityInformation();
-    }
+            element->setPhasem(phase + maxPhase);
+            element->setAutophaseVeto();
 
-    iterator_t it = OpalData::getInstance()->getFirstMaxPhases();
-    iterator_t end = OpalData::getInstance()->getLastMaxPhases();
-    for(; it < end; ++ it) {
-        updateRFElement((*it).first, (*it).second);
+            INFOMSG("Restored cavity phase from the h5 file. Name: " << element->getName() << ", phase: " << maxPhase << " rad" << endl);
+            return;
+        }
     }
 }
 
-void ParallelTTracker::execute() {
-    if(timeIntegrator_m == 3) {
-        executeAMTSTracker();
-    } else {
-        executeDefaultTracker();
-    }
+void ParallelTTracker::saveCavityPhases() {
+    itsDataSink_m->storeCavityInformation();
 }
 
-void ParallelTTracker::executeDefaultTracker() {
-    Inform msg("ParallelTTracker ", *gmsg);
-    const Vector_t vscaleFactor_m = Vector_t(scaleFactor_m);
-    BorisPusher pusher(itsReference);
-    secondaryFlg_m = false;
-    dtCurrentTrack_m = itsBunch->getdT();
-
-    // upper limit of particle number when we do field emission and secondary emission
-    // simulation. Could be reset to another value in input file with MAXPARTSNUM.
-    maxNparts_m = 100000000;
-    nEmissionMode_m = true;
-
-    prepareSections();
-
-    if (OpalData::getInstance()->hasBunchAllocated()) {
-        // delete last entry of sdds file and load balance file
-        // if we are in a follow-up track
-        itsDataSink_m->rewindLinesSDDS(1);
-        itsDataSink_m->rewindLinesLBal(1);
-    }
-
-    handleAutoPhasing();
-
-    numParticlesInSimulation_m = itsBunch->getTotalNum();
-    totalParticlesInSimulation_m = itsBunch->getTotalNum();
-
-    OPALTimer::Timer myt1;
-
-    setTime();
-
-    double t = itsBunch->getT();
-
-    unsigned long long step = itsBunch->getLocalTrackStep();
-
-    *gmsg << "Track start at: " << myt1.time() << ", t= " << t << "; zstop at: " << zStop_m.front() << " [m]" << endl;
-
-    gunSubTimeSteps_m = 10;
-    prepareEmission();
-
-    doSchottyRenormalization();
-
-    *gmsg << level1
-          << "Executing ParallelTTracker, initial DT " << itsBunch->getdT() << " [s];\n"
-          << "max integration steps " << localTrackSteps_m.front() << ", next step= " << step << "\n";
-    *gmsg << "Using default (Boris-Buneman) integrator" << endl;
-
-    itsOpalBeamline_m.print(*gmsg);
-
-    setupSUV(!(OpalData::getInstance()->inRestartRun() || (OpalData::getInstance()->hasBunchAllocated() && !Options::scan)));
-
-    // increase margin from 3.*c*dt to 10.*c*dt to prevent that fieldmaps are accessed
-    // before they are allocated when increasing the timestep in the gun.
-    switchElements(10.0);
-
-    initializeBoundaryGeometry();
-
-    setOptionalVariables();
-
-    // there is no point to do repartitioning with one node
-    if(Ippl::getNodes() == 1)
-        repartFreq_m = 1000000;
-
-    wakeStatus_m = false;
-    surfaceStatus_m = false;
-
-#ifdef OPAL_DKS
-    if (IpplInfo::DKSEnabled) {
-        //get number of elements in the bunch
-        numDeviceElements = itsBunch->getLocalNum();
-
-        //allocate memory on device
-        r_ptr = dksbase.allocateMemory<Vector_t>(numDeviceElements, ierr);
-        p_ptr = dksbase.allocateMemory<Vector_t>(numDeviceElements, ierr);
-        x_ptr = dksbase.allocateMemory<Vector_t>(numDeviceElements, ierr);
-
-        lastSec_ptr = dksbase.allocateMemory<long>(numDeviceElements, ierr);
-        dt_ptr = dksbase.allocateMemory<double>(numDeviceElements, ierr);
-
-        orient_ptr = dksbase.allocateMemory<Vector_t>(itsOpalBeamline_m.sections_m.size(), ierr);
-
-        //get all the section orientations
-        int nsec = itsOpalBeamline_m.sections_m.size();
-        Vector_t *orientation = new Vector_t[nsec];
-        for (long i = 0; i < nsec; i++) {
-            orientation[i] = itsOpalBeamline_m.getOrientation(i);
-        }
-        
-        //write orientations to device
-        dksbase.writeData<Vector_t>(orient_ptr, orientation, nsec);
-
-        //free local orientation memory
-        delete[] orientation;
-
-        //allocate memory on device for particle
-        allocateDeviceMemory();
-
-        //page lock itsBunch->X, itsBunch->R, itsBunch-P
-        registerHostMemory();
-        
-        //write R, P and X data to device
-        dksbase.writeDataAsync<Vector_t>(r_ptr, &itsBunch->R[0], itsBunch->getLocalNum());
-        dksbase.writeDataAsync<Vector_t>(p_ptr, &itsBunch->P[0], itsBunch->getLocalNum());
-        dksbase.writeDataAsync<Vector_t>(x_ptr, &itsBunch->X[0], itsBunch->getLocalNum());
-        
-        //create two new streams
-        dksbase.createStream(stream1);
-        dksbase.createStream(stream2);
-    }
-#endif
-
-    while (localTrackSteps_m.size() > 0) {
-        localTrackSteps_m.front() += step;
-        dtCurrentTrack_m = dtAllTracks_m.front();
-        changeDT();
-
-        for(; step < localTrackSteps_m.front(); ++step) {
-            bends_m = 0;
-            numberOfFieldEmittedParticles_m = 0;
-            
-            itsOpalBeamline_m.resetStatus();
-
-            // we dump later, after one step.
-            // dumpStats(step, true, true);
-
-
-            timeIntegration1(pusher);
-            timeIntegration1_bgf(pusher);
-
-            itsBunch->calcBeamParameters();
-
-            // reset E and B to Vector_t(0.0) for every step
-            itsBunch->Ef = Vector_t(0.0);
-            itsBunch->Bf = Vector_t(0.0);
-
-            if(step % repartFreq_m == 0 && step != 0) {
-                doBinaryRepartition();
-            }
-
-            computeSpaceChargeFields();
-
-            switchElements(10.0);
-
-            selectDT();
-            emitParticles(step);
-            selectDT();
-
-            computeExternalFields();
-
-            timeIntegration2(pusher);
-            timeIntegration2_bgf(pusher);
-
-            bgf_main_collision_test();
-
-            //t after a full global timestep with dT "synchronization point" for simulation time
-            t += itsBunch->getdT();
-            itsBunch->setT(t);
-
-            bool const psDump = itsBunch->getGlobalTrackStep() % Options::psDumpFreq == 0;
-            bool const statDump = itsBunch->getGlobalTrackStep() % Options::statDumpFreq == 0;
-            dumpStats(step, psDump, statDump);
-
-            if(hasEndOfLineReached()) break;
-
-            itsBunch->incTrackSteps();
+void ParallelTTracker::restoreCavityPhases() {
+    typedef std::vector<MaxPhasesT>::iterator iterator_t;
 
+    if (OpalData::getInstance()->hasPriorTrack() ||
+        OpalData::getInstance()->inRestartRun()) {
+        iterator_t it = OpalData::getInstance()->getFirstMaxPhases();
+        iterator_t end = OpalData::getInstance()->getLastMaxPhases();
+        for (; it < end; ++ it) {
+            updateRFElement((*it).first, (*it).second);
         }
-
-        dtAllTracks_m.pop();
-        localTrackSteps_m.pop();
-        zStop_m.pop();
     }
-
-    if(numParticlesInSimulation_m > minBinEmitted_m) {
-        itsBunch->boundp();
-        numParticlesInSimulation_m = itsBunch->getTotalNum();
-    }
-
-    bool const psDump = (itsBunch->getGlobalTrackStep() - 1) % Options::psDumpFreq != 0;
-    bool const statDump = (itsBunch->getGlobalTrackStep() - 1) % Options::statDumpFreq != 0;
-    writePhaseSpace((step + 1), itsBunch->get_sPos(), psDump, statDump);
-    msg << level2 << "Dump phase space of last step" << endl;
-    OPALTimer::Timer myt3;
-    itsOpalBeamline_m.switchElementsOff();
-    *gmsg << "done executing ParallelTTracker at " << myt3.time() << endl;
-
-#ifdef OPAL_DKS
-    if (IpplInfo::DKSEnabled) {
-        //free device memory
-        freeDeviceMemory();
-        dksbase.freeMemory<Vector_t>(orient_ptr, itsOpalBeamline_m.sections_m.size());
-        //unregister page lock itsBunch->X, itsBunch->R, itsBunch-P
-        unregisterHostMemory();
-    }
-#endif
 }
 
-void ParallelTTracker::executeAMTSTracker() {
+void ParallelTTracker::execute() {
     Inform msg("ParallelTTracker ", *gmsg);
-    const Vector_t vscaleFactor_m = Vector_t(scaleFactor_m);
-    dtCurrentTrack_m = itsBunch->getdT();
 
-    // upper limit of particle number when we do field emission and secondary emission
-    // simulation. Could be reset to another value in input file with MAXPARTSNUM.
-    maxNparts_m = 100000000;
+    OpalData::getInstance()->setInPrepState(true);
 
-    prepareSections();
-
-    handleAutoPhasing();
-
-    numParticlesInSimulation_m = itsBunch->getTotalNum();
-    setTime();
-    unsigned long long step = itsBunch->getLocalTrackStep();
-    msg << "Track start at: " << OPALTimer::Timer().time() << ", t = " << itsBunch->getT() << "; zstop at: " << zStop_m.front() << " [m]" << endl;
-    msg << "Executing ParallelTTracker, next step = " << step << endl;
-    msg << "Using AMTS (adaptive multiple-time-stepping) integrator" << endl;
-    itsOpalBeamline_m.print(msg);
-    setupSUV();
+    BorisPusher pusher(itsReference);
+    const double globalTimeShift = itsBunch_m->weHaveEnergyBins()? OpalData::getInstance()->getGlobalPhaseShift(): 0.0;
 
-    itsOpalBeamline_m.switchAllElements();
+    dtCurrentTrack_m = itsBunch_m->getdT();
 
-    setOptionalVariables();
+    evenlyDistributeParticles();
 
-    // there is no point to do repartitioning with one node
-    if(Ippl::getNodes() == 1)
-        repartFreq_m = 1000000;
-
-    wakeStatus_m = false;
-    surfaceStatus_m = false;
-
-    // Count inner steps
-    int totalInnerSteps = 0;
-
-    itsBunch->boundp();
-    itsBunch->calcBeamParameters();
-    itsBunch->Ef = Vector_t(0.0);
-    itsBunch->Bf = Vector_t(0.0);
-    computeSpaceChargeFields();
-    if(itsBunch->WeHaveEnergyBins()) {
-        itsBunch->Rebin();
-        itsBunch->resetInterpolationCache(true);
+    if (OpalData::getInstance()->hasPriorTrack() || OpalData::getInstance()->inRestartRun()) {
+        Options::openMode = Options::APPEND;
     }
 
-    // AMTS step size initialization
-    double const dt_inner_target = itsBunch->getdT();
-    msg << "AMTS initialization: dt_inner_target = " << dt_inner_target << endl;
-    double dt_outer, deltaTau;
-    if(itsBunch->deltaTau_m != -1.0) {
-        // DTAU is set in the inputfile, calc initial outer time step from that
-        deltaTau = itsBunch->deltaTau_m;
-        dt_outer = calcG() * deltaTau;
-    } else {
-        // Otherwise use DTSCINIT
-        dt_outer = itsBunch->dtScInit_m;
-        deltaTau = dt_outer / calcG();
-    }
-    msg << "AMTS initialization: dt_outer = " << dt_outer << " deltaTau = " << deltaTau << endl;
-
-    // AMTS calculation of stopping times
-    double const tEnd = itsBunch->getT() + double(localTrackSteps_m.front() - step) * dt_inner_target;
-    double const psDumpInterval = double(Options::psDumpFreq) * dt_inner_target;
-    double const statDumpInterval = double(Options::statDumpFreq) * dt_inner_target;
-    double const repartInterval = double(repartFreq_m) * dt_inner_target;
-    double const tTrackStart = itsBunch->getT() - double(step) * dt_inner_target; // we could be in a restarted simulation!
-    double tNextPsDump = tTrackStart + psDumpInterval;
-    while(tNextPsDump < itsBunch->getT()) tNextPsDump += psDumpInterval;
-    double tNextStatDump = tTrackStart + statDumpInterval;
-    while(tNextStatDump < itsBunch->getT()) tNextStatDump += statDumpInterval;
-    double tDoNotRepartBefore = itsBunch->getT() + repartInterval;
-
-    IpplTimings::startTimer(IpplTimings::getTimer("AMTS"));
-
-    bool finished = false;
-    for(; !finished; ++step) {
-        itsOpalBeamline_m.resetStatus();
-
-        // AMTS choose new timestep
-        IpplTimings::startTimer(IpplTimings::getTimer("AMTS-TimestepSelection"));
-        dt_outer = calcG() * deltaTau;
-        double tAfterStep = itsBunch->getT() + dt_outer;
-        double const tNextStop = std::min(std::min(tEnd, tNextPsDump), tNextStatDump);
-        bool psDump = false, statDump = false;
-        if(tAfterStep > tNextStop) {
-            dt_outer = tNextStop - itsBunch->getT();
-            tAfterStep = tNextStop;
-        }
-        double const eps = 1e-14; // To test approx. equality of times
-        if(std::fabs(tAfterStep - tEnd) < eps) {
-            finished = true;
-        }
-        if(std::fabs(tAfterStep - tNextPsDump) < eps) {
-            psDump = true;
-            tNextPsDump += psDumpInterval;
-        }
-        if(std::fabs(tAfterStep - tNextStatDump) < eps) {
-            statDump = true;
-            tNextStatDump += statDumpInterval;
-        }
-        msg << "AMTS: dt_outer = " << dt_outer;
-        double numSubsteps = std::max(round(dt_outer / dt_inner_target), 1.0);
-        msg << " numSubsteps = " << numSubsteps;
-        double dt_inner = dt_outer / numSubsteps;
-        msg << " dt_inner = " << dt_inner << endl;
-        IpplTimings::stopTimer(IpplTimings::getTimer("AMTS-TimestepSelection"));
-
-        IpplTimings::startTimer(IpplTimings::getTimer("AMTS-Kick"));
-        if(itsBunch->hasFieldSolver()) {
-            kick(0.5 * dt_outer);
-        }
-        IpplTimings::stopTimer(IpplTimings::getTimer("AMTS-Kick"));
+    prepareSections();
 
-        for(int n = 0; n < numSubsteps; ++n) {
-            bool const isFirstSubstep = (n == 0);
-            bool const isLastSubstep = (n == numSubsteps - 1);
-            borisExternalFields(dt_inner, isFirstSubstep, isLastSubstep);
-            ++totalInnerSteps;
-        }
+    itsOpalBeamline_m.compute3DLattice();
+    itsOpalBeamline_m.save3DLattice();
+    itsOpalBeamline_m.save3DInput();
 
-        IpplTimings::startTimer(IpplTimings::getTimer("AMTS-SpaceCharge"));
-        if(itsBunch->hasFieldSolver()) {
-            itsBunch->boundp();
-            itsBunch->Ef = Vector_t(0.0);
-            itsBunch->Bf = Vector_t(0.0);
-            if(itsBunch->getT() >= tDoNotRepartBefore) {
-            	doBinaryRepartition();
-            	tDoNotRepartBefore = itsBunch->getT() + repartInterval;
-            }
-            computeSpaceChargeFields();
-            if(itsBunch->WeHaveEnergyBins()) {
-                itsBunch->rebin();
-                itsBunch->resetInterpolationCache(true);
-            }
-        }
-        IpplTimings::stopTimer(IpplTimings::getTimer("AMTS-SpaceCharge"));
-
-        IpplTimings::startTimer(IpplTimings::getTimer("AMTS-Kick"));
-        if(itsBunch->hasFieldSolver()) {
-            kick(0.5 * dt_outer);
+    std::queue<double> timeStepSizes(dtAllTracks_m);
+    std::queue<unsigned long long> numSteps(localTrackSteps_m);
+    double minTimeStep = timeStepSizes.front();
+    unsigned long long totalNumSteps = 0;
+    while (timeStepSizes.size() > 0) {
+        if (minTimeStep > timeStepSizes.front()) {
+            totalNumSteps = std::ceil(totalNumSteps * minTimeStep / timeStepSizes.front());
+            minTimeStep = timeStepSizes.front();
         }
-        IpplTimings::stopTimer(IpplTimings::getTimer("AMTS-Kick"));
-
-        IpplTimings::startTimer(IpplTimings::getTimer("AMTS-Dump"));
-        itsBunch->RefPart_R = RefPartR_zxy_m;
-        itsBunch->RefPart_P = RefPartP_zxy_m;
-        itsBunch->calcBeamParameters();
-        dumpStats(step, psDump, statDump);
-        IpplTimings::stopTimer(IpplTimings::getTimer("AMTS-Dump"));
+        totalNumSteps += std::ceil(numSteps.front() * timeStepSizes.front() / minTimeStep);
 
-        if(hasEndOfLineReached()) break;
-        itsBunch->incTrackSteps();
+        numSteps.pop();
+        timeStepSizes.pop();
     }
 
-    IpplTimings::stopTimer(IpplTimings::getTimer("AMTS"));
-
-    msg << "totalInnerSteps = " << totalInnerSteps << endl;
-
-    itsBunch->boundp();
-    numParticlesInSimulation_m = itsBunch->getTotalNum();
-    writePhaseSpace((step + 1), itsBunch->get_sPos(), true, true);
-    msg << "Dump phase space of last step" << endl;
-    itsOpalBeamline_m.switchElementsOff();
-    msg << "done executing ParallelTTracker at " << OPALTimer::Timer().time() << endl;
-}
-
-void ParallelTTracker::doSchottyRenormalization() {
-    Inform msg("ParallelTTracker ", *gmsg);
-    double init_erg = itsBunch->getEkin();
-    double tol_iter = 1e-5;
-    rescale_coeff_m = 1 / init_erg / init_erg;
-
-    if(Options::schottkyRennormalization > 0) {
-        rescale_coeff_m = Options:: schottkyRennormalization;
-        msg << "Set schottky scale coefficient to  " << rescale_coeff_m << endl;
-    } else if(Options::schottkyCorrection) {
-        while(true) {
-            double real_charge = schottkyLoop(rescale_coeff_m);
-
-            double total_charge = itsBunch->getTotalNum() * itsBunch->getChargePerParticle();
-            msg << "Schottky scale coefficient " << rescale_coeff_m << ", actual emitted charge " << real_charge << " (Cb)" << endl;
-            itsBunch->cleanUpParticles();
-            itsBunch->setT(0);
-            double scale_error = total_charge / real_charge - 1;
-            // TODO : send scale_error to all nodes
-            rescale_coeff_m *= (1.3 * scale_error + 1);
-            if(fabs(scale_error) < tol_iter)
-                break;
-        }
-        msg << "Schottky scan, final scale coefficient " << rescale_coeff_m << " ()" << endl;
-    }
-}
-
-double ParallelTTracker::schottkyLoop(double rescale_coeff) {
-
-    Inform msg("ParallelTTracker ", *gmsg);
-
-    double recpgamma;
-    double t = 0.0;
-    double dt = itsBunch->getdT();
-    Vector_t vscaleFactor = Vector_t(scaleFactor_m);
-
-    unsigned long long step = 0;
-    unsigned int emissionSteps = 0;
-
-    Vector_t um, a, s;
-    Vector_t externalE, externalB;
-    BorisPusher pusher(itsReference);
-    Vector_t rmin, rmax;
-
-    bool global_EOL;
-
-    bool hasSwitchedToTEmission = false;
-    bool hasSwitchedBackToTTrack = false;
+    itsOpalBeamline_m.activateElements();
 
-    size_t totalParticles_i = itsBunch->getTotalNum();
+    if (OpalData::getInstance()->hasPriorTrack() ||
+        OpalData::getInstance()->inRestartRun()) {
 
-    msg << "*****************************************************************" << endl;
-    msg << " Estimate Schottky correction                                    " << endl;
-    msg << "*****************************************************************" << endl;
+        referenceToLabCSTrafo_m = itsBunch_m->toLabTrafo_m;
+        RefPartR_m = referenceToLabCSTrafo_m.transformFrom(itsBunch_m->RefPartR_m);
+        RefPartP_m = referenceToLabCSTrafo_m.rotateFrom(itsBunch_m->RefPartP_m);
 
-    double margin = 0.0;
-    if(!mpacflg_m) {
-        for(unsigned int i = 0; i < itsBunch->getLocalNum(); ++i) {
-            long &l = itsBunch->LastSection[i];
-            l = -1;
-            itsOpalBeamline_m.getSectionIndexAt(itsBunch->R[i], l);
-            itsBunch->ResetLocalCoordinateSystem(i, itsOpalBeamline_m.getOrientation(l), itsOpalBeamline_m.getSectionStart(l));
-        }
+        pathLength_m = itsBunch_m->get_sPos();
+        zstart_m = pathLength_m;
 
-        if(!(itsBunch->WeHaveEnergyBins())) {
-            IpplTimings::startTimer(BinRepartTimer_m);
-            itsBunch->do_binaryRepart();
-            IpplTimings::stopTimer(BinRepartTimer_m);
-            Ippl::Comm->barrier();
-        }
+        restoreCavityPhases();
+    } else {
+        RefPartR_m = Vector_t(0.0);
+        RefPartP_m = euclidian_norm(itsBunch_m->get_pmean_Distribution()) * Vector_t(0, 0, 1);
 
-        // Check if there are any particles in simulation. If there are,
-        // as in a restart, use the usual function to calculate beam
-        // parameters. If not, calculate beam parameters of the initial
-        // beam distribution.
-        if(totalParticles_i == 0) {// fixme: maybe cause nonsense output if initialized momenta=0; Q: by Chuan.
-            itsBunch->calcBeamParametersInitial();
-        } else {
-            itsBunch->calcBeamParameters();
-        }
+        if (itsBunch_m->getTotalNum() > 0) {
+            if (!itsOpalBeamline_m.containsSource()) {
+                RefPartP_m = euclidian_norm(itsBunch_m->get_pmean())  * Vector_t(0, 0, 1);
+            }
 
-        RefPartR_suv_m = RefPartR_zxy_m = itsBunch->get_rmean();
-        RefPartP_suv_m = RefPartP_zxy_m = itsBunch->get_pmean();
+            if (zstart_m > pathLength_m) {
+                findStartPosition(pusher);
+            }
 
-        if(!OpalData::getInstance()->hasBunchAllocated()) {
-            updateSpaceOrientation(false);  // vec{p} = (0,0,p_z), vec{r} = (0,0,z)
+            itsBunch_m->set_sPos(pathLength_m);
         }
-
-        RefPartR_suv_m = itsBunch->get_rmean();
-        RefPartP_suv_m = itsBunch->get_pmean();
-        /* Activate all elements which influence the particles when the simulation starts;
-         *  mark all elements which are already past.
-         */
-
-        /*
-         increase margin from 3.*c*dt to 10.*c*dt to prevent that fieldmaps are accessed
-         before they are allocated when increasing the timestep in the gun.
-         */
-        itsBunch->get_bounds(rmin, rmax);
-        margin = 10. * RefPartP_suv_m(2) * scaleFactor_m / sqrt(1.0 + pSqr(RefPartP_suv_m, RefPartP_suv_m));
-        margin = 0.01 > margin ? 0.01 : margin;
-        itsOpalBeamline_m.switchElements(rmin(2) - margin, rmax(2) + margin, getEnergyMeV(RefPartP_suv_m));
     }
 
-    double minBinEmitted  = 10.0;
-    RealVariable *ar = dynamic_cast<RealVariable *>(OpalData::getInstance()->find("MINBINEMITTED"));
-    if(ar) {
-        minBinEmitted = ar->getReal();  // the space charge solver crashes if we use less than ~10 particles.
-        // This variable controls the number of particles to be emitted before we use
-        // the space charge solver.
-
-        msg << level3 << "MINBINEMITTED " << minBinEmitted << endl;
-    }
-
-
-    double minStepforReBin  = 10000.0;
-    RealVariable *br = dynamic_cast<RealVariable *>(OpalData::getInstance()->find("MINSTEPFORREBIN"));
-    if(br) {
-        minStepforReBin = br->getReal();  // this variable controls the minimal number of steps of emission (using bins)
-        // before we can merge the bins
-        msg << level3 << "MINSTEPFORREBIN " << minStepforReBin << endl;
-    }
+    Vector_t rmin, rmax;
+    itsBunch_m->get_bounds(rmin, rmax);
+    OrbitThreader oth(itsReference,
+                      referenceToLabCSTrafo_m.transformTo(RefPartR_m),
+                      referenceToLabCSTrafo_m.rotateTo(RefPartP_m),
+                      pathLength_m,
+                      -rmin(2),
+                      itsBunch_m->getT(),
+                      minTimeStep,
+                      totalNumSteps,
+                      zStop_m.back() + 2 * rmax(2),
+                      itsOpalBeamline_m);
 
-    int repartFreq = 1000;
-    RealVariable *rep = dynamic_cast<RealVariable *>(OpalData::getInstance()->find("REPARTFREQ"));
-    if(rep) {
-        repartFreq = static_cast<int>(rep->getReal());  // this variable controls the minimal number of steps until we repartition the particles
-        msg << level3 << "REPARTFREQ " << repartFreq << endl;
-    }
+    oth.execute();
 
-    // there is no point to do repartitioning with one node
-    if(Ippl::getNodes() == 1)
-        repartFreq = 1000000;
+    saveCavityPhases();
 
-    size_t totalParticles_f = 0;
+    numParticlesInSimulation_m = itsBunch_m->getTotalNum();
 
-    for(; step < localTrackSteps_m.front(); ++step) {
-        global_EOL = true;  // check if any particle hasn't reached the end of the field from the last element
-
-        itsOpalBeamline_m.resetStatus();
+    setTime();
 
-        IpplTimings::startTimer(timeIntegrationTimer1_m);
+    double t = itsBunch_m->getT() - globalTimeShift;
+    itsBunch_m->setT(t);
 
-        // reset E and B to Vector_t(0.0) for every step
+    itsBunch_m->RefPartR_m = referenceToLabCSTrafo_m.transformTo(RefPartR_m);
+    itsBunch_m->RefPartP_m = referenceToLabCSTrafo_m.rotateTo(RefPartP_m);
 
-        itsBunch->Ef = Vector_t(0.0);
-        itsBunch->Bf = Vector_t(0.0);
+    t = itsBunch_m->getT();
 
-        Nimpact_m = 0; // Initial parallel plate benchmark variable.
-        SeyNum_m = 0; // Initial parallel plate benchmark variable.
+    *gmsg << level1 << *itsBunch_m << endl;
 
-        for(unsigned int i = 0; i < itsBunch->getLocalNum(); ++i) {
-            //scale each particle with c*dt
-            itsBunch->R[i] /= vscaleFactor;
-            pusher.push(itsBunch->R[i], itsBunch->P[i], itsBunch->dt[i]);
-            // update local coordinate system of particleInform &PartBunc
-            itsBunch->X[i] /= vscaleFactor;
-            pusher.push(itsBunch->X[i], TransformTo(itsBunch->P[i], itsOpalBeamline_m.getOrientation(itsBunch->LastSection[i])),
-                        itsBunch->getdT());
-            itsBunch->X[i] *= vscaleFactor;
-        }
+    unsigned long long step = itsBunch_m->getGlobalTrackStep();
+    OPALTimer::Timer myt1;
+    *gmsg << "Track start at: " << myt1.time() << ", t= " << Util::getTimeString(t) << "; "
+          << "zstart at: " << Util::getLengthString(pathLength_m)
+          << endl;
 
-        if(totalParticles_i > minBinEmitted) {
-            itsBunch->boundp();
-        }
+    prepareEmission();
 
-        IpplTimings::stopTimer(timeIntegrationTimer1_m);
-
-        itsBunch->calcBeamParameters();
-
-
-        /** \f[ Space Charge  \f]
-         */
-        if(itsBunch->hasFieldSolver() && totalParticles_i > minBinEmitted && fabs(itsBunch->getChargePerParticle()) > 0.0) {
-            // Do repartition if we have enough particles.
-            if(totalParticles_i > 1000 && (((step + 1) % repartFreq) == 0)) {
-                INFOMSG("*****************************************************************" << endl);
-                INFOMSG("do repartition because of repartFreq" << endl);
-                INFOMSG("*****************************************************************" << endl);
-                IpplTimings::startTimer(BinRepartTimer_m);
-                itsBunch->do_binaryRepart();
-                IpplTimings::stopTimer(BinRepartTimer_m);
-                Ippl::Comm->barrier();
-                INFOMSG("*****************************************************************" << endl);
-                INFOMSG("do repartition done" << endl);
-                INFOMSG("*****************************************************************" << endl);
-            }
+    *gmsg << level1
+          << "Executing ParallelTTracker, initial dt= " << Util::getTimeString(itsBunch_m->getdT()) << ";\n"
+          << "max integration steps " << getMaxSteps(localTrackSteps_m) << ", next step= " << step << endl;
 
-            // Calculate space charge.
-            if(itsBunch->WeHaveEnergyBins()) {
-                // When we have energy bins.
-                itsBunch->calcGammas();
-                ParticleAttrib<double> Q_back = itsBunch->Q;
-                itsBunch->resetInterpolationCache();
-                for(int binNumber = 0; binNumber <= itsBunch->getLastemittedBin() && binNumber < itsBunch->getNumBins(); ++binNumber) {
-                    itsBunch->setBinCharge(binNumber);
-                    itsBunch->computeSelfFields(binNumber);
-                    itsBunch->Q = Q_back;
-                }
-            } else {
-                // When we don't.
-                itsBunch->computeSelfFields();
-                /**
-                 Need this maybe for the adaptive time integration scheme
-                 pair<Vector_t,Vector_t> eExtrema = itsBunch->getEExtrema();
-                 INFOMSG("maxE= " << eExtrema.first << " minE= " << eExtrema.second << endl);
-                 */
-            }
-        }
+    setOptionalVariables();
 
-        IpplTimings::startTimer(timeIntegrationTimer2_m);
+    itsBunch_m->toLabTrafo_m = referenceToLabCSTrafo_m;
 
+    // loggingFrequency_m = floor(1e-11/itsBunch_m->getdT() + 0.5);
+    globalEOL_m = false;
+    wakeStatus_m = false;
+    deletedParticles_m = false;
+    OpalData::getInstance()->setInPrepState(false);
+    while (localTrackSteps_m.size() > 0) {
+        localTrackSteps_m.front() += step;
+        dtCurrentTrack_m = dtAllTracks_m.front();
+        changeDT();
 
-        /*
-         transport and emit particles
-         that passed the cathode in the first
-         half-step or that would pass it in the
-         second half-step.
+        for (; step < localTrackSteps_m.front(); ++step) {
 
-         to make IPPL and the field solver happy
-         make sure that at least 10 particles are emitted
+            timeIntegration1(pusher);
 
-         also remember that node 0 has
-         all the particles to be emitted
+            itsBunch_m->Ef = Vector_t(0.0);
+            itsBunch_m->Bf = Vector_t(0.0);
 
-         this has to be done *after* the calculation of the
-         space charges! thereby we neglect space charge effects
-         in the very first step of a new-born particle.
+            computeSpaceChargeFields(step);
 
-         */
+            selectDT();
+            emitParticles(step);
+            selectDT();
 
-        if((itsBunch->WeHaveEnergyBins())) {
+            computeExternalFields(oth);
 
-            // switch to TEmission
-            if(!hasSwitchedToTEmission) {
-                dt = itsBunch->GetEmissionDeltaT();
-                itsBunch->setdT(dt);
-                scaleFactor_m = dt * Physics::c;
-                vscaleFactor = Vector_t(scaleFactor_m);
-                msg << "Changing emission time step to: " << dt << endl;
-                hasSwitchedToTEmission = true;
-            }
+            timeIntegration2(pusher);
 
-            int ne = 0;
-            Vector_t externalE = Vector_t(0.0);
-            Vector_t externalB = Vector_t(0.0);
-            itsOpalBeamline_m.getFieldAt(Vector_t(0.0),
-                                         Vector_t(0.0),
-                                         itsBunch->getT() + 0.5 * itsBunch->getdT(),
-                                         externalE,
-                                         externalB);
-            ne += itsBunch->EmitParticles(externalE[2]);
-
-            if(Options::schottkyCorrection && !hasSwitchedBackToTTrack)
-                applySchottkyCorrection(*itsBunch, ne, t, rescale_coeff);
-
-            reduce(ne, ne, OpAddAssign());
-            totalParticles_i += ne;
-
-            //emission has finished, reset to TTrack
-            if(itsBunch->getNumBins() == itsBunch->getLastemittedBin() &&
-               !hasSwitchedBackToTTrack) {
-                //dt = dtTrack;
-                itsBunch->setdT(dt);
-                scaleFactor_m = dt * Physics::c;
-                vscaleFactor = Vector_t(scaleFactor_m);
-                msg << "Emission done. Switching back to track timestep: " << dt << endl;
-                hasSwitchedBackToTTrack = true;
-                break;
-            }
+            t += itsBunch_m->getdT();
+            itsBunch_m->setT(t);
 
-        } else {
-            //emission has finished, reset to TTrack
-            if(!hasSwitchedBackToTTrack) {
-                //dt = dtTrack;
-                itsBunch->setdT(dt);
-                scaleFactor_m = dt * Physics::c;
-                vscaleFactor = Vector_t(scaleFactor_m);
-                msg << "Emission done. Switching back to track timestep: " << dt << endl;
-                hasSwitchedBackToTTrack = true;
+            if (t > 0.0) {
+                updateRefToLabCSTrafo(pusher);
             }
 
-        }
-
-        // push the reference particle by a half step
-        recpgamma = 1.0 / sqrt(1.0 + dot(RefPartP_suv_m, RefPartP_suv_m));
-        RefPartR_zxy_m += RefPartP_zxy_m * recpgamma / 2. * scaleFactor_m;
-
-        //
-        // get external fields for all particles
-        //
-        IpplTimings::startTimer(timeFieldEvaluation_m);
-        for(unsigned int i = 0; i < itsBunch->getLocalNum(); ++i) {
-            //FIXME: rethink scaling!
-            itsBunch->R[i] *= Vector_t(Physics::c * itsBunch->dt[i], Physics::c * itsBunch->dt[i], Physics::c * itsBunch->dt[i]);
-
-            long ls = itsBunch->LastSection[i];
-            itsOpalBeamline_m.getSectionIndexAt(itsBunch->R[i], ls);
-            if(ls != itsBunch->LastSection[i]) {
-                if(!itsOpalBeamline_m.section_is_glued_to(itsBunch->LastSection[i], ls)) {
-                    itsBunch->ResetLocalCoordinateSystem(i, itsOpalBeamline_m.getOrientation(ls), itsOpalBeamline_m.getSectionStart(ls));
-                }
-                itsBunch->LastSection[i] = ls;
+            if (deletedParticles_m) {
+                evenlyDistributeParticles();
+                deletedParticles_m = false;
             }
-            const unsigned long rtv = itsOpalBeamline_m.getFieldAt(i, itsBunch->R[i], ls, t + itsBunch->dt[i] / 2., externalE, externalB);
-
-            global_EOL = global_EOL && (rtv & BEAMLINE_EOL);
-
-            // skip rest of the particle push if the
-            // particle is out of bounds i.e. does not see
-            // a E or B field
-            if(rtv & BEAMLINE_OOB)
-                itsBunch->Bin[i] = -1;
-
-
-            itsBunch->Ef[i] += externalE;
-            itsBunch->Bf[i] += externalB;
-
-            itsBunch->R[i] /= Vector_t(Physics::c * itsBunch->dt[i], Physics::c * itsBunch->dt[i], Physics::c * itsBunch->dt[i]);
-
-            // in case a particle is pushed behind the emission surface, delete the particle
-
-            if(itsBunch->R[i](2) < 0)
-                itsBunch->Bin[i] = -1;
-
-        }
-
-        IpplTimings::stopTimer(timeFieldEvaluation_m);
+            itsBunch_m->toLabTrafo_m = referenceToLabCSTrafo_m;
+            itsBunch_m->RefPartR_m = referenceToLabCSTrafo_m.transformTo(RefPartR_m);
+            itsBunch_m->RefPartP_m = referenceToLabCSTrafo_m.rotateTo(RefPartP_m);
+            itsBunch_m->set_sPos(pathLength_m);
 
-        // if(itsBunch->getLocalNum() == 0)
-        //    global_EOL = false;
+            if (hasEndOfLineReached()) break;
 
-        /**
-         Delete marked particles.
-         */
-
-        bool globPartOutOfBounds = (min(itsBunch->Bin) < 0);
-        size_t ne = 0;
-        if(globPartOutOfBounds) {
-            ne = itsBunch->boundp_destroyT();
-        }
-
-        totalParticles_f = totalParticles_i - ne;
-        if(ne > 0)
-            msg << "* Deleted in Shotky " << ne << " particles, remaining "
-                << totalParticles_f << " particles" << endl; //benchmark output
-
-        kickParticles(pusher);
-
-        if(totalParticles_f > 0) {
-            // none of the particles is in a bending element
-            updateReferenceParticle();
-        }
-
-        itsBunch->RefPart_R = RefPartR_zxy_m;
-        itsBunch->RefPart_P = RefPartP_zxy_m;
-
-        /*
-          calculate the dimensions of the bunch and add a small margin to them;
-          then decide which elements have to be triggered when an element is
-          triggered memory is allocated and the field map is read in
-        */
-        itsBunch->get_bounds(rmin, rmax);
-
-        // trigger the elements
-        margin = 3. * RefPartP_suv_m(2) * recpgamma;
-        margin = 0.01 > margin ? 0.01 : margin;
-        itsOpalBeamline_m.switchElements(
-            (rmin(2) - margin)*scaleFactor_m,
-            (rmax(2) + margin)*scaleFactor_m,
-            getEnergyMeV(RefPartP_suv_m));
-
-        // start normal particle loop part 2 for simulation without boundary geometry.
-        for(unsigned int i = 0; i < itsBunch->getLocalNum(); ++i) {
-            pusher.push(itsBunch->R[i], itsBunch->P[i], itsBunch->dt[i]);
-            //and scale back to dimensions
-            itsBunch->R[i] *= Vector_t (
-                Physics::c * itsBunch->dt[i],
-                Physics::c * itsBunch->dt[i],
-                Physics::c * itsBunch->dt[i]);
-            // update local coordinate system
-            itsBunch->X[i] /= vscaleFactor;
-            pusher.push(
-                itsBunch->X[i],
-                TransformTo (
-                    itsBunch->P[i],
-                    itsOpalBeamline_m.getOrientation(itsBunch->LastSection[i])),
-                itsBunch->getdT());
-            itsBunch->X[i] *= vscaleFactor;
-            //reset time step if particle was emitted in the first half-step
-            //the particle is now in sync with the simulation timestep
-            itsBunch->dt[i] = itsBunch->getdT();
-        }
-
-        IpplTimings::stopTimer(timeIntegrationTimer2_m);
-
-        if(totalParticles_f > minBinEmitted)
-            itsBunch->boundp();
-
-        totalParticles_i = itsBunch->getTotalNum();
-
-
-        t += itsBunch->getdT(); //t after a full global timestep with dT "synchronization point" for simulation time
+            bool const psDump = ((itsBunch_m->getGlobalTrackStep() % Options::psDumpFreq) + 1 == Options::psDumpFreq);
+            bool const statDump = ((itsBunch_m->getGlobalTrackStep() % Options::statDumpFreq) + 1 == Options::statDumpFreq);
+            dumpStats(step, psDump, statDump);
 
-        itsBunch->setT(t);
+            itsBunch_m->incTrackSteps();
 
-        //IFF: cheap step dump regulation
-        OPALTimer::Timer myt2;
-        double sposRef = 0.0;
-        if(totalParticles_f > 0) {
-            sposRef = itsBunch->get_sPos();
-            if(totalParticles_f <= minBinEmitted) {
-                INFOMSG(myt2.time() << " Step " << step << "; only " << totalParticles_f << " particles emitted; t= " << t
-                        << " [s] E=" << itsBunch->get_meanEnergy() << " [MeV] " << endl);
-            } else if(std::isnan(sposRef) || std::isinf(sposRef)) {
-                INFOMSG(myt2.time() << " Step " << step
-                        << "; there seems to be something wrong with the position of the bunch!" << endl);
-            } else {
-                INFOMSG(myt2.time() << " Step " << step
-                        << " at " << sposRef << " [m] t= " << t << " [s] E=" << itsBunch->get_meanEnergy() << " [MeV] " << endl);
-                if(step % Options::psDumpFreq == 0 || step % Options::statDumpFreq == 0) {
-                    size_t nLoc = itsBunch->getLocalNum();
-                    reduce(nLoc, nLoc, OpMultipplyAssign());
-                    if((nLoc == 0) || ((step + 1) % repartFreq == 0)) {
-                        INFOMSG("*****************************************************************" << endl);
-                        INFOMSG("do repartition because of zero particles or repartition frequency" << endl);
-                        IpplTimings::startTimer(BinRepartTimer_m);
-                        itsBunch->do_binaryRepart();
-                        IpplTimings::stopTimer(BinRepartTimer_m);
-                        Ippl::Comm->barrier();
-                        INFOMSG("done" << endl);
-                        INFOMSG("*****************************************************************" << endl);
-                    }
-                }
-            }
-            /**
-             Stop simulation if beyond zStop_m
-             */
-            if(sposRef > zStop_m.front()) {
+            if (pathLength_m > zStop_m.front())
                 localTrackSteps_m.front() = step;
-            }
-        } else {
-            INFOMSG("Step " << step << " no emission yet "  << " t= " << t << " [s]" << endl);
         }
 
-        if(step > emissionSteps) {
-            reduce(&global_EOL, &global_EOL + 1, &global_EOL, OpBitwiseAndAssign());
-            if(global_EOL) {
-                break;
-            }
-        }
-        // this seams to fix Ticket #12
-        //  Ippl::Comm->barrier();
-        itsBunch->get_bounds(rmin, rmax);
-        // trigger the elements
-        RefPartP_suv_m = itsBunch->get_pmean();
-        recpgamma = 1. / sqrt(1.0 + dot(RefPartP_suv_m, RefPartP_suv_m));
-
-        margin = 10. * RefPartP_suv_m(2) * recpgamma * scaleFactor_m;
-        margin = 0.01 > margin ? 0.01 : margin;
-    }
-    OPALTimer::Timer myt3;
-    OpalData::getInstance()->setLastStep(step);
-    msg << "done executing Schottky loop " << myt3.time() << endl;
-    return itsBunch->getCharge();
-}
-
-
-void ParallelTTracker::applySchottkyCorrection(PartBunch &itsBunch, int ne, double t, double rescale_coeff) {
+        if (globalEOL_m)
+            break;
 
-    Inform msg("ParallelTTracker ", *gmsg);
-    const long ls = 0;
-    /*
-     Now I can calculate E_{rf} at each position
-     of the newely generated particles and rescale Q
-
-     Note:
-     For now I only sample the field of the last emitted particles.
-     Space charge is not yet included
-     */
-
-    double laser_erg = itsBunch.getLaserEnergy();
-    double workFunction = itsBunch.getWorkFunctionRf();
-    // coeffecient for calculate schottky potenial from E field [eV/(MV^0.5)]
-    const double schottky_coeff = 0.037947;
-
-    if(ne == 0)
-        return ;
-
-    double Ez = 0;
-    double obtain_erg = 0;
-    double par_t = 0;
-    for(int k = 0; k < ne; k++) {
-        size_t n = itsBunch.getLocalNum() - k - 1;
-        Vector_t externalE(0.0);
-        Vector_t externalB(0.0);
-
-        itsBunch.R[n] *= Vector_t(Physics::c * itsBunch.dt[n]);
-        par_t = t + itsBunch.dt[n] / 2;
-        itsOpalBeamline_m.getFieldAt(n, itsBunch.R[n], ls, par_t, externalE, externalB);
-        Ez = externalE(2);
-
-        /*
-          fabs(Ez): if the field of cathode surface is in the right direction,
-          it will increase the energy which electron obtain. If the field is in
-          the wrong direction, this particle will be back to the cathode surface
-          and then be deleted automaticly by OPAL,  we don't add another logical
-          branch to handle this. So fabs is the simplest way to handle this
-        */
-        obtain_erg = laser_erg - workFunction + schottky_coeff * sqrt(fabs(Ez) / 1E6);
-        double schottkyScale = obtain_erg * obtain_erg * rescale_coeff;
-
-        itsBunch.Q[n] *= schottkyScale;
-        itsBunch.R[n] /= Vector_t(Physics::c * itsBunch.dt[n]);
+        dtAllTracks_m.pop();
+        localTrackSteps_m.pop();
+        zStop_m.pop();
     }
-}
-
-void ParallelTTracker::bgf_main_collision_test() {
-    if(!bgf_m) return;
 
-    const Vector_t outr = bgf_m->getmaxcoords() + bgf_m->gethr();
-    /**
-     Here we check if a particles is
-     outside the geometry, flag it for
-     deletion and create secondaries
-     */
-    size_t Inc_num = itsBunch->getLocalNum();
-    for(size_t i = 0; i < Inc_num; i++) {
-        double dtime = 0.5 * itsBunch->getdT();
-        double seyNum = 0;
-        if(secondaryFlg_m != 0) {//chuan: only for the secondary emission, change the particle type to be the old secondaries.
-            if(itsBunch->PType[i] == ParticleType::NEWSECONDARY)
-                itsBunch->PType[i] = ParticleType::SECONDARY;
-        }
+    itsBunch_m->toLabTrafo_m = referenceToLabCSTrafo_m;
+    itsBunch_m->RefPartR_m = referenceToLabCSTrafo_m.transformTo(RefPartR_m);
+    itsBunch_m->RefPartP_m = referenceToLabCSTrafo_m.rotateTo(RefPartP_m);
+    itsBunch_m->set_sPos(pathLength_m);
 
-        /*
-          for primary bunch, primary dark current particles,
-          old secondaries in previous time steps and newly
-          generated secondaries which have no collision with
-          boundary in both first and second half step, do main
-          collision test and emit the secondaries.
-        */
-        int res = 0;
-        int triId = itsBunch->TriID[i];
-        Vector_t position = itsBunch->R[i];
-        if (triId == 0) {
-            // no previous collision
-            Vector_t intersection_pt = outr;
-            res = bgf_m->PartInside (
-                itsBunch->R[i],
-                itsBunch->P[i],
-                dtime,
-                itsBunch->PType[i],
-                itsBunch->Q[i],
-                intersection_pt,
-                itsBunch->TriID[i]);//Chuan: should be itsBunch->TriID[i];
-            if (res < 0) continue;
-            position = intersection_pt;
-        }
+    if (numParticlesInSimulation_m > minBinEmitted_m) {
+        numParticlesInSimulation_m = itsBunch_m->getTotalNum();
+    }
 
-        /*
-          Attention: New secondaries have not been kicked and are without new momentum.
-        */
-        if (secondaryFlg_m == 1) {
-            res += bgf_m->emitSecondaryFurmanPivi (
-                position,
-                i,
-                itsBunch, seyNum);
-
-        } else if (secondaryFlg_m != 0) {
-            res += bgf_m->emitSecondaryVaughan (
-                position,
-                i,
-                itsBunch, seyNum);
+    bool const psDump = (((itsBunch_m->getGlobalTrackStep() - 1) % Options::psDumpFreq) + 1 != Options::psDumpFreq);
+    bool const statDump = (((itsBunch_m->getGlobalTrackStep() - 1) % Options::statDumpFreq) + 1 != Options::statDumpFreq);
+    writePhaseSpace((step + 1), psDump, statDump);
 
-        } else {
-            res += bgf_m->emitSecondaryNone (
-                position, triId);
-        }
-        if(res >= 0) {
-            itsBunch->Bin[i] = -1;
-            Nimpact_m++;
-            SeyNum_m += seyNum;
-        }
-    } // end for()
+    msg << level2 << "Dump phase space of last step" << endl;
 
-    for(size_t i = 0; i < itsBunch->getLocalNum(); i++) {
-        if (bgf_m->isOutsideApperture(itsBunch->R[i])) {
-            itsBunch->Bin[i] = -1;
-        }
-    }
+    itsOpalBeamline_m.switchElementsOff();
 
-    // Now we do field emission
-    if(itsBunch->getT() < surfaceEmissionStop_m)
-        numberOfFieldEmittedParticles_m +=
-            bgf_m->doFNemission (itsOpalBeamline_m, itsBunch, itsBunch->getT());
+    OPALTimer::Timer myt3;
+    *gmsg << "done executing ParallelTTracker at " << myt3.time() << endl;
 
-    itsBunch->boundp();
-    numParticlesInSimulation_m = itsBunch->getTotalNum();
-}
+    LossDataSink::writeStatistics();
 
-void ParallelTTracker::handleOverlappingMonitors() {
-    // make sure that no monitor has overlap with two tracks
-    FieldList monitors = itsOpalBeamline_m.getElementByType(ElementBase::MONITOR);
-    for(FieldList::iterator it = monitors.begin(); it != monitors.end(); ++ it) {
-        double zbegin, zend;
-        it->getElement()->getDimensions(zbegin, zend);
-        if(zbegin < zStop_m.front() && zend >= zStop_m.back()) {
-            ERRORMSG(
-                "\033[0;31m"
-                << "%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n"
-                << "% Removing '" << it->getElement()->getName() << "' since it resides in two tracks.   %\n"
-                << "% Please adjust zstop or place your monitor at a different position to prevent this. %\n "
-                << "%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n"
-                << "\033[0m"
-                << endl);
-            static_cast<Monitor *>(it->getElement().get())->moveBy(-zend - 0.001);
-            itsOpalBeamline_m.removeElement(it->getElement()->getName());
-        }
-    }
+    OpalData::getInstance()->setPriorTrack();
 }
 
 void ParallelTTracker::prepareSections() {
 
     itsBeamline_m.accept(*this);
-    handleOverlappingMonitors();
     itsOpalBeamline_m.prepareSections();
-
-    cavities_m = itsOpalBeamline_m.getElementByType(ElementBase::RFCAVITY);
-    FieldList travelingwaves = itsOpalBeamline_m.getElementByType(ElementBase::TRAVELINGWAVE);
-    cavities_m.merge(travelingwaves, ClassicField::SortAsc);
 }
 
 void ParallelTTracker::timeIntegration1(BorisPusher & pusher) {
 
-    IpplTimings::startTimer(timeIntegrationTimer1_m);
-    if(bgf_m != NULL && secondaryFlg_m > 0) return;
-
-    IpplTimings::startTimer(timeIntegrationTimer1Push_m);
-
-    if (IpplInfo::DKSEnabled) {
-#ifdef OPAL_DKS
-        //if bunch is largen than before reallocate memory
-        if (itsBunch->getLocalNum() > numDeviceElements) {
-            freeDeviceMemory();
-            unregisterHostMemory();
-            allocateDeviceMemory();
-            registerHostMemory();
-        }
-
-        //get all the section orientations
-        int nsec = itsOpalBeamline_m.sections_m.size();
-        Vector_t *orientation = new Vector_t[nsec];
-        for (long i = 0; i < nsec; i++) {
-            orientation[i] = itsOpalBeamline_m.getOrientation(i);
-        }
-    
-        //write orientations to device
-        dksbase.writeData<Vector_t>(orient_ptr, orientation, nsec);
-
-        //free local orientation memory
-        delete[] orientation;
-        
-        //write R to device
-        dksbase.writeDataAsync<Vector_t>(r_ptr, &itsBunch->R[0], 
-                                         itsBunch->getLocalNum(), stream1);
-        //write P to device
-        dksbase.writeDataAsync<Vector_t>(p_ptr, &itsBunch->P[0], 
-                                         itsBunch->getLocalNum(), stream1);
-        //write X to device
-        dksbase.writeDataAsync<Vector_t>(x_ptr, &itsBunch->X[0], 
-                                         itsBunch->getLocalNum(), stream2);
-
-        //write dt to device
-        dksbase.writeDataAsync<double>(dt_ptr, &itsBunch->dt[0], 
-                                       itsBunch->getLocalNum(), stream1);
-
-        //calc push
-        dksbase.callParallelTTrackerPush (r_ptr, p_ptr, itsBunch->getLocalNum(), dt_ptr,
-                                          itsBunch->getdT(), Physics::c, true, stream1);
-        //read R from device
-        dksbase.readDataAsync<Vector_t> (r_ptr, &itsBunch->R[0], 
-                                         itsBunch->getLocalNum(), stream1);
-
-        //write LastSection to device
-        dksbase.writeDataAsync<long> (lastSec_ptr, &itsBunch->LastSection[0], 
-                                      itsBunch->getLocalNum(), stream2);
-        //calc push
-        dksbase.callParallelTTrackerPushTransform(x_ptr, p_ptr, lastSec_ptr, orient_ptr,
-                                                  itsBunch->getLocalNum(),
-                                                  itsOpalBeamline_m.sections_m.size(),
-                                                  dt_ptr, itsBunch->getdT(), Physics::c, 
-                                                  false, stream2);
-        //read R from device
-        dksbase.readDataAsync<Vector_t>(x_ptr, &itsBunch->X[0], itsBunch->getLocalNum(), stream2);
-
-        //sync and wait till all tasks and reads are complete
-        dksbase.syncDevice();
-#endif
-    } else {
-        itsBunch->switchToUnitlessPositions();
-        for(unsigned int i = 0; i < itsBunch->getLocalNum(); ++i) {
-            //scale each particle with c*dt
-            pusher.push(itsBunch->R[i], itsBunch->P[i], itsBunch->dt[i]);
-
-            // update local coordinate system of particleInform &PartBunc
-            pusher.push(
-                itsBunch->X[i],
-                TransformTo(
-                    itsBunch->P[i],
-                    itsOpalBeamline_m.getOrientation(itsBunch->LastSection[i])),
-                itsBunch->getdT());
-        }
-        itsBunch->switchOffUnitlessPositions();
-    }
-    IpplTimings::stopTimer(timeIntegrationTimer1Push_m);
-
-    if(numParticlesInSimulation_m > minBinEmitted_m) {
-        itsBunch->boundp();
-    }
-    IpplTimings::stopTimer(timeIntegrationTimer1_m);
-}
-
-void ParallelTTracker::timeIntegration1_bgf(BorisPusher & pusher) {
-    if(bgf_m == NULL || secondaryFlg_m == 0) return;
-    IpplTimings::startTimer(timeIntegrationTimer1_m);
-
-    /*
-      We do collision test for newly generated secondaries before integration
-      in the first half step of each time step.  This is because only secondary
-      emission model yield non zero inital momenta. The initial momenta of
-      field emitted particles are zero.  If hit, we set itsBunch->R[i] to
-      intersection points, else we do normal integration.
-    */
-    Nimpact_m = 0;  // Initial parallel plate benchmark variable.
-    SeyNum_m = 0;   // Initial parallel plate benchmark variable.
-
-    const Vector_t outr = bgf_m->getmaxcoords() + bgf_m->gethr();
-    double dt = itsBunch->getdT();
-    double bgf_scaleFactor = dt * Physics::c;
-    Vector_t bgf_vscaleFactor = Vector_t(bgf_scaleFactor);
-
-    for(unsigned int i = 0; i < itsBunch->getLocalNum(); ++i) {
-        bool particleHitBoundary = false;
-        Vector_t intecoords = outr;
-        int triId = 0;
-        if (itsBunch->PType[i] == ParticleType::NEWSECONDARY) {
-            particleHitBoundary = bgf_m->PartInside(
-                itsBunch->R[i],
-                itsBunch->P[i],
-                0.5 * itsBunch->dt[i],
-                itsBunch->PType[i],
-                itsBunch->Q[i],
-                intecoords,
-                triId) == 0;
-        }
-        Vector_t rtmp = itsBunch->R[i];
-        if(particleHitBoundary && (std::fabs(rtmp[0]-intecoords[0])>EPS) && (std::fabs(rtmp[1]-intecoords[1])>EPS) && (std::fabs(rtmp[2]-intecoords[2])>EPS)) {
-            /*
-              set particle position to intersection points coordinates and
-              scale the position;
-              no scaling required
-            */
-            itsBunch->R[i] = intecoords/bgf_vscaleFactor;
-            itsBunch->TriID[i] = triId;
-        } else {
-            itsBunch->R[i] /= bgf_vscaleFactor;
-            pusher.push(itsBunch->R[i], itsBunch->P[i], itsBunch->dt[i]);
-        }
-        /*
-          :FIXME: is the local update necessary here?
-          update local coordinate system for particle
-        */
-        itsBunch->X[i] /= bgf_vscaleFactor;
-        pusher.push (
-            itsBunch->X[i],
-            TransformTo(
-                itsBunch->P[i],
-                itsOpalBeamline_m.getOrientation(itsBunch->LastSection[i])),
-            itsBunch->getdT());
-
-        itsBunch->R[i] *= bgf_vscaleFactor;
-        itsBunch->X[i] *= bgf_vscaleFactor;
-
-
-    }
-
-
-    if(numParticlesInSimulation_m > minBinEmitted_m) {
-        itsBunch->boundp();
-    }
-    IpplTimings::stopTimer(timeIntegrationTimer1_m);
-}
-
-void ParallelTTracker::timeIntegration2(BorisPusher & pusher) {
-    if(bgf_m) return;
-    /*
-     transport and emit particles
-     that passed the cathode in the first
-     half-step or that would pass it in the
-     second half-step.
-
-     to make IPPL and the field solver happy
-     make sure that at least 10 particles are emitted
-
-     also remember that node 0 has
-     all the particles to be emitted
-
-     this has to be done *after* the calculation of the
-     space charges! thereby we neglect space charge effects
-     in the very first step of a new-born particle.
-
-     */
-
-    IpplTimings::startTimer(timeIntegrationTimer2_m);
-    // push the reference particle by a half step
-    double recpgamma = 1.0 / sqrt(1.0 + dot(RefPartP_suv_m, RefPartP_suv_m));
-    RefPartR_zxy_m += RefPartP_zxy_m * recpgamma / 2. * scaleFactor_m;
-    kickParticles(pusher);
-    handleBends();
-
-    //switchElements();
-    IpplTimings::startTimer(timeIntegrationTimer2Push_m);
-    if (IpplInfo::DKSEnabled) {
-#ifdef OPAL_DKS
-    
-        //if bunch is largen than before reallocate memory
-        if (itsBunch->getLocalNum() > numDeviceElements) {
-            freeDeviceMemory();
-            unregisterHostMemory();
-            allocateDeviceMemory();
-            registerHostMemory();
-        }
-
-        //get all the section orientations
-        int nsec = itsOpalBeamline_m.sections_m.size();
-        Vector_t *orientation = new Vector_t[nsec];
-        for (long i = 0; i < nsec; i++) {
-            orientation[i] = itsOpalBeamline_m.getOrientation(i);
-        }
-
-        //write orientations to device
-        dksbase.writeData<Vector_t>(orient_ptr, orientation, nsec);
-
-        //free local orientation memory
-        delete[] orientation;
-
-        //write R to device
-        dksbase.writeDataAsync<Vector_t>(r_ptr, &itsBunch->R[0], 
-                                         itsBunch->getLocalNum(), stream1);
-        //write P to device
-        dksbase.writeDataAsync<Vector_t>(p_ptr, &itsBunch->P[0], 
-                                         itsBunch->getLocalNum(), stream1);
-        //write X to device
-        dksbase.writeDataAsync<Vector_t>(x_ptr, &itsBunch->X[0], 
-                                         itsBunch->getLocalNum(), stream2);
-
-        //wrote dt to device
-        dksbase.writeDataAsync<double>(dt_ptr, &itsBunch->dt[0], 
-                                       itsBunch->getLocalNum(), stream1);
-        //calc push
-        dksbase.callParallelTTrackerPush(r_ptr, p_ptr, itsBunch->getLocalNum(), dt_ptr,
-                                         itsBunch->getdT(), Physics::c, true, stream1);
-        //read R from device
-        dksbase.readDataAsync<Vector_t>(r_ptr, &itsBunch->R[0], itsBunch->getLocalNum(), stream1);
-
-        //write LastSection to device
-        dksbase.writeDataAsync<long>(lastSec_ptr, &itsBunch->LastSection[0],
-                                     itsBunch->getLocalNum(), stream2);
-        //calc push
-        dksbase.callParallelTTrackerPushTransform(x_ptr, p_ptr, lastSec_ptr, orient_ptr,
-                                                  itsBunch->getLocalNum(),
-                                                  itsOpalBeamline_m.sections_m.size(),
-                                                  dt_ptr, itsBunch->getdT(), Physics::c, 
-                                                  false, stream2);
-        //read R from device
-        dksbase.readDataAsync<Vector_t>(x_ptr, &itsBunch->X[0], itsBunch->getLocalNum(), stream2);
-
-        //sync and wait till all tasks and reads are complete
-        dksbase.syncDevice();
-#endif
-    } else {
-        itsBunch->switchToUnitlessPositions(true);
-        // start normal particle loop part 2 for simulation without boundary geometry.
-        for(unsigned int i = 0; i < itsBunch->getLocalNum(); ++i) {
-            /** \f[ \vec{x}_{n+1} = \vec{x}_{n+1/2} + \frac{1}{2}\vec{v}_{n+1/2}\quad (= \vec{x}_{n+1/2} + \frac{\Delta t}{2} \frac{\vec{\beta}_{n+1/2}\gamma_{n+1/2}}{\gamma_{n+1/2}}) \f]
-             * \code
-             * R[i] += 0.5 * P[i] * recpgamma;
-             * \endcode
-             */
-            pusher.push(itsBunch->R[i], itsBunch->P[i], itsBunch->dt[i]);
-            //and scale back to dimensions
-
-            // update local coordinate system
-            pusher.push (
-                itsBunch->X[i],
-                TransformTo(
-                    itsBunch->P[i],
-                    itsOpalBeamline_m.getOrientation(itsBunch->LastSection[i])),
-                itsBunch->getdT());
-            //reset time step if particle was emitted in the first half-step
-            //the particle is now in sync with the simulation timestep
+    IpplTimings::startTimer(timeIntegrationTimer1_m);
 
-        }
-        itsBunch->switchOffUnitlessPositions(true);
-    }
-    IpplTimings::stopTimer(timeIntegrationTimer2Push_m);
+    pushParticles(pusher);
 
-    //std::fill(itsBunch->dt.begin(), itsBunch->dt.end(), itsBunch->getdT());
-    for(unsigned int i = 0; i < itsBunch->getLocalNum(); ++i) {
-        itsBunch->dt[i] = itsBunch->getdT();
-    }
-    IpplTimings::stopTimer(timeIntegrationTimer2_m);
+    IpplTimings::stopTimer(timeIntegrationTimer1_m);
 }
 
-void ParallelTTracker::timeIntegration2_bgf(BorisPusher & pusher) {
 
-    if(!bgf_m) return;
+void ParallelTTracker::timeIntegration2(BorisPusher & pusher) {
     /*
-      After kick, we do collision test before integration in second half step
-      with new momentum, if hit, then move collision particles to the position
-      where collision occurs.
+      transport and emit particles
+      that passed the cathode in the first
+      half-step or that would pass it in the
+      second half-step.
+
+      to make IPPL and the field solver happy
+      make sure that at least 10 particles are emitted
+
+      also remember that node 0 has
+      all the particles to be emitted
+
+      this has to be done *after* the calculation of the
+      space charges! thereby we neglect space charge effects
+      in the very first step of a new-born particle.
+
     */
+
     IpplTimings::startTimer(timeIntegrationTimer2_m);
+    kickParticles(pusher);
 
-    // push the reference particle by a half step
-    double recpgamma = 1.0 / sqrt(1.0 + dot(RefPartP_suv_m, RefPartP_suv_m));
-    RefPartR_zxy_m += RefPartP_zxy_m * recpgamma / 2. * scaleFactor_m;
-    kickParticles(pusher, 0);
-    handleBends(); 
-    
-    const Vector_t outr = bgf_m->getmaxcoords() + bgf_m->gethr();
-    double dtime = 0.5 * itsBunch->getdT();
-
-    for(unsigned int i = 0; i < itsBunch->getLocalNum(); ++i) {
-        bool particleHitBoundary = false;
-        Vector_t intecoords = outr;
-        int triId = 0;
-
-        /*
-          test all particles except those already have collided the boundary in the first half step.
-          particles which already have collided the boundary in the first half step will stay at 
-          the positions that they collide on the boundaries.
-         */
-        if(itsBunch->TriID[i] == 0) {
-            particleHitBoundary =  bgf_m->PartInside(
-                itsBunch->R[i],
-                itsBunch->P[i],
-                dtime,
-                itsBunch->PType[i],
-                itsBunch->Q[i],
-                intecoords,
-                triId) == 0;
-            if(particleHitBoundary) {
-                itsBunch->R[i] = intecoords / Vector_t (Physics::c * itsBunch->dt[i]);
-                itsBunch->TriID[i] = triId;
-            } else {
-                //if no collision do normal push in the second half-step
-                itsBunch->R[i] /= Vector_t(Physics::c * itsBunch->dt[i]);
-                pusher.push(itsBunch->R[i], itsBunch->P[i], itsBunch->dt[i]);
-            }
-            itsBunch->X[i] /= Vector_t(Physics::c * itsBunch->dt[i]);
-            pusher.push(
-                itsBunch->X[i],
-                TransformTo(
-                    itsBunch->P[i],
-                    itsOpalBeamline_m.getOrientation(itsBunch->LastSection[i])),
-                itsBunch->getdT());
-            itsBunch->R[i] *= Vector_t(Physics::c * itsBunch->dt[i]);
-            itsBunch->X[i] *= Vector_t(Physics::c * itsBunch->dt[i]);
-        }
-    }
+    //switchElements();
+    pushParticles(pusher);
 
-    //fill(itsBunch->dt.begin(), itsBunch->dt.end(), itsBunch->getdT());
-    for(unsigned int i = 0; i < itsBunch->getLocalNum(); ++i) {
-        itsBunch->dt[i] = itsBunch->getdT();
+    const unsigned int localNum = itsBunch_m->getLocalNum();
+    for (unsigned int i = 0; i < localNum; ++ i) {
+        itsBunch_m->dt[i] = itsBunch_m->getdT();
     }
-
     IpplTimings::stopTimer(timeIntegrationTimer2_m);
 }
 
 void ParallelTTracker::selectDT() {
 
-    if(itsBunch->GetIfBeamEmitting()) {
-        double dt = itsBunch->GetEmissionDeltaT();
-        itsBunch->setdT(dt);
-        scaleFactor_m = dt * Physics::c;
-        vscaleFactor_m = Vector_t(scaleFactor_m);
+    if (itsBunch_m->getIfBeamEmitting()) {
+        double dt = itsBunch_m->getEmissionDeltaT();
+        itsBunch_m->setdT(dt);
     } else {
         double dt = dtCurrentTrack_m;
-        itsBunch->setdT(dt);
-        scaleFactor_m = dt * Physics::c;
-        vscaleFactor_m = Vector_t(scaleFactor_m);
+        itsBunch_m->setdT(dt);
     }
 }
 
 void ParallelTTracker::changeDT() {
     selectDT();
-    for(unsigned int i = 0; i < itsBunch->getLocalNum(); ++i) {
-        itsBunch->dt[i] = itsBunch->getdT();
+    const unsigned int localNum = itsBunch_m->getLocalNum();
+    for (unsigned int i = 0; i < localNum; ++ i) {
+        itsBunch_m->dt[i] = itsBunch_m->getdT();
     }
 }
 
 void ParallelTTracker::emitParticles(long long step) {
+    if (!itsBunch_m->weHaveEnergyBins()) return;
+
+    if (itsBunch_m->getIfBeamEmitting()) {
+        CoordinateSystemTrafo gunToLab = itsOpalBeamline_m.getCSTrafoLab2Local().inverted();
+        CoordinateSystemTrafo refToGun = itsOpalBeamline_m.getCSTrafoLab2Local() * referenceToLabCSTrafo_m;
 
-    if(!itsBunch->WeHaveEnergyBins()) return;
+        transformBunch(refToGun);
 
-    if(itsBunch->GetIfBeamEmitting()) {
-        int ne = 0;
-        itsBunch->switchToUnitlessPositions(true);
+        itsBunch_m->switchToUnitlessPositions(true);
 
         Vector_t externalE = Vector_t(0.0);
         Vector_t externalB = Vector_t(0.0);
-        itsOpalBeamline_m.getFieldAt(Vector_t(0.0),
-                                     Vector_t(0.0),
-                                     itsBunch->getT() + 0.5 * itsBunch->getdT(),
+        itsOpalBeamline_m.getFieldAt(gunToLab.transformTo(Vector_t(0.0)),
+                                     gunToLab.rotateTo(Vector_t(0.0)),
+                                     itsBunch_m->getT() + 0.5 * itsBunch_m->getdT(),
                                      externalE,
                                      externalB);
-        ne += itsBunch->EmitParticles(externalE(2));
+        itsBunch_m->emitParticles(externalE(2));
 
-        if(Options::schottkyCorrection)
-            applySchottkyCorrection(*itsBunch, ne, itsBunch->getT(), rescale_coeff_m);
+        itsBunch_m->updateNumTotal();
+        numParticlesInSimulation_m = itsBunch_m->getTotalNum();
+        itsBunch_m->switchOffUnitlessPositions(true);
 
-        reduce(ne, ne, OpAddAssign());
-        numParticlesInSimulation_m += ne;
-        itsBunch->switchOffUnitlessPositions(true);
+        transformBunch(refToGun.inverted());
+    }
 
-        if (numParticlesInSimulation_m > minBinEmitted_m)
-            itsBunch->boundp();
+    if (step > minStepforReBin_m) {
+        itsBunch_m->Rebin();
+        itsBunch_m->resetInterpolationCache(true);
     }
+}
 
-    if(step > minStepforReBin_m) {
-        itsBunch->Rebin();
-        itsBunch->resetInterpolationCache(true);
-	//	if (itsBunch->getTotalNum() < specifiedNPart_m) {
-	//  WARNMSG("Rebinning, but less particles emitted than specifyed. Either increase MINSTEPFORREBIN or you have particle losses!"<< endl);
-	//}
 
-    }
+void ParallelTTracker::computeSpaceChargeFields(unsigned long long step) {
+    if (numParticlesInSimulation_m <= minBinEmitted_m) return;
 
-}
+    if (!itsBunch_m->hasFieldSolver()) return;
 
+    itsBunch_m->calcBeamParameters();
+    Quaternion alignment = getQuaternion(itsBunch_m->get_pmean(), Vector_t(0, 0, 1));
+    CoordinateSystemTrafo beamToReferenceCSTrafo(Vector_t(0, 0, pathLength_m), alignment.conjugate());
+    CoordinateSystemTrafo referenceToBeamCSTrafo = beamToReferenceCSTrafo.inverted();
 
-void ParallelTTracker::computeSpaceChargeFields() {
-    if(numParticlesInSimulation_m <= minBinEmitted_m) return;
+    const unsigned int localNum1 = itsBunch_m->getLocalNum();
+    for (unsigned int i = 0; i < localNum1; ++ i) {
+        itsBunch_m->R[i] = referenceToBeamCSTrafo.transformTo(itsBunch_m->R[i]);
+    }
+
+    itsBunch_m->boundp();
 
-    // itsBunch->switchToUnitlessPositions(true);
-    // // FIXME! why do we have to do compute self fields with unitless positions?
-    // itsBunch->boundp();
+    if (step % repartFreq_m + 1 == repartFreq_m) {
+        doBinaryRepartition();
+    }
 
-    if(itsBunch->WeHaveEnergyBins()) {
-        itsBunch->calcGammas();
-        itsBunch->resetInterpolationCache();
-        ParticleAttrib<double> Q_back = itsBunch->Q;
-        for(int binNumber = 0; binNumber < itsBunch->GetLastEmittedEnergyBin() &&
-            binNumber < itsBunch->GetNumberOfEnergyBins(); ++binNumber) {
+    if (itsBunch_m->weHaveEnergyBins()) {
+        itsBunch_m->calcGammas();
+        itsBunch_m->resetInterpolationCache();
+        ParticleAttrib<double> Q_back = itsBunch_m->Q;
+        for (int binNumber = 0; binNumber < itsBunch_m->getLastEmittedEnergyBin() &&
+                 binNumber < itsBunch_m->getNumberOfEnergyBins(); ++binNumber) {
 
-            itsBunch->setBinCharge(binNumber);
-            itsBunch->setGlobalMeanR(itsBunch->get_centroid());
-            itsBunch->computeSelfFields(binNumber);
-            itsBunch->Q = Q_back;
+            itsBunch_m->setBinCharge(binNumber);
+            itsBunch_m->setGlobalMeanR(itsBunch_m->get_centroid());
+            itsBunch_m->computeSelfFields(binNumber);
+            itsBunch_m->Q = Q_back;
 
         }
 
     } else {
-        itsBunch->setGlobalMeanR(itsBunch->get_centroid());
-        itsBunch->computeSelfFields();
+        itsBunch_m->setGlobalMeanR(itsBunch_m->get_centroid());
+        itsBunch_m->computeSelfFields();
     }
 
-    // itsBunch->switchOffUnitlessPositions(true);
-    // // FIXME! (see above)
-    // itsBunch->boundp();
+    const unsigned int localNum2 = itsBunch_m->getLocalNum();
+    for (unsigned int i = 0; i < localNum2; ++ i) {
+        itsBunch_m->R[i] = beamToReferenceCSTrafo.transformTo(itsBunch_m->R[i]);
+        itsBunch_m->Ef[i] = beamToReferenceCSTrafo.rotateTo(itsBunch_m->Ef[i]);
+        itsBunch_m->Bf[i] = beamToReferenceCSTrafo.rotateTo(itsBunch_m->Bf[i]);
+    }
 }
 
 
-void ParallelTTracker::computeExternalFields() {
-    IpplTimings::startTimer(timeFieldEvaluation_m);
+void ParallelTTracker::computeExternalFields(OrbitThreader &oth) {
+    IpplTimings::startTimer(fieldEvaluationTimer_m);
     Inform msg("ParallelTTracker ", *gmsg);
+    const unsigned int localNum = itsBunch_m->getLocalNum();
 
-    unsigned long hasWake = 0;
-    int hasSurfacePhysics = 0;
-    long wfSection = 0;
-    std::set<long> sphysSections;
+    bool hasWake = false;
+    WakeFunction *wfInstance;
 
-    globalEOL_m = true;
-    bool emission_in_progress = itsBunch->GetIfBeamEmitting();
-    if(numParticlesInSimulation_m == 0 && emission_in_progress)
-        globalEOL_m = false;
-
-    for(unsigned int i = 0; i < itsBunch->getLocalNum(); ++i) {
-
-        long ls = itsBunch->LastSection[i];
-        itsOpalBeamline_m.getSectionIndexAt(itsBunch->R[i], ls);
-        if(ls != itsBunch->LastSection[i]) {
-            if(!(itsOpalBeamline_m.section_is_glued_to(itsBunch->LastSection[i], ls) ||
-                 itsOpalBeamline_m.section_is_glued_to(ls, itsBunch->LastSection[i]))) {
-                itsBunch->ResetLocalCoordinateSystem(i, itsOpalBeamline_m.getOrientation(ls), itsOpalBeamline_m.getSectionStart(ls));
-            }
-            itsBunch->LastSection[i] = ls;
-        }
+    Vector_t rmin, rmax;
+    itsBunch_m->get_bounds(rmin, rmax);
+    IndexMap::value_t elements;
 
-        Vector_t externalE, externalB;
-        const unsigned long rtv = itsOpalBeamline_m.getFieldAt(i, itsBunch->R[i], ls, itsBunch->getT() + itsBunch->dt[i] / 2., externalE, externalB);
+    try {
+        elements = oth.query(pathLength_m + 0.5 * (rmax(2) + rmin(2)), rmax(2) - rmin(2));
+    } catch(IndexMap::OutOfBounds e) {
+        globalEOL_m = true;
 
-        globalEOL_m = globalEOL_m && (rtv & BEAMLINE_EOL);
+        return;
+    }
 
-        if((rtv & BEAMLINE_WAKE) && hasWake == 0) {
-            wfSection = ls;
-            hasWake = 1;
-        }
+    IndexMap::value_t::const_iterator it = elements.begin();
+    const IndexMap::value_t::const_iterator end = elements.end();
 
-        if((rtv & BEAMLINE_SURFACEPHYSICS) && hasSurfacePhysics == 0) {
-            sphysSections.insert(ls);
-        }
+    for (; it != end; ++ it) {
+        CoordinateSystemTrafo refToLocalCSTrafo = (itsOpalBeamline_m.getMisalignment((*it)) *
+                                                   (itsOpalBeamline_m.getCSTrafoLab2Local((*it)) * referenceToLabCSTrafo_m));
+        CoordinateSystemTrafo localToRefCSTrafo = refToLocalCSTrafo.inverted();
 
-        bends_m = bends_m || (rtv & BEAMLINE_BEND);
+        (*it)->setCurrentSCoordinate(pathLength_m + rmin(2));
 
-        // skip rest of the particle push if the
-        // particle is out of bounds i.e. does not see
-        // a E or B field
-        if(rtv & BEAMLINE_OOB)
-            itsBunch->Bin[i] = -1;
+        for (unsigned int i = 0; i < localNum; ++ i) {
+            if (itsBunch_m->Bin[i] < 0) continue;
 
-        itsBunch->Ef[i] += externalE;
-        itsBunch->Bf[i] += externalB;
-        // in case a particle is pushed behind the emission surface, delete the particle
-        if(itsBunch->R[i](2) < 0)
-            itsBunch->Bin[i] = -1;
+            itsBunch_m->R[i] = refToLocalCSTrafo.transformTo(itsBunch_m->R[i]);
+            itsBunch_m->P[i] = refToLocalCSTrafo.rotateTo(itsBunch_m->P[i]);
+            double &dt = itsBunch_m->dt[i];
 
-    }
+            Vector_t localE(0.0), localB(0.0);
 
-    //if any new surfacephysics sections enabled, check if there are other surface physics 
-    //elements fallowing directy after it, then handle these elements as well, to process particles
-    //moving from one degrader to another   
-    std::set<long> attachedSphysSections;
-    for (long it: sphysSections) {
-       
-        //get the section it + 1 if it has surface physics
-        long newit = it + 1;
-        while ( itsOpalBeamline_m.getSection(newit).hasSurfacePhysics() ) {
-
-            //check if two sections following one another dont share the same surface physics handler
-            if (itsOpalBeamline_m.getSection(newit).getSurfacePhysicsHandler() != 
-                itsOpalBeamline_m.getSection(newit - 1).getSurfacePhysicsHandler())
-            {
-                attachedSphysSections.insert(newit);
+            if ((*it)->apply(i, itsBunch_m->getT() + 0.5 * dt, localE, localB)) {
+                itsBunch_m->R[i] = localToRefCSTrafo.transformTo(itsBunch_m->R[i]);
+                itsBunch_m->P[i] = localToRefCSTrafo.rotateTo(itsBunch_m->P[i]);
+                itsBunch_m->Bin[i] = -1;
+                continue;
             }
-            newit++;
-        }
 
-    }
-    //merge two sets
-    sphysSections.insert(attachedSphysSections.begin(), attachedSphysSections.end());
-
-    IpplTimings::stopTimer(timeFieldEvaluation_m);
-
-    reduce(hasWake, hasWake, OpAddAssign());
-    reduce(bends_m, bends_m, OpAddAssign());
-
-    hasSurfacePhysics = sphysSections.size();
-    reduce(hasSurfacePhysics, hasSurfacePhysics, OpMaxAssign());
-
-    if(hasWake > 0) {
-        IpplTimings::startTimer(WakeFieldTimer_m);
-        reduce(wfSection, wfSection, OpMaxAssign());
-        WakeFunction *wf = itsOpalBeamline_m.getWakeFunction(wfSection);
-        /*--------- Added by Xiaoying Pang 04/22/2014 ---------------
-         * If the CSR is turned on for a dipole, save its pointer to the CSRWakeFunction
-         * and reuse it in the following drift.*/
-        // xpang: start
-        std::shared_ptr<const ElementBase> element = itsOpalBeamline_m.getWakeFunctionOwner(wfSection);
-        if(dynamic_cast<CSRWakeFunction*>(wf))
-            {
-                if(dynamic_cast<const RBend*>(element.get()) || dynamic_cast<const SBend*>(element.get()))
-                    wakeFunction_m = wf;
-                if(dynamic_cast<const Drift*>(element.get()))
-                    wf = wakeFunction_m;
-            }
-        // xpang: end
-        if(!wakeStatus_m) {
-            msg << level2 << "============== START WAKE CALCULATION =============" << endl;
-            std::shared_ptr<const ElementBase> element = itsOpalBeamline_m.getWakeFunctionOwner(wfSection);
-            wf->initialize(element.get());
-            wakeStatus_m = true;
-        }
-        if(wf == NULL) {
-            INFOMSG("no wakefunction attached" << endl);
-        } else {
-            wf->apply(*itsBunch);
+            itsBunch_m->R[i] = localToRefCSTrafo.transformTo(itsBunch_m->R[i]);
+            itsBunch_m->P[i] = localToRefCSTrafo.rotateTo(itsBunch_m->P[i]);
+            itsBunch_m->Ef[i] += localToRefCSTrafo.rotateTo(localE);
+            itsBunch_m->Bf[i] += localToRefCSTrafo.rotateTo(localB);
         }
-        IpplTimings::stopTimer(WakeFieldTimer_m);
-
-    } else if(wakeStatus_m) {
-        msg << level2 << "=============== END WAKE CALCULATION ==============" << endl;
-        wakeStatus_m = false;
-    }
 
-    if(hasSurfacePhysics > 0) {    // in a section we have an element with surface physics
-
-        // this is a workaround fighting the zero partilce problem on a core
-        // noy yet understood 
-        // with setMimumNumberOfParticlesPerCore(2) degrader simulations for the PSI gantry are running
-        itsBunch->setMimumNumberOfParticlesPerCore(0);
-
-        std::set<long> old_sphysSections;
-        std::vector<long> leftBehindSections, newSections;
-        for (auto it: sphys_m) {
-            old_sphysSections.insert(it.first);
-        }       
-
-        std::vector<long> sectionsWithSurfacePhysics(Ippl::getNodes() * hasSurfacePhysics, -1);
-        unsigned int insPosition = Ippl::myNode() * hasSurfacePhysics;
-        for (auto it :sphysSections)
-            sectionsWithSurfacePhysics[insPosition ++] = it;
-
-        MPI_Allgather(MPI_IN_PLACE, 0, MPI_DATATYPE_NULL,
-                      &sectionsWithSurfacePhysics[0], hasSurfacePhysics, MPI_LONG,
-                      Ippl::getComm());
-        sphysSections.insert(sectionsWithSurfacePhysics.begin(),
-                             sectionsWithSurfacePhysics.end());
-        auto dummySection = sphysSections.find(-1);
-        if (dummySection != sphysSections.end()) {
-            sphysSections.erase(dummySection);
-        }
+        if ((*it)->hasWake() && !hasWake) {
+            IpplTimings::stopTimer(fieldEvaluationTimer_m);
+            IpplTimings::startTimer(WakeFieldTimer_m);
 
-        newSections.resize(leftBehindSections.size());
-        {
-            leftBehindSections.resize(std::max(old_sphysSections.size(),
-                                               sphysSections.size()));
-            auto last = std::set_difference(old_sphysSections.begin(), old_sphysSections.end(),
-                                            sphysSections.begin(), sphysSections.end(),
-                                            leftBehindSections.begin());
-            leftBehindSections.resize(last - leftBehindSections.begin());
-        }
+            hasWake = true;
 
-        for (long it: leftBehindSections) {
-            if (!sphys_m[it]->stillActive()) {
-                sphys_m[it] = NULL;
-                sphys_m.erase(it);
+            if ((*it)->getWake()->getType() == "CSRWakeFunction" ||
+                (*it)->getWake()->getType() == "CSRIGFWakeFunction") {
+                if ((*it)->getType() == ElementBase::RBEND ||
+                    (*it)->getType() == ElementBase::SBEND) {
+                    wfInstance = (*it)->getWake();
+                    wakeFunction_m = wfInstance;
+                } else {
+                    wfInstance = wakeFunction_m;
+                }
+            } else {
+                wfInstance = (*it)->getWake();
             }
-        }
-
-        {
-            newSections.resize(std::max(old_sphysSections.size(),
-                                        sphysSections.size()));
-            auto last = std::set_difference(sphysSections.begin(), sphysSections.end(),
-                                            old_sphysSections.begin(), old_sphysSections.end(),
-                                            newSections.begin());
-            newSections.resize(last - newSections.begin());
-        }
-
-        for (long it: newSections) {
-            sphys_m.insert(std::make_pair(it, itsOpalBeamline_m.getSurfacePhysicsHandler(it)));
-        }
 
-        if(!surfaceStatus_m) {
-            msg << level2 << "============== START SURFACE PHYSICS CALCULATION =============" << endl;
-            surfaceStatus_m = true;
-        }
-      
-    } 
-
-    if (surfaceStatus_m) {
-        do {
-            ///all particles in material if max per node is 2 and other degraders have 0 particles
-            //check if more than one degrader has particles
-            long degraderWithParticles;
-            int degradersWithParticlesCount = 0;
-            for (auto it: sphys_m) {
-                it.second->AllParticlesIn(false);
-                if (it.second->getParticlesInMat() > 0) {
-                    degraderWithParticles = it.first;
-                    degradersWithParticlesCount++;
-                }
+            if (!wfInstance) {
+                throw OpalException("ParallelTTracker::computeExternalFields",
+                                    "empty wake function");
             }
-        
-            //if max particles per node is 2, and only one degrader has particles set 
-            //AllParticlesIn for this degrader to true
-            int maxPerNode = itsBunch->getLocalNum();
-            reduce(maxPerNode, maxPerNode, OpMaxAssign());
-            bool allParticlesInMat = ( (unsigned)maxPerNode <= itsBunch->getMinimumNumberOfParticlesPerCore() && degradersWithParticlesCount == 1 );
-
-            if (allParticlesInMat) {
-                sphys_m[degraderWithParticles]->AllParticlesIn(true);
-                msg << "All particles in degrader" << endl;
+
+            if (!wakeStatus_m) {
+                msg << level2 << "============== START WAKE CALCULATION =============" << endl;
+                wfInstance->initialize((*it).get());
+                wakeStatus_m = true;
             }
 
-            unsigned redifusedParticles = 0;
-            for (auto it: sphys_m) {
-                it.second->apply(*itsBunch, totalParticlesInSimulation_m);
-                it.second->print(msg);
+            if (!itsBunch_m->hasFieldSolver()) itsBunch_m->calcBeamParameters();
 
-                redifusedParticles += it.second->getRedifused();
-                //if all particles where in material update time to time in degrader
-                if (allParticlesInMat)
-                    itsBunch->setT(it.second->getTime() - itsBunch->getdT());
-            }
+            Quaternion alignment = getQuaternion(itsBunch_m->get_pmean(), Vector_t(0, 0, 1));
+            CoordinateSystemTrafo referenceToBeamCSTrafo(Vector_t(0.0), alignment);
+            CoordinateSystemTrafo beamToReferenceCSTrafo = referenceToBeamCSTrafo.inverted();
 
-            //perform boundp only if there are particles in the bunch, or there are particles
-            //comming out of the degrader
-            if ((unsigned)maxPerNode > itsBunch->getMinimumNumberOfParticlesPerCore() || 
-                redifusedParticles > 0)
-            {
-                itsBunch->boundp();    
+            for (unsigned int i = 0; i < localNum; ++ i) {
+                itsBunch_m->R[i] = referenceToBeamCSTrafo.transformTo(itsBunch_m->R[i]);
+                itsBunch_m->Ef[i] = referenceToBeamCSTrafo.rotateTo(itsBunch_m->Ef[i]);
             }
-             
-            //if bunch has no particles update time to time in degrader
-            if (itsBunch->getTotalNum() == 0)
-                itsBunch->setT(itsBunch->getT() + itsBunch->getdT());
-
-        } while (itsBunch->getTotalNum() == 0);
-        
-
-        if (sphys_m.size() == 0) {
-            msg << level2 << "============== END SURFACE PHYSICS CALCULATION =============" << endl;
-            surfaceStatus_m = false;
-            itsBunch->setMimumNumberOfParticlesPerCore(0);
-        }
-    }
 
-    size_t ne = 0;    
-    bool globPartOutOfBounds = (min(itsBunch->Bin) < 0) && (itsBunch->getTotalNum() > itsBunch->getMinimumNumberOfParticlesPerCore());
-    if(globPartOutOfBounds) {
-        ne = itsBunch->boundp_destroyT();
-        numParticlesInSimulation_m  = itsBunch->getTotalNum();
-    }
+            wfInstance->apply(*itsBunch_m);
 
-    if(numParticlesInSimulation_m > minBinEmitted_m || itsBunch->getTotalNum() > minBinEmitted_m) {
-        itsBunch->update();
-        numParticlesInSimulation_m = itsBunch->getTotalNum();
-    }
-    
-    //remove surface physics elements from start of the list till hit one which is still active
-    if (surfaceStatus_m) {
-        for (auto it: sphys_m) {
-            if (it.second->stillActive()) {
-                break;
-            } else {
-                //check if degrader is empty and bunch has moved past it (needed to free GPU memory)
-                if ( !it.second->stillAlive(*itsBunch) )
-                    msg << "Surface physiscs at element " << it.second->getName() << " has become inactive" << endl;
-               
-                it.second = NULL;
-                sphys_m.erase(it.first);                
+            for (unsigned int i = 0; i < localNum; ++ i) {
+                itsBunch_m->R[i] = beamToReferenceCSTrafo.transformTo(itsBunch_m->R[i]);
+                itsBunch_m->Ef[i] = beamToReferenceCSTrafo.rotateTo(itsBunch_m->Ef[i]);
             }
+
+            IpplTimings::stopTimer(WakeFieldTimer_m);
+            IpplTimings::startTimer(fieldEvaluationTimer_m);
         }
     }
 
-    if(ne > 0 || surfaceStatus_m) {
-        msg << level1 << "* Deleted " << ne << " particles, "
-          << "remaining " << itsBunch->getTotalNum() << " particles" << endl;
-        totalParticlesInSimulation_m -= ne;
-    }  
+    IpplTimings::stopTimer(fieldEvaluationTimer_m);
 
-}
+    if (wakeStatus_m && !hasWake) {
+        msg << level2 << "=============== END WAKE CALCULATION ==============" << endl;
+        wakeStatus_m = false;
+    }
 
-void ParallelTTracker::handleBends() {
-    if(bends_m == 0) {
-        if(itsBunch->getTotalNum() > 0) {
-            // none of the particles is in a bending element
-            updateReferenceParticle();
+    size_t ne = 0;
+    bool globPartOutOfBounds = (min(itsBunch_m->Bin) < 0) && (itsBunch_m->getTotalNum() > 1);
+    if (globPartOutOfBounds) {
+        if (itsBunch_m->hasFieldSolver()) {
+            ne = itsBunch_m->boundp_destroyT();
+        } else {
+            ne = itsBunch_m->destroyT();
         }
-    } else {
-        /*
-         at least one of the elements bends the beam; until all
-         particles have left the bending elements we track the
-         reference particle as if it were a regular particle; from
-         the moment when the reference particle has reached the
-         bending field until it leaves it again we rotate the bunch
-         about the position of the reference particle such that the
-         momentum of the reference particle points in z direction;
-         First update the momentum of the reference particle in zxy
-         coordinate system, then update its position
-         */
-
-        updateSpaceOrientation(false);
-        double recpgamma = 1. / sqrt(1.0 + dot(RefPartP_suv_m, RefPartP_suv_m));
-
-        RefPartP_zxy_m = dot(space_orientation_m, RefPartP_suv_m);
-        RefPartR_zxy_m += RefPartP_zxy_m * recpgamma * scaleFactor_m / 2.;
-
-        RefPartP_suv_m = Vector_t(0.0, 0.0, sqrt(dot(RefPartP_suv_m, RefPartP_suv_m)));
-        RefPartR_suv_m += RefPartP_suv_m * recpgamma / 2. * Physics::c * itsBunch->getdT();
+        numParticlesInSimulation_m  = itsBunch_m->getTotalNum();
+        deletedParticles_m = true;
     }
 
-    itsBunch->RefPart_R = RefPartR_zxy_m;
-    itsBunch->RefPart_P = RefPartP_zxy_m;
-
-}
-
-void ParallelTTracker::switchElements(double scaleMargin) {
-    // calculate the dimensions of the bunch and add a small margin to them; then decide which elements have to be triggered
-    // when an element is triggered memory is allocated and the field map is read in
-    Vector_t rmin(0.0), rmax(0.0);
-    itsBunch->get_bounds(rmin, rmax);
-
-    //FIXME: necessary
-    RefPartP_suv_m = itsBunch->get_pmean();
-    double recpgamma = 1. / sqrt(1.0 + dot(RefPartP_suv_m, RefPartP_suv_m));
+    size_t totalNum = itsBunch_m->getTotalNum();
+    if (numParticlesInSimulation_m > minBinEmitted_m || totalNum > minBinEmitted_m) {
+        numParticlesInSimulation_m = totalNum;
+    }
 
-    // trigger the elements
-    double margin = scaleMargin * RefPartP_suv_m(2) * recpgamma * Physics::c * itsBunch->getdT();
-    margin = 0.01 > margin ? 0.01 : margin;
-    itsOpalBeamline_m.switchElements((rmin(2) - margin), (rmax(2) + margin), getEnergyMeV(RefPartP_suv_m));
+    if (ne > 0) {
+        msg << level1 << "* Deleted " << ne << " particles, "
+            << "remaining " << itsBunch_m->getTotalNum() << " particles" << endl;
+    }
 }
 
 void ParallelTTracker::doBinaryRepartition() {
     size_t particles_or_bins = std::max(minBinEmitted_m, size_t(1000));
-    if(itsBunch->hasFieldSolver() && numParticlesInSimulation_m > particles_or_bins) {
+    if (itsBunch_m->hasFieldSolver() && numParticlesInSimulation_m > particles_or_bins) {
 
         INFOMSG("*****************************************************************" << endl);
         INFOMSG("do repartition because of repartFreq_m" << endl);
         INFOMSG("*****************************************************************" << endl);
         IpplTimings::startTimer(BinRepartTimer_m);
-        itsBunch->do_binaryRepart();
+        itsBunch_m->do_binaryRepart();
         Ippl::Comm->barrier();
         IpplTimings::stopTimer(BinRepartTimer_m);
         INFOMSG("*****************************************************************" << endl);
@@ -2070,88 +722,46 @@ void ParallelTTracker::dumpStats(long long step, bool psDump, bool statDump) {
     OPALTimer::Timer myt2;
     Inform msg("ParallelTTracker ", *gmsg);
 
-    if ((itsBunch->getGlobalTrackStep() + 1) % 1000 == 0) {
+    if (itsBunch_m->getGlobalTrackStep() % 1000 + 1 == 1000) {
         msg << level1;
-    } else if ((itsBunch->getGlobalTrackStep() + 1) % 100 == 0) {
+    } else if (itsBunch_m->getGlobalTrackStep() % 100 + 1 == 100) {
         msg << level2;
     } else {
         msg << level3;
     }
 
-    if(numParticlesInSimulation_m == 0) {
+    if (numParticlesInSimulation_m == 0) {
         msg << myt2.time() << " "
-            << "Step " << setw(6) <<  itsBunch->getGlobalTrackStep() << "; "
+            << "Step " << setw(6) <<  itsBunch_m->getGlobalTrackStep() << "; "
             << "   -- no emission yet --     "
-            << "t= "   << scientific << setprecision(3) << setw(10) << itsBunch->getT() << " [s]"
+            << "t= "   << Util::getTimeString(itsBunch_m->getT())
             << endl;
         return;
     }
 
-    double sposRef = itsBunch->get_sPos();
-    double sposPrint = sposRef;
-    std::string sposUnit(" [m] ");
-    double meanEnergy = itsBunch->get_meanEnergy();
-    std::string meanEnergyUnit(" [MeV] ");
-
-    if (sposRef < 1.0) {
-        sposPrint = 1000.0*sposRef;
-        sposUnit = std::string(" [mm] ");
-    }
-
-    if (meanEnergy < 1.0) {
-        meanEnergy *= 1000.0;
-        meanEnergyUnit = std::string(" [keV] ");
-    }
-
+    itsBunch_m->calcEMean();
     size_t totalParticles_f = numParticlesInSimulation_m;
-    if(totalParticles_f <= minBinEmitted_m) {
+    if (totalParticles_f <= minBinEmitted_m) {
         msg << myt2.time() << " "
-            << "Step " << setw(6) << itsBunch->getGlobalTrackStep() << "; "
+            << "Step " << setw(6) << itsBunch_m->getGlobalTrackStep() << "; "
             << "only " << setw(4) << totalParticles_f << " particles emitted; "
-            << "t= "   << scientific << setprecision(3) << setw(10) << itsBunch->getT() << " [s] "
-            << "E="    << fixed      << setprecision(3) << setw(9) << meanEnergy << meanEnergyUnit
+            << "t= "   << Util::getTimeString(itsBunch_m->getT()) << ", "
+            << "E="    << Util::getEnergyString(itsBunch_m->get_meanKineticEnergy()) << ", "
             << endl;
-    } else if(std::isnan(sposRef) || std::isinf(sposRef)) {      
+    } else if (std::isnan(pathLength_m) || std::isinf(pathLength_m)) {
         throw OpalException("ParallelTTracker::dumpStats()",
                             "there seems to be something wrong with the position of the bunch!");
     } else {
 
         msg << myt2.time() << " "
-            << "Step " << setw(6) <<  itsBunch->getGlobalTrackStep() << " "
-            << "at " << fixed      << setprecision(3) << setw(8) << sposPrint << sposUnit
-            << "t= " << scientific << setprecision(3) << setw(10) << itsBunch->getT() << " [s] "
-            << "E="  << fixed      << setprecision(3) << setw(9) << meanEnergy << meanEnergyUnit
+            << "Step " << setw(6)  <<  itsBunch_m->getGlobalTrackStep() << " "
+            << "at "   << Util::getLengthString(pathLength_m) << ", "
+            << "t= "   << Util::getTimeString(itsBunch_m->getT()) << ", "
+            << "E="    << Util::getEnergyString(itsBunch_m->get_meanKineticEnergy())
             << endl;
 
-        writePhaseSpace(step, sposRef, psDump, statDump);
-    }
-
-    if(bgf_m) {
-        reduce(SeyNum_m, SeyNum_m, OpAddAssign());
-        reduce(Nimpact_m, Nimpact_m, OpAddAssign());
-
-        itsDataSink_m->writePartlossZASCII(*itsBunch, *bgf_m, std::string("data/Partloss-"));
-
-        long long ustep = step;
-        itsDataSink_m->writeImpactStatistics(
-            *itsBunch, ustep, Nimpact_m, SeyNum_m, numberOfFieldEmittedParticles_m, nEmissionMode_m, std::string("data/PartStatistics"));
-
-        if(((Options::surfDumpFreq) > 0) && ((step % Options::surfDumpFreq) == 0)) {
-            itsDataSink_m->writeSurfaceInteraction(*itsBunch, ustep, *bgf_m, std::string("SurfaceInteraction"));
-        }
-
-        // If we are dealing with field emission and secondary emission, set upper
-        // limit of particle number in simulation to prevent memory overflow.
-        if(numParticlesInSimulation_m > maxNparts_m)
-            localTrackSteps_m.front() = step;
-
-        // ada reset Nimpact_m, does not make sense to integrate this we obtain a rediculus large number !!
-        Nimpact_m = 0;
+        writePhaseSpace(step, psDump, statDump);
     }
-
-    if(sposRef > zStop_m.front())
-        localTrackSteps_m.front() = step;
-
 }
 
 
@@ -2160,28 +770,26 @@ void ParallelTTracker::setOptionalVariables() {
 
     minBinEmitted_m  = 10;
     RealVariable *ar = dynamic_cast<RealVariable *>(OpalData::getInstance()->find("MINBINEMITTED"));
-    if(ar)
+    if (ar)
         minBinEmitted_m = static_cast<size_t>(ar->getReal());
     msg << level2 << "MINBINEMITTED " << minBinEmitted_m << endl;
 
     minStepforReBin_m  = 200;
     RealVariable *br = dynamic_cast<RealVariable *>(OpalData::getInstance()->find("MINSTEPFORREBIN"));
-    if(br)
+    if (br)
         minStepforReBin_m = static_cast<int>(br->getReal());
     msg << level2 << "MINSTEPFORREBIN " << minStepforReBin_m << endl;
 
-    surfaceEmissionStop_m  = 1000.0;
-    RealVariable *cr = dynamic_cast<RealVariable *>(OpalData::getInstance()->find("SURFACEEMISSIONSTOP"));
-    if(cr)
-        surfaceEmissionStop_m = static_cast<double>(cr->getReal());
-    msg << level2 << "SURFACEEMISSIONSTOP after " << surfaceEmissionStop_m << " seconds" <<  endl;
-
-    repartFreq_m = 1000;
-    RealVariable *rep = dynamic_cast<RealVariable *>(OpalData::getInstance()->find("REPARTFREQ"));
-    if(rep)
-        repartFreq_m = static_cast<int>(rep->getReal());
-    msg << level2 << "REPARTFREQ " << repartFreq_m << endl;
-
+    // there is no point to do repartitioning with one node
+    if (Ippl::getNodes() == 1) {
+        repartFreq_m = numeric_limits<unsigned int>::max();
+    } else {
+        repartFreq_m = 1000;
+        RealVariable *rep = dynamic_cast<RealVariable *>(OpalData::getInstance()->find("REPARTFREQ"));
+        if (rep)
+            repartFreq_m = static_cast<int>(rep->getReal());
+        msg << level2 << "REPARTFREQ " << repartFreq_m << endl;
+    }
 }
 
 
@@ -2190,609 +798,495 @@ bool ParallelTTracker::hasEndOfLineReached() {
     return globalEOL_m;
 }
 
-void ParallelTTracker::setupSUV(bool updateReference) {
-
-    if(mpacflg_m) return;
-
-    for(unsigned int i = 0; i < itsBunch->getLocalNum(); ++i) {
-        long &l = itsBunch->LastSection[i];
-        l = -1;
-        itsOpalBeamline_m.getSectionIndexAt(itsBunch->R[i], l);
-        itsBunch->ResetLocalCoordinateSystem(i, itsOpalBeamline_m.getOrientation(l), itsOpalBeamline_m.getSectionStart(l));
-    }
-
-    if(!(itsBunch->WeHaveEnergyBins())) {
-        IpplTimings::startTimer(BinRepartTimer_m);
-        itsBunch->do_binaryRepart();
-        Ippl::Comm->barrier();
-        IpplTimings::stopTimer(BinRepartTimer_m);
+void ParallelTTracker::setTime() {
+    const unsigned int localNum = itsBunch_m->getLocalNum();
+    for (unsigned int i = 0; i < localNum; ++i) {
+        itsBunch_m->dt[i] = itsBunch_m->getdT();
     }
+}
 
-    // Check if there are any particles in simulation. If there are,
-    // as in a restart, use the usual function to calculate beam
-    // parameters. If not, calculate beam parameters of the initial
-    // beam distribution.
-    if(numParticlesInSimulation_m == 0) {// fixme: maybe cause nonsense output if initialized momenta=0; Q: by Chuan.
-        itsBunch->calcBeamParametersInitial();
-    } else {
-        itsBunch->calcBeamParameters();
-    }
+void ParallelTTracker::prepareEmission() {
+    Inform msg("ParallelTTracker ", *gmsg);
 
-    RefPartP_suv_m = itsBunch->get_pmean();
-    RefPartR_suv_m = itsBunch->get_rmean();
+    if (!itsBunch_m->doEmission()) return;
 
-    if (updateReference) {
-        RefPartP_zxy_m = RefPartP_suv_m;
+    emissionSteps_m = itsBunch_m->getNumberOfEmissionSteps();
+    msg << level2 << "Do emission for " << itsBunch_m->getTEmission() << " [s] using "
+        << itsBunch_m->getNumberOfEnergyBins() << " energy bins " << endl
+        << "Change dT from " <<  itsBunch_m->getdT() << " [s] to "
+        <<  itsBunch_m->getEmissionDeltaT() << " [s] during emission " << endl;;
 
-        updateSpaceOrientation(false);
-        RefPartP_suv_m = itsBunch->get_pmean();
-    }
 }
 
-void ParallelTTracker::setTime() {
+void ParallelTTracker::writePhaseSpace(const long long step, bool psDump, bool statDump) {
+    extern Inform *gmsg;
+    Inform msg("OPAL ", *gmsg);
+    Vector_t externalE, externalB;
+    Vector_t FDext[2];  // FDext = {BHead, EHead, BRef, ERef, BTail, ETail}.
 
-    //if(Options::scan && OpalData::getInstance()->hasBunchAllocated())
+    // Sample fields at (xmin, ymin, zmin), (xmax, ymax, zmax) and the centroid location. We
+    // are sampling the electric and magnetic fields at the back, front and
+    // center of the beam.
+    Vector_t rmin, rmax;
+    itsBunch_m->get_bounds(rmin, rmax);
 
+    Vector_t position = referenceToLabCSTrafo_m.transformTo(RefPartR_m);
+    Vector_t momentum = referenceToLabCSTrafo_m.rotateTo(RefPartP_m);
+    if (psDump || statDump) {
+        externalB = Vector_t(0.0);
+        externalE = Vector_t(0.0);
+        itsOpalBeamline_m.getFieldAt(position,
+                                     momentum,
+                                     itsBunch_m->getT() - 0.5 * itsBunch_m->getdT(),
+                                     externalE,
+                                     externalB);
+        FDext[0] = referenceToLabCSTrafo_m.rotateFrom(externalB);
+        FDext[1] = referenceToLabCSTrafo_m.rotateFrom(externalE * 1e-6);
+    }
 
-    /*
-     The track command set's T0 (or default 0.0)
-     so we do not need this anymore
+    if (statDump) {
+        std::vector<std::pair<std::string, unsigned int> > collimatorLosses;
+        FieldList collimators = itsOpalBeamline_m.getElementByType(ElementBase::COLLIMATOR);
+	if (collimators.size() != 0) {
+            for (FieldList::iterator it = collimators.begin(); it != collimators.end(); ++ it) {
+                Collimator* coll = static_cast<Collimator*>(it->getElement().get());
+                std::string name = coll->getName();
+                unsigned int losses = coll->getLosses();
+                collimatorLosses.push_back(std::make_pair(name, losses));
+            }
+            std::sort(collimatorLosses.begin(), collimatorLosses.end(),
+                      [](const std::pair<std::string, unsigned int>& a, const std::pair<std::string, unsigned int>& b) ->bool {
+                          return a.first < b.first;
+                      });
+            std::vector<unsigned int> bareLosses(collimatorLosses.size(),0);
+            for (size_t i = 0; i < collimatorLosses.size(); ++ i){
+                bareLosses[i] = collimatorLosses[i].second;
+            }
 
-     if(!OpalData::getInstance()->hasBunchAllocated() &&
-     !OpalData::getInstance()->inRestartRun())
-     itsBunch->setT(0.0);
-     */
+            reduce(&bareLosses[0], &bareLosses[0] + bareLosses.size(), &bareLosses[0], OpAddAssign());
 
-    if(mpacflg_m) return;
+            for (size_t i = 0; i < collimatorLosses.size(); ++ i){
+                collimatorLosses[i].second = bareLosses[i];
+            }
+	}
+        // Write statistical data.
+        itsDataSink_m->writeStatData(*itsBunch_m, FDext, collimatorLosses);
 
-    // set dt for all particles already in the simulation,
-    // i.e. when doing a restarted simulation
-    for(unsigned int i = 0; i < itsBunch->getLocalNum(); ++i) {
-        itsBunch->dt[i] = itsBunch->getdT();
+        msg << level3 << "* Wrote beam statistics." << endl;
     }
-}
-
-void ParallelTTracker::prepareEmission() {
-    Inform msg("ParallelTTracker ", *gmsg);
-
-    if(mpacflg_m || !itsBunch->doEmission()) return;
 
-    emissionSteps_m = itsBunch->GetNumberOfEmissionSteps();
-    msg << level2 << "Do emission for " << itsBunch->getTEmission() << " [s] using "
-        << itsBunch->GetNumberOfEnergyBins() << " energy bins " << endl
-        << "Change dT from " <<  itsBunch->getdT() << " [s] to "
-        <<  itsBunch->GetEmissionDeltaT() << " [s] during emission " << endl;;
-
-}
+    if (psDump && (itsBunch_m->getTotalNum() > 0)) {
+        // Write fields to .h5 file.
+        const size_t localNum = itsBunch_m->getLocalNum();
+        double distToLastStop = std::abs(pathLength_m - zStop_m.back());
+        Vector_t driftPerTimeStep = itsBunch_m->getdT() * Physics::c * RefPartP_m / Util::getGamma(RefPartP_m);
+        bool driftToCorrectPosition = distToLastStop < 0.5 * euclidian_norm(driftPerTimeStep);
+        Ppos_t stashedR;
+
+        if (driftToCorrectPosition) {
+            const double tau = distToLastStop / euclidian_norm(driftPerTimeStep) * itsBunch_m->getdT();
+            if (localNum > 0) {
+                stashedR.create(localNum);
+                stashedR = itsBunch_m->R;
+
+                for (size_t i = 0; i < localNum; ++ i) {
+                    itsBunch_m->R[i] += tau * (Physics::c * itsBunch_m->P[i] / Util::getGamma(itsBunch_m->P[i]) -
+                                               driftPerTimeStep / itsBunch_m->getdT());
+                }
+            }
 
-void ParallelTTracker::initializeBoundaryGeometry() {
+            itsBunch_m->RefPartR_m = referenceToLabCSTrafo_m.transformTo(RefPartR_m + tau * driftPerTimeStep / itsBunch_m->getdT());
+            CoordinateSystemTrafo update(tau * driftPerTimeStep / itsBunch_m->getdT(),
+                                         Quaternion());
+            itsBunch_m->toLabTrafo_m = referenceToLabCSTrafo_m * update.inverted();
 
-    Inform msg("ParallelTTracker ", *gmsg);
+            itsBunch_m->set_sPos(zStop_m.back());
 
-    // for the time being, the Boundary geomentry must be attachedto the first element
-    bgf_m = itsOpalBeamline_m.getBoundaryGeometry(0);
-    if (bgf_m) {
-        Distribution *dist = NULL;
-        Distribution *distrand = NULL;
-        std::vector<std::string> distr_str = bgf_m->getDistributionArray();
-
-        if(distr_str.size() == 0) {
-            std::string distr = bgf_m->getDistribution();
-            if(!distr.empty()) {
-                msg << "* Find boundary geometry, start at: " << bgf_m->getS()
-                    << " (m) Distribution= " << bgf_m->getDistribution() << endl;
-                dist = Distribution::find(bgf_m->getDistribution());
-                msg << "* " << *dist << endl;
-            } else {
-                throw OpalException("ParallelTTracker::execute()",
-                                    "No distribution attached to BoundaryGeometry. Please check the input file... ...");
-            }
-        } else {
-            msg << "************************************************************************************************* " << endl;
-            msg <<  "* Find boundary geometry, start at: " << bgf_m->getS()  << " (m). " << endl;
-            msg << "* Attached more than one distribution: " << endl;
-            for(std::vector<std::string>::const_iterator dit = distr_str.begin(); dit != distr_str.end(); ++ dit) {
-                Distribution *d = Distribution::find(*dit);
-                msg << "* Distribution: " << *dit << " distribution type: " << d->GetTypeofDistribution() << endl;
-                msg << "************************************************************************************************* " << endl;
-                if(d->GetTypeofDistribution() == "SURFACEEMISSION") {
-                    dist = d;
-                    msg << *dist << endl;
-                } else if(d->GetTypeofDistribution() == "SURFACERANDCREATE") {
-                    distrand = d;
-                    msg << *distrand << endl;
-                    /*
-                      here nbparts should be non zero as these particles will
-                      be the initialization of primary bunch.
-                    */
-                    size_t nbparts = distrand->GetNumberOfDarkCurrentParticles();
-                    double darkinwardmargin = distrand->GetDarkCurrentParticlesInwardMargin();
-                    double einitthreshold = distrand->GetEInitThreshold();
-                    /*
-                      make sure that the elements have already been switched
-                      on before initializing particles in position where the
-                      electric field > einitthreshold.
-                    */
-                    bgf_m->setEInitThreshold(einitthreshold);
-                    if(!mpacflg_m) {
-                        bgf_m->createPriPart(nbparts, darkinwardmargin, itsOpalBeamline_m, itsBunch);
-                        distrand->CreatePriPart(itsBunch, *bgf_m);
-                        numParticlesInSimulation_m = itsBunch->getTotalNum();
-                    } else {
-                        /*
-                          Multipacting flag set true. Generate primary particles.
-                          Activate all elements (switch on the field map of elements
-                          in multipacting) in multipacting simulation
-                        */
-
-                        itsOpalBeamline_m.switchAllElements();
-                        /*
-                          it is possible to generate initial particles according
-                          to E field, since all elements switched on before we
-                          create particles.
-                        */
-                        bgf_m->createPriPart(nbparts, darkinwardmargin, itsOpalBeamline_m, itsBunch);
-                        /*
-                          for Parallel Plate benchmark, Vw should be defined in
-                          input file and will be invoked by getVw method in
-                          createPriPart().  For other multipacting simulation
-                          no need to define the Vw in SURFACERANDCREATE in input
-                          file.
-                        */
-                        distrand->CreatePriPart(itsBunch, *bgf_m);
-                        numParticlesInSimulation_m = itsBunch->getTotalNum();
-                        itsBunch->calcBeamParameters();
-                        for(unsigned int i = 0; i < itsBunch->getLocalNum(); ++i) {
-                            long &l = itsBunch->LastSection[i];
-                            l = -1;
-                            itsOpalBeamline_m.getSectionIndexAt (itsBunch->R[i], l);
-                            itsBunch->ResetLocalCoordinateSystem (
-                                i,
-                                itsOpalBeamline_m.getOrientation(l),
-                                itsOpalBeamline_m.getSectionStart(l));
-                        }
-
-                        /*
-                          Check if there are any particles in simulation. If there are,
-                          as in a restart, use the usual function to calculate beam
-                          parameters. If not, calculate beam parameters of the initial
-                          beam distribution.
-                        */
-                        if(numParticlesInSimulation_m == 0) {
-                            itsBunch->calcBeamParametersInitial();
-                        } else {
-                            itsBunch->calcBeamParameters();
-                        }
-
-                        //updateSpaceOrientation(false);
-                        RefPartR_suv_m = RefPartR_zxy_m = itsBunch->get_rmean();
-                        RefPartP_suv_m = RefPartP_zxy_m = itsBunch->get_pmean();
-                        msg << *itsBunch << endl;
-                    }
-                } else {
-                    throw OpalException("ParallelTTracker::execute()",
-                                        "Unacceptable distribution type:\"" +
-                                        d->GetTypeofDistribution() +
-                                        "\". Need to check the input file... ...");
-                }
-            }
+            itsBunch_m->calcBeamParameters();
         }
+        if (!statDump && !driftToCorrectPosition) itsBunch_m->calcBeamParameters();
 
-        /// this is still in BoundaryGeometry
-        size_t nbparts = dist->GetNumberOfDarkCurrentParticles();
-        double darkinwardmargin = dist->GetDarkCurrentParticlesInwardMargin();
-        double workFunction = dist->GetWorkFunction();
-        double fieldEnhancement = dist->GetFieldEnhancement();
-        size_t maxfnemission = dist->GetMaxFNemissionPartPerTri();
-        double fieldFNthreshold = dist->GetFieldFNThreshold();
-        double parameterFNA = dist->GetFNParameterA();
-        double parameterFNB = dist->GetFNParameterB();
-        double parameterFNY = dist->GetFNParameterY();
-        double parameterFNVYZe = dist->GetFNParameterVYZero();
-        double parameterFNVYSe = dist->GetFNParameterVYSecond();
-
-        secondaryFlg_m = dist->GetSecondaryEmissionFlag();
-        nEmissionMode_m = dist->GetEmissionMode();
-        bgf_m->setNEmissionMode(nEmissionMode_m);
-        if(secondaryFlg_m) {
-            if(secondaryFlg_m == 1) {
-                int BoundaryMatType = dist->GetSurfMaterial();
-                bgf_m->setBoundaryMatType(BoundaryMatType);
-                if(Options::ppdebug) {
-                    /*
-                      set thermal velocity of Maxwellian distribution of
-                      secondaries for benchmark
-                    */
-                    double vVThermal = dist->GetvVThermal();
-                    bgf_m->setvVThermal(vVThermal);
-                    double ppVw = dist->GetVw();
-                    bgf_m->setVw(ppVw);
-                } else {
-                    bgf_m->setvVThermal(1.0);
-                    bgf_m->setVw(1.0);
-                }
-            } else {
-                /*
-                  parameters for Vaughan's secondary model
-                */
-                // sey_0 in Vaughan's model
-                double vSeyZero = dist->GetvSeyZero();
-                // energy related to sey_0 in Vaughan's model
-                double vEZero = dist->GetvEZero();
-                // sey max in Vaughan's model
-                double vSeyMax = dist->GetvSeyMax();
-                // Emax in Vaughan's model
-                double vEmax = dist->GetvEmax();
-                // fitting parameter denotes the roughness of surface for impact energy in Vaughan's model
-                double vKenergy = dist->GetvKenergy();
-                // fitting parameter denotes the roughness of surface for impact angle in Vaughan's model
-                double vKtheta = dist->GetvKtheta();
-                // return thermal velocity of Maxwellian distribution of secondaries in Vaughan's model
-                double vVThermal = dist->GetvVThermal();
-                double ppVw = dist->GetVw();
-                bgf_m->setVw(ppVw);
-                bgf_m->setvSeyZero(vSeyZero);
-                bgf_m->setvEZero(vEZero);
-                bgf_m->setvSeyMax(vSeyMax);
-                bgf_m->setvEmax(vEmax);
-                bgf_m->setvKenergy(vKenergy);
-                bgf_m->setvKtheta(vKtheta);
-                bgf_m->setvVThermal(vVThermal);
+        msg << *itsBunch_m << endl;
+        itsDataSink_m->writePhaseSpace(*itsBunch_m, FDext);
+
+        if (driftToCorrectPosition) {
+            if (localNum > 0) {
+                itsBunch_m->R = stashedR;
+                stashedR.destroy(localNum, 0);
             }
-        }
-        if(nbparts != 0) {
-            /*
-              :FIXME: maybe need to be called in each time step for modeling
-              creating darkcurrent in each time step
-            */
-            bgf_m->createParticlesOnSurface(nbparts, darkinwardmargin, itsOpalBeamline_m, *itsBunch);
-            dist->CreateBoundaryGeometry(*itsBunch, *bgf_m);
-        }
-        bgf_m->setWorkFunction(workFunction);
-        bgf_m->setFieldEnhancement(fieldEnhancement);
-        bgf_m->setMaxFN(maxfnemission);
-        bgf_m->setFNTreshold(fieldFNthreshold);
-        bgf_m->setFNParameterA(parameterFNA);
-        bgf_m->setFNParameterB(parameterFNB);
-        bgf_m->setFNParameterY(parameterFNY);
-        bgf_m->setFNParameterVYZe(parameterFNVYZe);
-        bgf_m->setFNParameterVYSe(parameterFNVYSe);
-        numParticlesInSimulation_m = itsBunch->getTotalNum();
-        if(numParticlesInSimulation_m > 0) {
-            writePhaseSpace(0, 0, true, true); // dump the initial particles
-        }
-        itsDataSink_m->writeGeomToVtk(*bgf_m, std::string("data/testGeometry-00000.vtk"));
-        //itsDataSink->writePartlossZASCII(*itsBunch, *bgf_m, std::string("vtk/PartlossZ-"));
 
-        OpalData::getInstance()->setGlobalGeometry(bgf_m);
+            itsBunch_m->RefPartR_m = referenceToLabCSTrafo_m.transformTo(RefPartR_m);
+            itsBunch_m->set_sPos(pathLength_m);
 
-        RealVariable *maxnp = dynamic_cast<RealVariable *>(OpalData::getInstance()->find("MAXPARTSNUM"));
-        if(maxnp) {
-            // set upper limit of particle number in simulation
-            maxNparts_m = static_cast<size_t>(maxnp->getReal());
+            itsBunch_m->calcBeamParameters();
         }
 
-        msg << "Boundary geometry initialized " << endl;
+        msg << level2 << "* Wrote beam phase space." << endl;
     }
 }
 
-void ParallelTTracker::push(double h) {
-    for(unsigned int i = 0; i < itsBunch->getLocalNum(); ++i) {
-        double const gamma = sqrt(1.0 + dot(itsBunch->P[i], itsBunch->P[i]));
-        Vector_t const v = itsBunch->P[i] * Physics::c / gamma;
-        itsBunch->R[i] += h * v;
-        itsBunch->X[i] += h * TransformTo(v, itsOpalBeamline_m.getOrientation(itsBunch->LastSection[i]));
+void ParallelTTracker::updateReferenceParticle(const BorisPusher &pusher) {
+    static size_t step = 0;
+    const double dt = std::min(itsBunch_m->getT(), itsBunch_m->getdT());
+    const double scaleFactor = Physics::c * dt;
+    Vector_t Ef(0.0), Bf(0.0);
+    // Vector_t oldR = RefPartR_m;
+
+    RefPartR_m /= scaleFactor;
+    pusher.push(RefPartR_m, RefPartP_m, dt);
+    RefPartR_m *= scaleFactor;
+
+    IndexMap::value_t elements = itsOpalBeamline_m.getElements(referenceToLabCSTrafo_m.transformTo(RefPartR_m));
+    IndexMap::value_t::const_iterator it = elements.begin();
+    const IndexMap::value_t::const_iterator end = elements.end();
+
+    for (; it != end; ++ it) {
+        CoordinateSystemTrafo refToLocalCSTrafo = itsOpalBeamline_m.getCSTrafoLab2Local((*it)) * referenceToLabCSTrafo_m;
+
+        Vector_t localR = refToLocalCSTrafo.transformTo(RefPartR_m);
+        Vector_t localP = refToLocalCSTrafo.rotateTo(RefPartP_m);
+        Vector_t localE(0.0), localB(0.0);
+
+        if ((*it)->applyToReferenceParticle(localR,
+                                            localP,
+                                            itsBunch_m->getT() - 0.5 * dt,
+                                            localE,
+                                            localB)) {
+            globalEOL_m = true;
+        }
+
+        Ef += refToLocalCSTrafo.rotateFrom(localE);
+        Bf += refToLocalCSTrafo.rotateFrom(localB);
+    }
+
+    // if (step % loggingFrequency_m == 0) {
+    //     Vector_t R = referenceToLabCSTrafo_m.transformTo(RefPartR_m);
+    //     Vector_t P = referenceToLabCSTrafo_m.rotateTo(RefPartP_m);
+    //     Vector_t lEf = referenceToLabCSTrafo_m.rotateTo(Ef);
+    //     Vector_t lBf = referenceToLabCSTrafo_m.rotateTo(Bf);
+    //     logger_m << std::setw(18) << std::setprecision(8) << pathLength_m + euclidian_norm(RefPartR_m - oldR)
+    //              << std::setw(18) << std::setprecision(8) << R(0)
+    //              << std::setw(18) << std::setprecision(8) << R(1)
+    //              << std::setw(18) << std::setprecision(8) << R(2)
+    //              << std::setw(18) << std::setprecision(8) << P(0)
+    //              << std::setw(18) << std::setprecision(8) << P(1)
+    //              << std::setw(18) << std::setprecision(8) << P(2)
+    //              << std::setw(18) << std::setprecision(8) << lEf(0)
+    //              << std::setw(18) << std::setprecision(8) << lEf(1)
+    //              << std::setw(18) << std::setprecision(8) << lEf(2)
+    //              << std::setw(18) << std::setprecision(8) << lBf(0)
+    //              << std::setw(18) << std::setprecision(8) << lBf(1)
+    //              << std::setw(18) << std::setprecision(8) << lBf(2)
+    //              << std::setw(18) << std::setprecision(8) << Util::getEnergy(RefPartP_m, itsBunch_m->getM() * 1e-6)
+    //              << std::setw(18) << std::setprecision(8) << (itsBunch_m->getT() - 0.5 * itsBunch_m->getdT()) * 1e9
+    //              << std::endl;
+    // }
+
+    pusher.kick(RefPartR_m, RefPartP_m, Ef, Bf, dt);
+
+    RefPartR_m /= scaleFactor;
+    pusher.push(RefPartR_m, RefPartP_m, dt);
+    RefPartR_m *= scaleFactor;
+
+    ++ step;
+}
+
+void ParallelTTracker::transformBunch(const CoordinateSystemTrafo &trafo) {
+    const unsigned int localNum = itsBunch_m->getLocalNum();
+    for (unsigned int i = 0; i < localNum; ++i) {
+        itsBunch_m->R[i] = trafo.transformTo(itsBunch_m->R[i]);
+        itsBunch_m->P[i] = trafo.rotateTo(itsBunch_m->P[i]);
+        itsBunch_m->Ef[i] = trafo.rotateTo(itsBunch_m->Ef[i]);
+        itsBunch_m->Bf[i] = trafo.rotateTo(itsBunch_m->Bf[i]);
     }
+}
 
-    // Push the reference particle
-    double const gamma = sqrt(1.0 + dot(RefPartP_suv_m, RefPartP_suv_m));
-    Vector_t v_zxy = RefPartP_zxy_m * Physics::c / gamma;
-    RefPartR_zxy_m += h * v_zxy;
+void ParallelTTracker::updateRefToLabCSTrafo(const BorisPusher &pusher) {
+    updateReferenceParticle(pusher);
 
-    itsBunch->setT(itsBunch->getT() + h);
+    pathLength_m += euclidian_norm(RefPartR_m);
+
+    CoordinateSystemTrafo update(RefPartR_m,
+                                 getQuaternion(RefPartP_m, Vector_t(0, 0, 1)));
+
+    RefPartR_m = update.transformTo(RefPartR_m);
+    RefPartP_m = update.rotateTo(RefPartP_m);
+
+    transformBunch(update);
+
+    referenceToLabCSTrafo_m = referenceToLabCSTrafo_m * update.inverted();
 }
 
-void ParallelTTracker::kick(double h, bool avoidGammaCalc) {
-    double const q = itsReference.getQ();
-    double const M = itsReference.getM();
-    double const h12Halfqc_M = 0.5 * h * q * Physics::c / M;
-    double const h12Halfqcc_M = h12Halfqc_M * Physics::c;
-    for(unsigned int i = 0; i < itsBunch->getLocalNum(); ++i) {
-        itsBunch->P[i] += h12Halfqc_M * itsBunch->Ef[i];
+void ParallelTTracker::findStartPosition(const BorisPusher &pusher) {
+
+    double t = 0.0;
+    itsBunch_m->setT(t);
+
+    dtCurrentTrack_m = dtAllTracks_m.front();
+    changeDT();
+
+    if (Util::getEnergy(RefPartP_m, itsBunch_m->getM()) < 1e-3) {
+        double gamma = 0.1 / itsBunch_m->getM() + 1.0;
+        RefPartP_m = sqrt(std::pow(gamma, 2) - 1) * Vector_t(0, 0, 1);
     }
-    if(avoidGammaCalc) {
-        // Only calculate gamma if B-field nonzero...of course this check itself
-        // gives some overhead, thus the caller can use the flag avoidGammaCalc
-        Vector_t const zero = Vector_t(0.0);
-        for(unsigned int i = 0; i < itsBunch->getLocalNum(); ++i) {
-            if(itsBunch->Bf[i] != zero) {
-                double const gamma = sqrt(1.0 + dot(itsBunch->P[i], itsBunch->P[i]));
-                Vector_t const r = h12Halfqcc_M * itsBunch->Bf[i] / gamma;
-                Vector_t const w = itsBunch->P[i] + cross(itsBunch->P[i], r);
-                Vector_t const s = 2.0 / (1.0 + dot(r, r)) * r;
-                itsBunch->P[i] += cross(w, s);
-            }
+
+    while (true) {
+        autophaseCavities(pusher);
+
+        t += itsBunch_m->getdT();
+        itsBunch_m->setT(t);
+
+        Vector_t oldR = RefPartR_m;
+        updateReferenceParticle(pusher);
+        pathLength_m += euclidian_norm(RefPartR_m - oldR);
+
+        if (pathLength_m > zStop_m.front()) {
+            if (localTrackSteps_m.size() == 0) return;
+
+            dtAllTracks_m.pop();
+            localTrackSteps_m.pop();
+            zStop_m.pop();
+
+            changeDT();
         }
-    } else {
-        for(unsigned int i = 0; i < itsBunch->getLocalNum(); ++i) {
-            double const gamma = sqrt(1.0 + dot(itsBunch->P[i], itsBunch->P[i]));
-            Vector_t const r = h12Halfqcc_M * itsBunch->Bf[i] / gamma;
-            Vector_t const w = itsBunch->P[i] + cross(itsBunch->P[i], r);
-            Vector_t const s = 2.0 / (1.0 + dot(r, r)) * r;
-            itsBunch->P[i] += cross(w, s);
+
+        double speed = euclidian_norm(RefPartP_m) * Physics::c / sqrt(dot(RefPartP_m, RefPartP_m) + 1);
+        if (std::abs(pathLength_m - zstart_m) <=  0.5 * itsBunch_m->getdT() * speed) {
+            double tau = (pathLength_m - zstart_m) / speed;
+
+            t += tau;
+            itsBunch_m->setT(t);
+
+            RefPartR_m /= (Physics::c * tau);
+            pusher.push(RefPartR_m, RefPartP_m, tau);
+            RefPartR_m *= (Physics::c * tau);
+
+            pathLength_m = zstart_m;
+
+            CoordinateSystemTrafo update(RefPartR_m,
+                                         getQuaternion(RefPartP_m, Vector_t(0, 0, 1)));
+            referenceToLabCSTrafo_m = referenceToLabCSTrafo_m * update.inverted();
+
+            RefPartR_m = update.transformTo(RefPartR_m);
+            RefPartP_m = update.rotateTo(RefPartP_m);
+
+            return;
         }
     }
-    for(unsigned int i = 0; i < itsBunch->getLocalNum(); ++i) {
-        itsBunch->P[i] += h12Halfqc_M * itsBunch->Ef[i];
-    }
 }
 
-void ParallelTTracker::computeExternalFields_AMTS() {
-    // We use a own function because the original computeExternalFields evaluates
-    // the field at times itsBunch->getT() + itsBunch->dt[i] / 2, but we
-    // need it evaluated at itsBunch->getT(). There is currently no need for individual time steps
-    // in AMTS, because we don't support emission.
-    // TODO: Unify these two functions
-    Inform msg("ParallelTTracker ", *gmsg);
-    bends_m = 0;
-    for(unsigned int i = 0; i < itsBunch->getLocalNum(); ++i) {
-        long ls = itsBunch->LastSection[i];
-        itsOpalBeamline_m.getSectionIndexAt(itsBunch->R[i], ls);
-        if(ls != itsBunch->LastSection[i]) {
-            if(!itsOpalBeamline_m.section_is_glued_to(itsBunch->LastSection[i], ls)) {
-                itsBunch->ResetLocalCoordinateSystem(i, itsOpalBeamline_m.getOrientation(ls), itsOpalBeamline_m.getSectionStart(ls));
+void ParallelTTracker::autophaseCavities(const BorisPusher &pusher) {
+
+    double t = itsBunch_m->getT();
+    Vector_t nextR = RefPartR_m / (Physics::c * itsBunch_m->getdT());
+    pusher.push(nextR, RefPartP_m, itsBunch_m->getdT());
+    nextR *= Physics::c * itsBunch_m->getdT();
+
+    auto elementSet = itsOpalBeamline_m.getElements(referenceToLabCSTrafo_m.transformTo(nextR));
+    for (auto element: elementSet) {
+        if (element->getType() == ElementBase::TRAVELINGWAVE) {
+            const TravelingWave *TWelement = static_cast<const TravelingWave *>(element.get());
+            if (!TWelement->getAutophaseVeto()) {
+                RefPartR_m = referenceToLabCSTrafo_m.transformTo(RefPartR_m);
+                RefPartP_m = referenceToLabCSTrafo_m.rotateTo(RefPartP_m);
+                CavityAutophaser ap(itsReference, element);
+                ap.getPhaseAtMaxEnergy(itsOpalBeamline_m.transformToLocalCS(element, RefPartR_m),
+                                       itsOpalBeamline_m.rotateToLocalCS(element, RefPartP_m),
+                                       t, itsBunch_m->getdT());
+                RefPartR_m = referenceToLabCSTrafo_m.transformFrom(RefPartR_m);
+                RefPartP_m = referenceToLabCSTrafo_m.rotateFrom(RefPartP_m);
+            }
+
+        } else if (element->getType() == ElementBase::RFCAVITY) {
+            const RFCavity *RFelement = static_cast<const RFCavity *>(element.get());
+            if (!RFelement->getAutophaseVeto()) {
+                RefPartR_m = referenceToLabCSTrafo_m.transformTo(RefPartR_m);
+                RefPartP_m = referenceToLabCSTrafo_m.rotateTo(RefPartP_m);
+                CavityAutophaser ap(itsReference, element);
+                ap.getPhaseAtMaxEnergy(itsOpalBeamline_m.transformToLocalCS(element, RefPartR_m),
+                                       itsOpalBeamline_m.rotateToLocalCS(element, RefPartP_m),
+                                       t, itsBunch_m->getdT());
+                RefPartR_m = referenceToLabCSTrafo_m.transformFrom(RefPartR_m);
+                RefPartP_m = referenceToLabCSTrafo_m.rotateFrom(RefPartP_m);
             }
-            itsBunch->LastSection[i] = ls;
         }
-        Vector_t externalE, externalB;
-        const unsigned long rtv = itsOpalBeamline_m.getFieldAt(i, itsBunch->R[i], ls, itsBunch->getT(), externalE, externalB);
-        itsBunch->Ef[i] += externalE;
-        itsBunch->Bf[i] += externalB;
-        bends_m = bends_m || (rtv & BEAMLINE_BEND);
     }
-    reduce(bends_m, bends_m, OpAddAssign());
 }
 
-void ParallelTTracker::borisExternalFields(double h, bool isFirstSubstep, bool isLastSubstep) {
+struct DistributionInfo {
+    unsigned int who;
+    unsigned int whom;
+    unsigned int howMany;
+};
 
-    IpplTimings::startTimer(IpplTimings::getTimer("AMTS-Push"));
-    if(isFirstSubstep) {
-        push(0.5 * h);
-    }
-    // Optimization: If this is not the first substep, our first half push was done in the last
-    // substep.
-    IpplTimings::stopTimer(IpplTimings::getTimer("AMTS-Push"));
-
-    IpplTimings::startTimer(IpplTimings::getTimer("AMTS-EvalExternal"));
-    itsBunch->Ef = Vector_t(0.0);
-    itsBunch->Bf = Vector_t(0.0);
-    computeExternalFields_AMTS();
-    IpplTimings::stopTimer(IpplTimings::getTimer("AMTS-EvalExternal"));
-
-    IpplTimings::startTimer(IpplTimings::getTimer("AMTS-Kick"));
-    kick(h, true);
-
-    // Update momentum of reference particle
-    if(bends_m == 0) {
-        RefPartP_suv_m = calcMeanP();
-    } else {
-        updateSpaceOrientation(false);
-        RefPartP_suv_m = Vector_t(0.0, 0.0, sqrt(dot(RefPartP_suv_m, RefPartP_suv_m)));
-    }
-    RefPartP_zxy_m = dot(space_orientation_m, RefPartP_suv_m);
-    IpplTimings::stopTimer(IpplTimings::getTimer("AMTS-Kick"));
+void ParallelTTracker::evenlyDistributeParticles() {
+    if (itsBunch_m->hasFieldSolver()) return;
 
-    IpplTimings::startTimer(IpplTimings::getTimer("AMTS-Push"));
-    if(isLastSubstep) {
-        push(0.5 * h);
-    } else {
-        // Optimization: We include the first half push of the following substep here
-        push(h);
-    }
-    IpplTimings::stopTimer(IpplTimings::getTimer("AMTS-Push"));
+    long onAverage = itsBunch_m->getTotalNum() / Ippl::getNodes();
+    if (itsBunch_m->getTotalNum() % Ippl::getNodes() > 0.5 * Ippl::getNodes())
+        ++ onAverage;
 
-}
+    std::vector<long> localParticles(Ippl::getNodes(), 0);
+    localParticles[Ippl::myNode()] = itsBunch_m->getLocalNum() - onAverage;
+    reduce(&(localParticles[0]),
+           &(localParticles[0]) + Ippl::getNodes(),
+           &(localParticles[0]),
+           OpAddAssign());
 
-double ParallelTTracker::calcG() {
-    if(!itsBunch->hasFieldSolver()) {
-        return 1.0;
-    }
-    double maxAcc = 0.0;
-    for(unsigned int i = 0; i < itsBunch->getLocalNum(); ++i) {
-        // Assuming m = 1 and q = 1 (constants can be taken out of g)
-        Vector_t const P = itsBunch->P[i];
-        double const invGamma = 1.0 / sqrt(1.0 + dot(P, P));
-        // dpdt is the force acting on the particle, derivative of the relativistic momentum
-        Vector_t const dpdt = itsBunch->Ef[i] + cross(P * Physics::c * invGamma, itsBunch->Bf[i]);
-        // Calculate acceleration as the second derivative of the position, i.e. derivative of
-        // velocity
-        Vector_t const acc = invGamma * (dpdt - P * dot(P, dpdt) * invGamma * invGamma);
-        double const accSquared = dot(acc, acc);
-        if(accSquared > maxAcc) {
-            maxAcc = accSquared;
-        }
-    }
-    reduce(maxAcc, maxAcc, OpMaxAssign());
-    maxAcc = sqrt(maxAcc);
-    double const exponent = 1.0;
-    return std::pow(maxAcc, -0.5 * exponent);
-}
+    std::vector<DistributionInfo> send;
+    std::vector<DistributionInfo> receive;
 
-Vector_t ParallelTTracker::calcMeanR() const {
-    Vector_t meanR(0.0, 0.0, 0.0);
-    for(unsigned int i = 0; i < itsBunch->getLocalNum(); ++i) {
-        for(int d = 0; d < 3; ++d) {
-            meanR(d) += itsBunch->R[i](d);
-        }
-    }
-    reduce(meanR, meanR, OpAddAssign());
-    return meanR / Vector_t(itsBunch->getTotalNum());
-}
+    for (int i = 0; i < Ippl::getNodes(); ++ i) {
+        if (localParticles[i] <= 0) continue;
 
-Vector_t ParallelTTracker::calcMeanP() const {
-    Vector_t meanP(0.0, 0.0, 0.0);
-    for(unsigned int i = 0; i < itsBunch->getLocalNum(); ++i) {
-        for(int d = 0; d < 3; ++d) {
-            meanP(d) += itsBunch->P[i](d);
-        }
-    }
-    reduce(meanP, meanP, OpAddAssign());
-    return meanP / Vector_t(itsBunch->getTotalNum());
-}
+        for (int j = 0; j < Ippl::getNodes(); ++ j) {
+            if (j == i || localParticles[j] >= 0) continue;
 
-void ParallelTTracker::writePhaseSpace(const long long step, const double &sposRef, bool psDump, bool statDump) {
-    extern Inform *gmsg;
-    Inform msg("OPAL ", *gmsg);
-    Vector_t externalE, externalB;
-    Vector_t FDext[6];  // FDext = {BHead, EHead, BRef, ERef, BTail, ETail}.
+            long numParts = std::min(localParticles[i], -localParticles[j]);
+            localParticles[i] -= numParts;
+            localParticles[j] += numParts;
 
-    // Sample fields at (xmin, ymin, zmin), (xmax, ymax, zmax) and the centroid location. We
-    // are sampling the electric and magnetic fields at the back, front and
-    // center of the beam.
-    Vector_t rmin, rmax;
-    itsBunch->get_bounds(rmin, rmax);
-
-    Vector_t pos[3];
-    pos[0] = Vector_t(rmax(0), rmax(1), rmax(2));
-    pos[1] = Vector_t(0.0, 0.0, sposRef);
-    pos[2] = Vector_t(rmin(0), rmin(1), rmin(2));
-
-#ifdef DBG_SYM
-
-    const double h = 0.001;
-
-    Vector_t gridN = Vector_t(h, h, sposRef);
-    Vector_t gridS = Vector_t(h, -h, sposRef);
-    Vector_t gridW = Vector_t(-h, h, sposRef);
-    Vector_t gridO = Vector_t(-h, -h, sposRef);
-
-    externalB = Vector_t(0.0);
-    externalE = Vector_t(0.0);
-    itsOpalBeamline_m.getFieldAt(gridN, itsBunch->get_rmean(), itsBunch->getT() - 0.5 * itsBunch->getdT(), externalE, externalB);
-    of_m << sposRef << "\t " << externalE(0) * 1e-6 << "\t " << externalE(1) * 1e-6 << "\t " << externalE(2) * 1e-6
-         << "\t " << externalB(0) << "\t " << externalB(1) << "\t " << externalB(2) << "\t ";
-    externalB = Vector_t(0.0);
-    externalE = Vector_t(0.0);
-    itsOpalBeamline_m.getFieldAt(gridS, itsBunch->get_rmean(), itsBunch->getT() - 0.5 * itsBunch->getdT(), externalE, externalB);
-    of_m << externalE(0) * 1e-6 << "\t " << externalE(1) * 1e-6 << "\t " << externalE(2) * 1e-6
-         << "\t " << externalB(0) << "\t " << externalB(1) << "\t " << externalB(2) << "\t ";
-
-    externalB = Vector_t(0.0);
-    externalE = Vector_t(0.0);
-    itsOpalBeamline_m.getFieldAt(gridW, itsBunch->get_rmean(), itsBunch->getT() - 0.5 * itsBunch->getdT(), externalE, externalB);
-    of_m << externalE(0) * 1e-6 << "\t " << externalE(1) * 1e-6 << "\t " << externalE(2) * 1e-6
-         << "\t " << externalB(0) << "\t " << externalB(1) << "\t " << externalB(2) << "\t ";
-    externalB = Vector_t(0.0);
-    externalE = Vector_t(0.0);
-    itsOpalBeamline_m.getFieldAt(gridO, itsBunch->get_rmean(), itsBunch->getT() - 0.5 * itsBunch->getdT(), externalE, externalB);
-    of_m << externalE(0) * 1e-6 << "\t " << externalE(1) * 1e-6 << "\t " << externalE(2) * 1e-6
-         << "\t " << externalB(0) << "\t " << externalB(1) << "\t " << externalB(2) << endl;
-#endif
+            if (i == Ippl::myNode() || j == Ippl::myNode()) {
+                DistributionInfo request;
+                request.who = i;
+                request.whom = j;
+                request.howMany = numParts;
 
-    if (psDump || statDump) {
-        for(int k = 0; k < 3; ++k) {
-            externalB = Vector_t(0.0);
-            externalE = Vector_t(0.0);
-            itsOpalBeamline_m.getFieldAt(pos[k], itsBunch->get_rmean(), itsBunch->getT() - 0.5 * itsBunch->getdT(), externalE, externalB);
-            FDext[2 * k]   = externalB;
-            FDext[2 * k + 1] = externalE * 1e-6;
+                if (i == Ippl::myNode()) {
+                    send.push_back(request);
+                } else {
+                    receive.push_back(request);
+                }
+            }
+
+            if (localParticles[i] == 0) break;
         }
     }
 
-    if(psDump && (itsBunch->getTotalNum() > 0)) {
-        // Write fields to .h5 file.
-        itsDataSink_m->writePhaseSpace(*itsBunch, FDext, rmax(2), sposRef, rmin(2));
-        msg << level3 << "* Wrote beam phase space." << endl;
-        msg << *itsBunch << endl;
-    }
+    std::vector<MPI_Request> requests;
+    std::vector<char> msgbuf;
+    const char *buffer;
+    int tag = Ippl::Comm->next_tag(P_SPATIAL_TRANSFER_TAG,P_LAYOUT_CYCLE);
 
-    if(statDump) {
-        std::vector<std::pair<std::string, unsigned int> > collimatorLosses;
-        FieldList collimators = itsOpalBeamline_m.getElementByType(ElementBase::COLLIMATOR);
-	if (collimators.size() != 0) {
-	  for (FieldList::iterator it = collimators.begin(); it != collimators.end(); ++ it) {
-  	    Collimator* coll = static_cast<Collimator*>(it->getElement().get());
-            std::string name = coll->getName();
-            unsigned int losses = coll->getLosses();
-            collimatorLosses.push_back(std::make_pair(name, losses));
-	  }
-	  std::sort(collimatorLosses.begin(), collimatorLosses.end(),
-		    [](const std::pair<std::string, unsigned int>& a, const std::pair<std::string, unsigned int>& b) ->bool {
-                      return a.first < b.first;
-		    });
-	  std::vector<unsigned int> bareLosses(collimatorLosses.size(),0);
-	  for (size_t i = 0; i < collimatorLosses.size(); ++ i){
-            bareLosses[i] = collimatorLosses[i].second;
-	  }
-
-	  reduce(&bareLosses[0], &bareLosses[0] + bareLosses.size(), &bareLosses[0], OpAddAssign());
-
-	  for (size_t i = 0; i < collimatorLosses.size(); ++ i){
-            collimatorLosses[i].second = bareLosses[i];
-	  }
-	}
-        // Write statistical data.
-        msg << level3 << "* Wrote beam statistics." << endl;
-        itsDataSink_m->writeStatData(*itsBunch, FDext, rmax(2), sposRef, rmin(2), collimatorLosses);
+    long sizeSingleParticle = 9 * sizeof(double) + sizeof(short) + sizeof(int) + sizeof(PID_t::Return_t);
+    long idx = itsBunch_m->getLocalNum() - 1;
+    unsigned int totalSend = 0, startIndex = 0;
+    for (DistributionInfo &request: send) {
+        totalSend += request.howMany;
     }
-}
+    msgbuf.reserve(totalSend * sizeSingleParticle);
 
-#ifdef OPAL_DKS
+    for (DistributionInfo &request: send) {
 
-void ParallelTTracker::registerHostMemory() {
+        // long j = startIndex;
+        for (long i = 0; i < request.howMany; ++ i, -- idx) {
+            buffer = reinterpret_cast<const char*>(&(itsBunch_m->R[idx](0)));
+            msgbuf.insert(msgbuf.end(), buffer, buffer + 3 * sizeof(double));
+            buffer = reinterpret_cast<const char*>(&(itsBunch_m->P[idx](0)));
+            msgbuf.insert(msgbuf.end(), buffer, buffer + 3 * sizeof(double));
+            buffer = reinterpret_cast<const char*>(&(itsBunch_m->Q[idx]));
+            msgbuf.insert(msgbuf.end(), buffer, buffer + sizeof(double));
+            buffer = reinterpret_cast<const char*>(&(itsBunch_m->M[idx]));
+            msgbuf.insert(msgbuf.end(), buffer, buffer + sizeof(double));
+            buffer = reinterpret_cast<const char*>(&(itsBunch_m->dt[idx]));
+            msgbuf.insert(msgbuf.end(), buffer, buffer + sizeof(double));
+            buffer = reinterpret_cast<const char*>(&(itsBunch_m->PType[idx]));
+            msgbuf.insert(msgbuf.end(), buffer, buffer + sizeof(short));
+            buffer = reinterpret_cast<const char*>(&(itsBunch_m->TriID[idx]));
+            msgbuf.insert(msgbuf.end(), buffer, buffer + sizeof(int));
+            buffer = reinterpret_cast<const char*>(&(itsBunch_m->ID[idx]));
+            msgbuf.insert(msgbuf.end(), buffer, buffer + sizeof(PID_t::Return_t));
 
-    if (Ippl::getNodes() == 1) {
-        dksbase.registerHostMemory(&itsBunch->R[0], itsBunch->getLocalNum());
-        dksbase.registerHostMemory(&itsBunch->P[0], itsBunch->getLocalNum());
-        dksbase.registerHostMemory(&itsBunch->X[0], itsBunch->getLocalNum());
-        dksbase.registerHostMemory(&itsBunch->dt[0], itsBunch->getLocalNum());
-        dksbase.registerHostMemory(&itsBunch->LastSection[0], itsBunch->getLocalNum());
-    }
-    numDeviceElements = itsBunch->getLocalNum();
+            // const double *dbuffer = reinterpret_cast<const double*>(&msgbuf[0] + j);
+            // const short *shbuffer = reinterpret_cast<const short*>(&msgbuf[0] + j + 9 * sizeof(double));
+            // const int* ibuffer = reinterpret_cast<const int*>(&msgbuf[0] + j + 9 * sizeof(double) + sizeof(short));
+            // const PID_t::Return_t *sbuffer = reinterpret_cast<const PID_t::Return_t*>(&msgbuf[0] + j + sizeSingleParticle - sizeof(PID_t::Return_t));
 
-}
+            // befo << std::setw(18) << dbuffer[0]
+            //      << std::setw(18) << dbuffer[1]
+            //      << std::setw(18) << dbuffer[2]
+            //      << std::setw(18) << dbuffer[3]
+            //      << std::setw(18) << dbuffer[4]
+            //      << std::setw(18) << dbuffer[5]
+            //      << std::setw(8) << shbuffer[0]
+            //      << std::setw(8) << ibuffer[0]
+            //      << std::setw(18) << *sbuffer
+            //      << std::endl;
 
-void ParallelTTracker::unregisterHostMemory() {
-    
-    if (Ippl::getNodes() == 1) {
-        dksbase.unregisterHostMemory(&itsBunch->R[0]);
-        dksbase.unregisterHostMemory(&itsBunch->P[0]);
-        dksbase.unregisterHostMemory(&itsBunch->X[0]);
-        dksbase.unregisterHostMemory(&itsBunch->dt[0]);
-        dksbase.unregisterHostMemory(&itsBunch->LastSection[0]);
+
+            // j += sizeSingleParticle;
+        }
+
+        size_t sendSizeThis = request.howMany * sizeSingleParticle;
+        MPI_Request req = Ippl::Comm->raw_isend(&(msgbuf[startIndex]),
+                                                sendSizeThis,
+                                                request.whom,
+                                                tag);
+
+        requests.push_back(req);
+
+        startIndex += sendSizeThis;
     }
-    
-}
+    itsBunch_m->destroy(totalSend, idx + 1, true);
+    // itsBunch_m->performDestroy();
 
-void ParallelTTracker::allocateDeviceMemory() {
+    for (unsigned int i = 0; i < receive.size(); ++ i) {
+        int node = Communicate::COMM_ANY_NODE;
+        char *recvbuf;
+        const int bufsize = Ippl::Comm->raw_probe_receive(recvbuf, node, tag);
 
-    //allocate memory on device
-    r_ptr = dksbase.allocateMemory<Vector_t>(itsBunch->getLocalNum(), ierr);
-    p_ptr = dksbase.allocateMemory<Vector_t>(itsBunch->getLocalNum(), ierr);
-    x_ptr = dksbase.allocateMemory<Vector_t>(itsBunch->getLocalNum(), ierr);
-    lastSec_ptr = dksbase.allocateMemory<long>(itsBunch->getLocalNum(), ierr);
-    dt_ptr = dksbase.allocateMemory<double>(itsBunch->getLocalNum(), ierr);
+        int j = 0;
+
+        while (j < bufsize) {
+            ++ idx;
+            itsBunch_m->create(1);
+            {
+                const double *buffer = reinterpret_cast<const double*>(recvbuf + j);
+                itsBunch_m->R[idx] = Vector_t(buffer[0], buffer[1], buffer[2]);
+                itsBunch_m->P[idx] = Vector_t(buffer[3], buffer[4], buffer[5]);
+                itsBunch_m->Q[idx] = buffer[6];
+                itsBunch_m->M[idx] = buffer[7];
+                itsBunch_m->dt[idx] = buffer[8];
+            }
+            j += 9 * sizeof(double);
 
-    numDeviceElements = itsBunch->getLocalNum();
+            {
+                const short *buffer = reinterpret_cast<const short*>(recvbuf + j);
+                itsBunch_m->PType[idx] = buffer[0];
+            }
+            j += sizeof(short);
 
-}
+            {
+                const int *buffer = reinterpret_cast<const int*>(recvbuf + j);
+                itsBunch_m->TriID[idx] = buffer[0];
+            }
+            j += sizeof(int);
+
+            {
+                const PID_t::Return_t *buffer = reinterpret_cast<const PID_t::Return_t*>(recvbuf + j);
+                itsBunch_m->ID[idx] = buffer[0];
+            }
+            j += sizeof(PID_t::Return_t);
 
-void ParallelTTracker::freeDeviceMemory() {
+            // aft << std::setw(18) << itsBunch_m->R[idx](0)
+            //       << std::setw(18) << itsBunch_m->R[idx](1)
+            //       << std::setw(18) << itsBunch_m->R[idx](2)
+            //       << std::setw(18) << itsBunch_m->P[idx](0)
+            //       << std::setw(18) << itsBunch_m->P[idx](1)
+            //       << std::setw(18) << itsBunch_m->P[idx](2)
+            //       << std::setw(18) << itsBunch_m->ID[idx]
+            //       << std::endl;
+        }
 
-    //free device memory
-    dksbase.freeMemory<Vector_t>(r_ptr, numDeviceElements);
-    dksbase.freeMemory<Vector_t>(p_ptr, numDeviceElements);
-    dksbase.freeMemory<Vector_t>(x_ptr, numDeviceElements);
-    dksbase.freeMemory<long>(lastSec_ptr, numDeviceElements);
-    dksbase.freeMemory<double>(dt_ptr, numDeviceElements);
+        delete[] recvbuf;
+    }
 
+    MPI_Waitall(requests.size(), &(requests[0]), MPI_STATUSES_IGNORE);
 }
 
-#endif
-
 // vi: set et ts=4 sw=4 sts=4:
 // Local Variables:
-// mode:c
+// mode:c++
 // c-basic-offset: 4
 // indent-tabs-mode:nil
-// End:
+// End:
\ No newline at end of file
diff --git a/src/Algorithms/ParallelTTracker.h b/src/Algorithms/ParallelTTracker.h
index 2bfa42a3d271fcf36e80ab46462244972b728481..abc054c1c7c6cc22cf5589b0f7ed879513c02482 100644
--- a/src/Algorithms/ParallelTTracker.h
+++ b/src/Algorithms/ParallelTTracker.h
@@ -28,33 +28,33 @@
 
 #include "Physics/Physics.h"
 
-class BMultipoleField;
-class PartBunch;
-class AlignWrapper;
-class BeamBeam;
+class OrbitThreader;
+#include "AbsBeamline/AlignWrapper.h"
+#include "AbsBeamline/BeamBeam.h"
 #include "AbsBeamline/Collimator.h"
-class Corrector;
-class Degrader;
-class Diagnostic;
-class Drift;
-class ElementBase;
-class Lambertson;
-class Marker;
-class Monitor;
-class Multipole;
-class Probe;
-class RBend;
-class RFCavity;
-class TravelingWave;
-class RFQuadrupole;
-class SBend;
-class Separator;
-class Septum;
-class Solenoid;
-class ParallelPlate;
-class CyclotronValley;
+#include "AbsBeamline/Corrector.h"
+#include "AbsBeamline/Diagnostic.h"
+#include "AbsBeamline/Drift.h"
+#include "AbsBeamline/ElementBase.h"
+#include "AbsBeamline/Lambertson.h"
+#include "AbsBeamline/Marker.h"
+#include "AbsBeamline/Monitor.h"
+#include "AbsBeamline/Multipole.h"
+#include "AbsBeamline/Probe.h"
+#include "AbsBeamline/RBend.h"
+#include "AbsBeamline/RBend3D.h"
+#include "AbsBeamline/RFCavity.h"
+#include "AbsBeamline/TravelingWave.h"
+#include "AbsBeamline/RFQuadrupole.h"
+#include "AbsBeamline/SBend.h"
+#include "AbsBeamline/Separator.h"
+#include "AbsBeamline/Septum.h"
+#include "AbsBeamline/Solenoid.h"
+#include "AbsBeamline/ParallelPlate.h"
+#include "AbsBeamline/CyclotronValley.h"
 
 #include "Beamlines/Beamline.h"
+#include "Beamlines/FlaggedBeamline.h"
 #include "Elements/OpalBeamline.h"
 #include "Solvers/WakeFunction.hh"
 
@@ -64,48 +64,7 @@ class CyclotronValley;
 
 class BorisPusher;
 
-
-
-// Class ParallelTTracker
-// ------------------------------------------------------------------------
-/// Track using a time integration scheme
-// [p]
-// Phase space coordinates numbering:
-// [tab 3 b]
-// [row]number [&]name          [&]unit  [/row]
-// [row]0      [&]$x$           [&]metres [/row]
-// [row]1      [&]$p_x/p_r$     [&]1      [/row]
-// [row]2      [&]$y$           [&]metres [/row]
-// [row]3      [&]$p_y/p_r$     [&]1      [/row]
-// [row]4      [&]$v*delta_t$   [&]metres [/row]
-// [row]5      [&]$delta_p/p_r$ [&]1      [/row]
-// [/tab][p]
-// Where $p_r$ is the constant reference momentum defining the reference
-// frame velocity, $m$ is the rest mass of the particles, and $v$ is the
-// instantaneous velocity of the particle.
-// [p]
-// Other units used:
-// [tab 2 b]
-// [row]quantity             [&]unit           [/row]
-// [row]reference momentum   [&]electron-volts [/row]
-// [row]velocity             [&]metres/second  [/row]
-// [row]accelerating voltage [&]volts          [/row]
-// [row]separator voltage    [&]volts          [/row]
-// [row]frequencies          [&]hertz          [/row]
-// [row]phase lags           [&]$2*pi$         [/row]
-// [/tab][p]
-// Approximations used:
-// [ul]
-// [li] blah
-// [li] blah
-// [li] blah
-// [/ul]
-//
-// On going through an element, we use the following steps:
-// To complete the map, we propagate the closed orbit and add that to the map.
-
 typedef std::pair<double, Vector_t > PhaseEnT;
-// typedef std::pair<std::string, double > MaxPhasesT;
 
 class ParallelTTracker: public Tracker {
 
@@ -116,8 +75,10 @@ public:
     //  The particle bunch tracked is initially empty.
     //  If [b]revBeam[/b] is true, the beam runs from s = C to s = 0.
     //  If [b]revTrack[/b] is true, we track against the beam.
-    explicit ParallelTTracker(const Beamline &bl, const PartData &data,
-                              bool revBeam, bool revTrack, size_t N);
+    explicit ParallelTTracker(const Beamline &bl,
+                              const PartData &data,
+                              bool revBeam,
+                              bool revTrack);
 
     /// Constructor.
     //  The beam line to be tracked is "bl".
@@ -125,10 +86,17 @@ public:
     //  The particle bunch tracked is taken from [b]bunch[/b].
     //  If [b]revBeam[/b] is true, the beam runs from s = C to s = 0.
     //  If [b]revTrack[/b] is true, we track against the beam.
-    explicit ParallelTTracker(const Beamline &bl, PartBunch &bunch, DataSink &ds,
-                              const PartData &data, bool revBeam, bool revTrack,
-                              const std::vector<unsigned long long> &maxSTEPS, const std::vector<double> &zstop,
-                              int timeIntegrator, const std::vector<double> &dt, size_t N);
+    explicit ParallelTTracker(const Beamline &bl,
+                              PartBunch &bunch,
+                              DataSink &ds,
+                              const PartData &data,
+                              bool revBeam,
+                              bool revTrack,
+                              const std::vector<unsigned long long> &maxSTEPS,
+                              double zstart,
+                              const std::vector<double> &zstop,
+                              const std::vector<double> &dt);
+
 
     virtual ~ParallelTTracker();
 
@@ -171,6 +139,9 @@ public:
     /// Apply the algorithm to a RBend.
     virtual void visitRBend(const RBend &);
 
+    /// Apply the algorithm to a RBend.
+    virtual void visitRBend3D(const RBend3D &);
+
     /// Apply the algorithm to a RFCavity.
     virtual void visitRFCavity(const RFCavity &);
 
@@ -192,6 +163,9 @@ public:
     /// Apply the algorithm to a Solenoid.
     virtual void visitSolenoid(const Solenoid &);
 
+    /// Apply the algorithm to a Solenoid.
+    virtual void visitSource(const Source &);
+
     /// Apply the algorithm to a ParallelPlate.
     virtual void visitParallelPlate(const ParallelPlate &);
 
@@ -199,27 +173,13 @@ public:
     virtual void visitCyclotronValley(const CyclotronValley &);
 
 
-    //
-    // Apply the emission considered schottky effect
-    double schottkyLoop(double coeff);
-
-    // Apply the correction to each particle for schottky effect
-    void applySchottkyCorrection(PartBunch &itsBunch, int ne, double t, double rescale_coeff);
-
-
-    /// Apply the algorithm to the top-level beamline.
-    //  overwrite the execute-methode from DefaultVisitor
-    virtual void execute();
-
     /// Apply the algorithm to a beam line.
     //  overwrite the execute-methode from DefaultVisitor
     virtual void visitBeamline(const Beamline &);
 
-    /// set Multipacting flag
-    inline void setMpacflg(bool mpacflg) {
-
-        mpacflg_m = mpacflg;
-    }
+    /// Apply the algorithm to the top-level beamline.
+    //  overwrite the execute-methode from DefaultVisitor
+    virtual void execute();
 
 private:
 
@@ -230,83 +190,35 @@ private:
 
     /******************** STATE VARIABLES ***********************************/
 
-    PartBunch        *itsBunch;
-    DataSink         *itsDataSink_m;
-    BoundaryGeometry *bgf_m;
+    PartBunch *itsBunch_m;
+    DataSink *itsDataSink_m;
 
     OpalBeamline itsOpalBeamline_m;
-    LineDensity  lineDensity_m;
-
-
-    Vector_t RefPartR_zxy_m;
-    Vector_t RefPartP_zxy_m;
-    Vector_t RefPartR_suv_m;
-    Vector_t RefPartP_suv_m;
-
-
-#ifdef OPAL_DKS
-  DKSBase dksbase;
 
-  void *r_ptr;
-  void *p_ptr;
-  void *x_ptr;
-
-  void *lastSec_ptr;
-  void *orient_ptr;
-  void *dt_ptr;
-
-  int ierr;
-
-  int stream1;
-  int stream2;
-
-  unsigned int numDeviceElements;
-
-  void registerHostMemory();
-  void unregisterHostMemory();
-  void allocateDeviceMemory();
-  void freeDeviceMemory();
-#endif
+    Vector_t RefPartR_m;
+    Vector_t RefPartP_m;
 
     bool globalEOL_m;
 
     bool wakeStatus_m;
 
-    /*--------- Added by Xiaoying Pang 04/22/2014 ---------------
-     * This WakeFunction pointer is used to store a dipole's wake function and
-     * to be used in the following drift if CSR calculation is requested in
-     * the drift. */
-    WakeFunction* wakeFunction_m;
-
-    bool surfaceStatus_m;
+    bool deletedParticles_m;
 
-    int secondaryFlg_m;
+    WakeFunction* wakeFunction_m;
 
-    /// multipacting flag
-    bool mpacflg_m;
+    double pathLength_m;
 
-    bool nEmissionMode_m;
+    /// where to start
+    double zstart_m;
 
     /// where to stop
     std::queue<double> zStop_m;
 
-    /// The scale factor for dimensionless variables (FIXME: move to PartBunch)
-    double scaleFactor_m;
-
-    // Vector of the scale factor for dimensionless variables (FIXME: move to PartBunch)
-    Vector_t vscaleFactor_m;
-
-    double recpGamma_m;
-
-    double rescale_coeff_m;
-
     double dtCurrentTrack_m;
     std::queue<double> dtAllTracks_m;
 
-    double surfaceEmissionStop_m;
-
-
-    size_t specifiedNPart_m;
+    /// The maximal number of steps the system is integrated per TRACK
+    std::queue<unsigned long long> localTrackSteps_m;
 
     // This variable controls the minimal number of steps of emission (using bins)
     // before we can merge the bins
@@ -318,399 +230,203 @@ private:
     size_t minBinEmitted_m;
 
     // this variable controls the minimal number of steps until we repartition the particles
-    int repartFreq_m;
-
-    int lastVisited_m;
-
-    /// The number of refinements of the search range of the phase
-    int numRefs_m;
-
-    /// ??
-    int gunSubTimeSteps_m;
+    unsigned int repartFreq_m;
 
     unsigned int emissionSteps_m;
 
-    /// The maximal number of steps the system is integrated per TRACK
-    std::queue<unsigned long long> localTrackSteps_m;
-
-    size_t maxNparts_m;
-    size_t numberOfFieldEmittedParticles_m;
-
-    // flag which indicates whether any particle is within the influence of bending element.
-    // if this is the case we track the reference particle as if it were a real particle,
-    // otherwise the reference particle is defined as the centroid particle of the bunch
-    unsigned long bends_m;
-
     size_t numParticlesInSimulation_m;
-    size_t totalParticlesInSimulation_m;
-
-    Tenzor<double, 3> space_orientation_m;
-
-    // Vector of the scale factor for dimensionless variables (FIXME: move to PartBunch)
 
     IpplTimings::TimerRef timeIntegrationTimer1_m;
     IpplTimings::TimerRef timeIntegrationTimer2_m;
-    IpplTimings::TimerRef timeFieldEvaluation_m ;
+    IpplTimings::TimerRef fieldEvaluationTimer_m ;
     IpplTimings::TimerRef BinRepartTimer_m;
     IpplTimings::TimerRef WakeFieldTimer_m;
-  
-    IpplTimings::TimerRef timeIntegrationTimer1Push_m;
-    IpplTimings::TimerRef timeIntegrationTimer2Push_m;
-
-    // 1 --- LF-2 (Boris-Buneman)
-    // 3 --- AMTS (Adaptive Boris-Buneman with multiple time stepping)
-    int timeIntegrator_m;
-
-
-    size_t Nimpact_m;
-    double SeyNum_m;
-
-
-    std::map<long, SurfacePhysicsHandler*> sphys_m;
 
+    CoordinateSystemTrafo referenceToLabCSTrafo_m;
 
     /********************** END VARIABLES ***********************************/
 
-    int LastVisited;
-
-    // Fringe fields for entrance and exit of magnetic elements.
-    void applyEntranceFringe(double edge, double curve,
-                             const BMultipoleField &field, double scale);
-    void applyExitFringe(double edge, double curve,
-                         const BMultipoleField &field, double scale);
-
-    inline double getEnergyMeV(Vector_t p) {
-        return (sqrt(dot(p, p) + 1.0) - 1.0) * itsBunch->getM() * 1e-6;
-    }
-
     void kickParticles(const BorisPusher &pusher);
-    void kickParticles(const BorisPusher &pusher, const int &flg);
-    void updateReferenceParticle();
-
-    void updateSpaceOrientation(const bool &move = false);
-    Vector_t TransformTo(const Vector_t &vec, const Vector_t &ori) const;
-    Vector_t TransformBack(const Vector_t &vec, const Vector_t &ori) const;
+    void pushParticles(const BorisPusher &pusher);
+    void updateReferenceParticle(const BorisPusher &pusher);
 
-    void kickReferenceParticle(const Vector_t &externalE, const Vector_t &externalB);
-    void writePhaseSpace(const long long step, const double &sposRef, bool psDump, bool statDump);
+    void writePhaseSpace(const long long step, bool psDump, bool statDump);
 
     /********** BEGIN AUTOPHSING STUFF **********/
     void updateRFElement(std::string elName, double maxPhi);
     void printRFPhases();
-    void handleAutoPhasing();
+    void saveCavityPhases();
+    void restoreCavityPhases();
     /************ END AUTOPHSING STUFF **********/
 
-    void handleOverlappingMonitors();
     void prepareSections();
 
-    double ptoEMeV(Vector_t p);
-
-    void bgf_main_collision_test();
     void timeIntegration1(BorisPusher & pusher);
-    void timeIntegration1_bgf(BorisPusher & pusher);
     void timeIntegration2(BorisPusher & pusher);
-    void timeIntegration2_bgf(BorisPusher & pusher);
     void selectDT();
     void changeDT();
     void emitParticles(long long step);
-    void computeExternalFields();
-    void handleBends();
-    void switchElements(double scaleMargin = 3.0);
-    void computeSpaceChargeFields();
+    void computeExternalFields(OrbitThreader &oth);
+    void computeSpaceChargeFields(unsigned long long step);
     void prepareOpalBeamlineSections();
     void dumpStats(long long step, bool psDump, bool statDump);
     void setOptionalVariables();
     bool hasEndOfLineReached();
-    void doSchottyRenormalization();
-    void setupSUV(bool updateReference = true);
     void handleRestartRun();
     void prepareEmission();
     void setTime();
-    void initializeBoundaryGeometry();
     void doBinaryRepartition();
-    void executeDefaultTracker();
-    void executeAMTSTracker();
-    void push(double h);
-    void kick(double h, bool avoidGammaCalc = false);
-    void computeExternalFields_AMTS();
-    void borisExternalFields(double h, bool isFirstSubstep, bool isLastSubstep);
-    double calcG(); // Time step chooser for adaptive variant
-    Vector_t calcMeanR() const;
-    Vector_t calcMeanP() const;
-    double pSqr(Vector_t p1, Vector_t p2);
-};
 
-inline double ParallelTTracker::pSqr(Vector_t p1, Vector_t p2) {
-  return p1[0]*p2[0] + p1[0]*p2[1] + p1[0]*p2[2] + p1[1]*p2[0] + p1[1]*p2[1] + p1[1]*p2[2] + p1[2]*p2[0] + p1[2]*p2[1] + p1[2]*p2[2];
-}
+    void transformBunch(const CoordinateSystemTrafo &trafo);
 
-inline double ParallelTTracker::ptoEMeV(Vector_t p) {
-    return (sqrt(dot(p, p) + 1.0) - 1.0) * itsBunch->getM() * 1e-6;
-}
+    void updateRefToLabCSTrafo(const BorisPusher &pusher);
+    void findStartPosition(const BorisPusher &pusher);
+    void autophaseCavities(const BorisPusher &pusher);
 
+    void evenlyDistributeParticles();
 
-inline void ParallelTTracker::visitBeamline(const Beamline &bl) {
-    itsBeamline_m.iterate(*dynamic_cast<BeamlineVisitor *>(this), false);
-}
+    static unsigned long long getMaxSteps(std::queue<unsigned long long> numSteps);
+
+    // std::ofstream logger_m;
+    // size_t loggingFrequency_m;
+};
 
 inline void ParallelTTracker::visitAlignWrapper(const AlignWrapper &wrap) {
-    itsOpalBeamline_m.visit(wrap, *this, itsBunch);
+    itsOpalBeamline_m.visit(wrap, *this, itsBunch_m);
 }
 
 inline void ParallelTTracker::visitBeamBeam(const BeamBeam &bb) {
-    itsOpalBeamline_m.visit(bb, *this, itsBunch);
+    itsOpalBeamline_m.visit(bb, *this, itsBunch_m);
 }
 
 
 inline void ParallelTTracker::visitCollimator(const Collimator &coll) {
-    itsOpalBeamline_m.visit(coll, *this, itsBunch);
+    itsOpalBeamline_m.visit(coll, *this, itsBunch_m);
 }
 
 
 inline void ParallelTTracker::visitCorrector(const Corrector &corr) {
-    itsOpalBeamline_m.visit(corr, *this, itsBunch);
+    itsOpalBeamline_m.visit(corr, *this, itsBunch_m);
 }
 
 
 inline void ParallelTTracker::visitDegrader(const Degrader &deg) {
-    itsOpalBeamline_m.visit(deg, *this, itsBunch);
+    itsOpalBeamline_m.visit(deg, *this, itsBunch_m);
 }
 
 
 inline void ParallelTTracker::visitDiagnostic(const Diagnostic &diag) {
-    itsOpalBeamline_m.visit(diag, *this, itsBunch);
+    itsOpalBeamline_m.visit(diag, *this, itsBunch_m);
 }
 
 
 inline void ParallelTTracker::visitDrift(const Drift &drift) {
-    itsOpalBeamline_m.visit(drift, *this, itsBunch);
+    itsOpalBeamline_m.visit(drift, *this, itsBunch_m);
 }
 
 
 inline void ParallelTTracker::visitLambertson(const Lambertson &lamb) {
-    itsOpalBeamline_m.visit(lamb, *this, itsBunch);
+    itsOpalBeamline_m.visit(lamb, *this, itsBunch_m);
 }
 
 
 inline void ParallelTTracker::visitMarker(const Marker &marker) {
-    itsOpalBeamline_m.visit(marker, *this, itsBunch);
+    itsOpalBeamline_m.visit(marker, *this, itsBunch_m);
 }
 
 
 inline void ParallelTTracker::visitMonitor(const Monitor &mon) {
-    itsOpalBeamline_m.visit(mon, *this, itsBunch);
+    itsOpalBeamline_m.visit(mon, *this, itsBunch_m);
 }
 
 
 inline void ParallelTTracker::visitMultipole(const Multipole &mult) {
-    itsOpalBeamline_m.visit(mult, *this, itsBunch);
+    itsOpalBeamline_m.visit(mult, *this, itsBunch_m);
 }
 
 inline void ParallelTTracker::visitProbe(const Probe &prob) {
-    itsOpalBeamline_m.visit(prob, *this, itsBunch);
+    itsOpalBeamline_m.visit(prob, *this, itsBunch_m);
 }
 
 
 inline void ParallelTTracker::visitRBend(const RBend &bend) {
-    itsOpalBeamline_m.visit(bend, *this, itsBunch);
+    itsOpalBeamline_m.visit(bend, *this, itsBunch_m);
+}
+
+inline void ParallelTTracker::visitRBend3D(const RBend3D &bend) {
+    itsOpalBeamline_m.visit(bend, *this, itsBunch_m);
 }
 
 
 inline void ParallelTTracker::visitRFCavity(const RFCavity &as) {
-    itsOpalBeamline_m.visit(as, *this, itsBunch);
+    itsOpalBeamline_m.visit(as, *this, itsBunch_m);
 }
 
 inline void ParallelTTracker::visitTravelingWave(const TravelingWave &as) {
-    itsOpalBeamline_m.visit(as, *this, itsBunch);
+    itsOpalBeamline_m.visit(as, *this, itsBunch_m);
 }
 
 
 inline void ParallelTTracker::visitRFQuadrupole(const RFQuadrupole &rfq) {
-    itsOpalBeamline_m.visit(rfq, *this, itsBunch);
+    itsOpalBeamline_m.visit(rfq, *this, itsBunch_m);
 }
 
 inline void ParallelTTracker::visitSBend(const SBend &bend) {
-    itsOpalBeamline_m.visit(bend, *this, itsBunch);
+    itsOpalBeamline_m.visit(bend, *this, itsBunch_m);
 }
 
 
 inline void ParallelTTracker::visitSeparator(const Separator &sep) {
-    itsOpalBeamline_m.visit(sep, *this, itsBunch);
+    itsOpalBeamline_m.visit(sep, *this, itsBunch_m);
 }
 
 
 inline void ParallelTTracker::visitSeptum(const Septum &sept) {
-    itsOpalBeamline_m.visit(sept, *this, itsBunch);
+    itsOpalBeamline_m.visit(sept, *this, itsBunch_m);
 }
 
 
 inline void ParallelTTracker::visitSolenoid(const Solenoid &solenoid) {
-    itsOpalBeamline_m.visit(solenoid, *this, itsBunch);
+    itsOpalBeamline_m.visit(solenoid, *this, itsBunch_m);
 }
 
+inline void ParallelTTracker::visitSource(const Source &source) {
+    itsOpalBeamline_m.visit(source, *this, itsBunch_m);
+}
 
 inline void ParallelTTracker::visitParallelPlate(const ParallelPlate &pplate) {
-    itsOpalBeamline_m.visit(pplate, *this, itsBunch);
+    itsOpalBeamline_m.visit(pplate, *this, itsBunch_m);
 }
 
 inline void ParallelTTracker::visitCyclotronValley(const CyclotronValley &cv) {
-    itsOpalBeamline_m.visit(cv, *this, itsBunch);
+    itsOpalBeamline_m.visit(cv, *this, itsBunch_m);
 }
 
 inline void ParallelTTracker::kickParticles(const BorisPusher &pusher) {
-    int localNum = itsBunch->getLocalNum();
-    for(int i = 0; i < localNum; ++i)
-        pusher.kick(itsBunch->R[i], itsBunch->P[i], itsBunch->Ef[i], itsBunch->Bf[i], itsBunch->dt[i]);
-    itsBunch->calcBeamParameters();
+    int localNum = itsBunch_m->getLocalNum();
+    for (int i = 0; i < localNum; ++i)
+        pusher.kick(itsBunch_m->R[i], itsBunch_m->P[i], itsBunch_m->Ef[i], itsBunch_m->Bf[i], itsBunch_m->dt[i]);
 }
 
-// BoundaryGeometry version of kickParticles function
-inline void ParallelTTracker::kickParticles(const BorisPusher &pusher, const int &flg) {
-    int localNum = itsBunch->getLocalNum();
-    for(int i = 0; i < localNum; ++i) {
-        if(itsBunch->TriID[i] == 0) { //TriID[i] will be 0 if particles don't collide the boundary before kick;
-            pusher.kick(itsBunch->R[i], itsBunch->P[i], itsBunch->Ef[i], itsBunch->Bf[i], itsBunch->dt[i]);
-        }
-    }
-    itsBunch->calcBeamParameters();
-}
-
-inline void ParallelTTracker::updateReferenceParticle() {
-    RefPartR_suv_m = itsBunch->get_rmean() * scaleFactor_m;
-    RefPartP_suv_m = itsBunch->get_pmean();
-
-    /* Update the position of the reference particle in ZXY-coordinates. The angle between the ZXY- and the SUV-coordinate
-     *  system is determined by the momentum of the reference particle. We calculate the momentum of the reference
-     *  particle by rotating the centroid momentum (= momentum of the reference particle in the SUV-coordinate system).
-     *  Then we push the reference particle with this momentum for half a time step.
-     */
-
-    double gamma = sqrt(1.0 + dot(RefPartP_suv_m, RefPartP_suv_m));
-
-    /* First update the momentum of the reference particle in zxy coordinate system, then update its position     */
-    RefPartP_zxy_m = dot(space_orientation_m, RefPartP_suv_m);
+inline void ParallelTTracker::pushParticles(const BorisPusher &pusher) {
+    itsBunch_m->switchToUnitlessPositions(true);
 
-    RefPartR_zxy_m += RefPartP_zxy_m * scaleFactor_m / (2. * gamma);
-    RefPartR_suv_m += RefPartP_suv_m * scaleFactor_m / (2. * gamma);
-
-}
-
-inline void ParallelTTracker::updateSpaceOrientation(const bool &move) {
-    /*
-       Update the position of the reference particle in
-       ZXY-coordinates. The angle between the ZXY- and the
-       SUV-coordinate system is determined by the momentum of the
-       reference particle. We calculate the momentum of the reference
-       particle by rotating the centroid momentum (= momentum of the
-       reference particle in the SUV-coordinate system). Then we push
-       the reference particle with this momentum for half a time step.
-     */
-    itsBunch->calcBeamParameters();
-    RefPartR_suv_m = itsBunch->get_rmean();
-    RefPartP_suv_m = itsBunch->get_pmean();
-
-    double AbsMomentum = sqrt(dot(RefPartP_suv_m, RefPartP_suv_m));
-    double AbsMomentumProj = sqrt(RefPartP_suv_m(0) * RefPartP_suv_m(0) + RefPartP_suv_m(2) * RefPartP_suv_m(2));
-    RefPartP_zxy_m *= AbsMomentum / sqrt(dot(RefPartP_zxy_m, RefPartP_zxy_m));
-
-    space_orientation_m(0, 0) = RefPartP_zxy_m(2) / AbsMomentumProj;
-    space_orientation_m(0, 1) = -RefPartP_zxy_m(0) * RefPartP_zxy_m(1) / (AbsMomentum * AbsMomentumProj);
-    space_orientation_m(0, 2) = RefPartP_zxy_m(0) / AbsMomentum;
-    space_orientation_m(1, 0) = 0.;
-    space_orientation_m(1, 1) = AbsMomentumProj / AbsMomentum;
-    space_orientation_m(1, 2) = RefPartP_zxy_m(1) / AbsMomentum;
-    space_orientation_m(2, 0) = -RefPartP_zxy_m(0) / AbsMomentumProj;
-    space_orientation_m(2, 1) = -RefPartP_zxy_m(2) * RefPartP_zxy_m(1) / (AbsMomentum * AbsMomentumProj);
-    space_orientation_m(2, 2) = RefPartP_zxy_m(2) / AbsMomentum;
-
-    Vector_t EulerAngles;
-
-    if(RefPartP_suv_m(2) < 1.0e-12) {
-        EulerAngles = Vector_t(0.0);
-    } else {
-        EulerAngles = Vector_t(-atan(RefPartP_suv_m(0) / RefPartP_suv_m(2)),          \
-                               -asin(RefPartP_suv_m(1) / AbsMomentum),    \
-                               0.0);
+    for (unsigned int i = 0; i < itsBunch_m->getLocalNum(); ++i) {
+        pusher.push(itsBunch_m->R[i], itsBunch_m->P[i], itsBunch_m->dt[i]);
     }
-
-    // Rotate the local coordinate system of all sections which are online
-    Vector_t smin(0.0), smax(0.0);
-    itsBunch->get_bounds(smin, smax);
-    itsOpalBeamline_m.updateOrientation(EulerAngles, RefPartR_suv_m, smin(2), smax(2));
-
-    itsBunch->rotateAbout(RefPartR_suv_m, RefPartP_suv_m);
-    if(move)       // move the bunch such that the new centroid location is at (0,0,z)
-        itsBunch->moveBy(Vector_t(-RefPartR_suv_m(0), -RefPartR_suv_m(1), 0.0));
+    itsBunch_m->switchOffUnitlessPositions(true);
 }
 
-inline Vector_t ParallelTTracker::TransformTo(const Vector_t &vec, const Vector_t &ori) const {
-
-    // Rotate to the the element's local coordinate system.
-    //
-    // 1) Rotate about the z axis by angle negative ori(2).
-    // 2) Rotate about the y axis by angle negative ori(0).
-    // 3) Rotate about the x axis by angle ori(1).
-
-    const double sina = sin(ori(0));
-    const double cosa = cos(ori(0));
-    const double sinb = sin(ori(1));
-    const double cosb = cos(ori(1));
-    const double sinc = sin(ori(2));
-    const double cosc = cos(ori(2));
-
-    Vector_t temp(0.0, 0.0, 0.0);
-
-    temp(0) = (cosa * cosc) * vec(0) + (cosa * sinc) * vec(1) - sina *        vec(2);
-    temp(1) = (-cosb * sinc - sina * sinb * cosc) * vec(0) + (cosb * cosc - sina * sinb * sinc) * vec(1) - cosa * sinb * vec(2);
-    temp(2) = (-sinb * sinc + sina * cosb * cosc) * vec(0) + (sinb * cosc + sina * cosb * sinc) * vec(1) + cosa * cosb * vec(2);
-
-    return temp;
-}
-
-inline Vector_t ParallelTTracker::TransformBack(const Vector_t &vec, const Vector_t &ori) const {
-
-    // Rotate out of the element's local coordinate system.
-    //
-    // 1) Rotate about the x axis by angle negative ori(1).
-    // 2) Rotate about the y axis by angle ori(0).
-    // 3) Rotate about the z axis by angle ori(3).
+inline
+unsigned long long ParallelTTracker::getMaxSteps(std::queue<unsigned long long> numSteps) {
+    unsigned long long totalNumSteps = 0;
 
-    const double sina = sin(ori(0));
-    const double cosa = cos(ori(0));
-    const double sinb = sin(ori(1));
-    const double cosb = cos(ori(1));
-    const double sinc = sin(ori(2));
-    const double cosc = cos(ori(2));
-
-    Vector_t temp(0.0, 0.0, 0.0);
-
-    temp(0) =  cosa * cosc * vec(0) + (-sina * sinb * cosc - cosb * sinc) * vec(1) + (sina * cosb * cosc - sinb * sinc) * vec(2);
-    temp(1) =  cosa * sinc * vec(0) + (-sina * sinb * sinc + cosb * cosc) * vec(1) + (sina * cosb * sinc + sinb * cosc) * vec(2);
-    temp(2) = -sina        * vec(0) + (-cosa * sinb) * vec(1) + (cosa * cosb) * vec(2);
-
-    return temp;
-}
-
-inline void ParallelTTracker::kickReferenceParticle(const Vector_t &externalE, const Vector_t &externalB) {
-    using Physics::c;
-
-    // track reference particle
-    Vector_t um = RefPartP_suv_m + 0.5 * itsReference.getQ() * itsBunch->getdT() / itsReference.getM() * c * externalE;
-    double gamma = sqrt(1.0 + dot(um, um));
-
-    double tmp = 0.5 * itsReference.getQ() * c * c * itsBunch->getdT() / (itsReference.getM() * gamma);
-    Vector_t a = tmp * externalB;
-
-    Vector_t s = um + tmp * cross(um, externalB);
-
-    tmp = 1.0 + dot(a, a);
-
-    um(0) = ((1.0 + a(0) * a(0))    * s(0) + (a(0) * a(1) + a(2)) * s(1) + (a(0) * a(2) - a(1)) * s(2)) / tmp;
-    um(1) = ((a(0) * a(1) - a(2)) * s(0) + (1.0 + a(1) * a(1)) * s(1) + (a(1) * a(2) + a(0)) * s(2)) / tmp;
-    um(2) = ((a(0) * a(2) + a(1)) * s(0) + (a(1) * a(2) - a(0)) * s(1) + (1.0 + a(2) * a(2)) * s(2)) / tmp;
-
-    RefPartP_suv_m = um + 0.5 * itsReference.getQ()  * itsBunch->getdT() / itsReference.getM() * c * externalE;
+    while (numSteps.size() > 0) {
+        totalNumSteps += numSteps.front();
+        numSteps.pop();
+    }
 
+    return totalNumSteps;
 }
 
-#endif // OPAL_ParallelTTracker_HH
+#endif // OPAL_ParallelTTracker_HH
\ No newline at end of file
diff --git a/src/Algorithms/bet/EnvelopeBunch.cpp b/src/Algorithms/bet/EnvelopeBunch.cpp
index b041e9ccf8aaa01c3313e3b3ad3fe0aeb2f2ac08..63b8874afa412e57b5b82e08e9537a28f7cd1c47 100644
--- a/src/Algorithms/bet/EnvelopeBunch.cpp
+++ b/src/Algorithms/bet/EnvelopeBunch.cpp
@@ -19,6 +19,7 @@
 #include "Algorithms/bet/math/rk.h"       // Runge-Kutta Integration
 
 #include "Algorithms/bet/EnvelopeBunch.h"
+#include "Utility/IpplTimings.h"
 
 #define USE_HOMDYN_SC_MODEL
 
@@ -501,7 +502,6 @@ void EnvelopeBunch::createBunch() {
     //size_t nSlices = (3 / 100.0 + 1.0) * numMySlices_m;
 
     size_t nSlices = getLocalNum();
-    LastSection.resize(nSlices);
 
     KR = std::unique_ptr<Vector_t[]>(new Vector_t[nSlices]);
     KT = std::unique_ptr<Vector_t[]>(new Vector_t[nSlices]);
@@ -1531,7 +1531,7 @@ Inform &EnvelopeBunch::slprint(Inform &os) {
     if(this->getTotalNum() != 0) {  // to suppress Nan's
         os << "* ************** S L B U N C H ***************************************************** " << endl;
         os << "* NSlices= " << this->getTotalNum() << " Qtot= " << Q_m << endl; //" [nC]  Qi= " << std::abs(qi_m) << " [C]" << endl;
-        os << "* Emean= " << get_meanEnergy() * 1e-6 << " [MeV]" << endl;
+        os << "* Emean= " << get_meanKineticEnergy() * 1e-6 << " [MeV]" << endl;
         os << "* dT= " << this->getdT() << " [s]" << endl;
         os << "* spos= " << this->zAvg() << " [m]" << endl;
 
diff --git a/src/Algorithms/bet/EnvelopeBunch.h b/src/Algorithms/bet/EnvelopeBunch.h
index 4022421fc081b37be91029884e090cfdb6acd285..eb806090462e272c6f7814da9b1c1028a54c37f7 100644
--- a/src/Algorithms/bet/EnvelopeBunch.h
+++ b/src/Algorithms/bet/EnvelopeBunch.h
@@ -79,10 +79,6 @@ public:
 
     bool isValid_m;
 
-    /// last em-field section
-    // PartBunch is created with 0 particles (all attribute containers empty)!
-    std::vector<long> LastSection;
-
     /// current profile of bunch (fit)
     std::unique_ptr<Profile> currentProfile_m;
 
@@ -162,7 +158,7 @@ public:
     /// returns the current time of the bunch
     double getT() { return t; }
     /// returns the mean energy
-    double get_meanEnergy() { return Eavg(); }
+    double get_meanKineticEnergy() { return Eavg(); }
     /// returns the energy spread
     double get_dEdt() { return dEdt_m; }
     /// returns vector with rms position
diff --git a/src/Algorithms/bet/math/svdfit.cpp b/src/Algorithms/bet/math/svdfit.cpp
index bb094d4e0cdb41b2a591fe9706a6c8b81820f7b3..01a64c3310edcf76acaa0ae6910dd81aaea4ca3b 100644
--- a/src/Algorithms/bet/math/svdfit.cpp
+++ b/src/Algorithms/bet/math/svdfit.cpp
@@ -131,7 +131,7 @@ static double pythag(double a, double b) {
 }
 
 static void svdcmp(double **a, int m, int n, double w[], double **v) {
-    int flag, i, its, j, jj, k, l, nm;
+    int flag, i, its, j, jj, k, l, nm = 0;
     double anorm, c, f, g, h, s, scale, x, y, z, *rv1;
 
     rv1 = vector(n + 1);
diff --git a/src/Algorithms/lomb.h b/src/Algorithms/lomb.h
index 6bfba6d1b6f4debb8a626b31bcd0481fc2074168..b4e7d708962cf1f5332ac99ace13617e833ebbb2 100644
--- a/src/Algorithms/lomb.h
+++ b/src/Algorithms/lomb.h
@@ -54,7 +54,7 @@ public:
                int amp);
 
     int avevar(std::vector<LOMB_TYPE> *data, double *ave, double *var);
-    double Signi(double *peak, int *nout, double *ofac);
+    double signi(double *peak, int *nout, double *ofac);
 
     int moment(std::vector<LOMB_TYPE> *indata, double *ave, double *adev,
                double *sdev, double *var, double *skew, double *curt);
diff --git a/src/Algorithms/lomb.hpp b/src/Algorithms/lomb.hpp
index 2214127f79487da596b55c0dd7b6d2b97ce96638..ed0bbd30a11e5b70a4463b9abed5d73b2aba692f 100644
--- a/src/Algorithms/lomb.hpp
+++ b/src/Algorithms/lomb.hpp
@@ -229,7 +229,7 @@ int LOMB_class::avevar(std::vector<LOMB_TYPE> *data, double *ave, double *var)
 
 
 
-double LOMB_class::Signi(double *peak, int *nout, double *ofac)
+double LOMB_class::signi(double *peak, int *nout, double *ofac)
 /*---------------------------------------------------------------------------*
  * Calculate the significance of a peak in an Lomb Periodogram
  * ===========================================================
diff --git a/src/Aperture/Aperture.cpp b/src/Aperture/Aperture.cpp
index 72ca0afb1c9dbc227dd07f76b091cf55130600a5..f1d1d83dc5369c313ddb140adbb66d99c9ab859c 100644
--- a/src/Aperture/Aperture.cpp
+++ b/src/Aperture/Aperture.cpp
@@ -650,14 +650,14 @@ void Aperture::calcul(Twiss::TLine::iterator i, A_row &a, int nslice, Twiss *tp)
             dat.erase(dat.begin(), dat.begin() + 4);
             ShapeBeamScreen = getShape(dat);
         } else {
-            vector<double> vec = elem.getApert();
+            auto vec = elem.getApert();
 
-            tolerance_x = vec[0];
-            tolerance_y = vec[1];
-            offsetx = vec[2];
-            offsety = vec[3];
-            vec.erase(vec.begin(), vec.begin() + 4);
-            ShapeBeamScreen = getShape(vec);
+            tolerance_x = vec.second[0];
+            tolerance_y = vec.second[1];
+            offsetx = vec.second[2];
+            offsety = vec.second[3];
+            vec.second.erase(vec.second.begin(), vec.second.begin() + 4);
+            ShapeBeamScreen = getShape(vec.second);
 
         }
     }
@@ -903,7 +903,7 @@ void Aperture::run() {
             } else {
                 OpalElement &elem = dynamic_cast<OpalElement &>(*Element::find(nam));
                 std::string Typ = elem.getBaseObject()->getOpalName();
-                if((elem.getApert().size() == 0) && (Typ != "MARKER")) i++;
+                if((elem.getApert().second.size() == 0) && (Typ != "MARKER")) i++;
                 else {
                     A_row row(*i, static_cast<int>(nslice));
                     i->accept(*this);
@@ -923,7 +923,7 @@ void Aperture::run() {
                 OpalElement &elem = dynamic_cast<OpalElement &>(*Element::find(nam));
                 std::string Typ = elem.getBaseObject()->getOpalName();
                 if(Typ == "MARKER") i++;
-                else if(elem.getApert().size() == 0) i++;
+                else if(elem.getApert().second.size() == 0) i++;
                 else {
                     A_row row(*i, static_cast<int>(nslice));
                     i->accept(*this);
@@ -1048,4 +1048,4 @@ Aperture::A_row &Aperture::findRow(const PlaceRep &place) {
     throw OpalException("Aperture::findRow()", "A_row \"" + os.str() +
                         "\" not found in twiss table \"" + getOpalName() + "\".");
 #endif
-}
+}
\ No newline at end of file
diff --git a/src/Aperture/CMakeLists.txt b/src/Aperture/CMakeLists.txt
index 5d16b1ce5d17d420a587a9c17ec1b4ae256f8fd3..7fa0697cf3057d83a980ec48857971d80e0ff47f 100644
--- a/src/Aperture/CMakeLists.txt
+++ b/src/Aperture/CMakeLists.txt
@@ -7,4 +7,11 @@ include_directories (
   ${CMAKE_CURRENT_SOURCE_DIR}
 )
 
-add_sources(${_SRCS})
+add_opal_sources(${_SRCS})
+
+set (HDRS
+    Aperture.h
+    Split.h
+)
+
+install (FILES ${HDRS} DESTINATION "${CMAKE_INSTALL_PREFIX}/include/Aperture")
\ No newline at end of file
diff --git a/src/Attributes/CMakeLists.txt b/src/Attributes/CMakeLists.txt
index 67dea42d2791ad2145a78578888835b2977cc5fa..a3a2f9615e25f3626f5612c8e89a4b9d7dc12997 100644
--- a/src/Attributes/CMakeLists.txt
+++ b/src/Attributes/CMakeLists.txt
@@ -1,21 +1,39 @@
 set (_SRCS
-  Attributes.cpp
-  Bool.cpp
-  BoolArray.cpp
-  Place.cpp
-  Range.cpp
-  Real.cpp
-  RealArray.cpp
-  Reference.cpp
-  opalstr.cpp
-  StringArray.cpp
-  TableRow.cpp
-  TokenList.cpp
-  TokenListArray.cpp
-  )
+    Attributes.cpp
+    Bool.cpp
+    BoolArray.cpp
+    Place.cpp
+    Range.cpp
+    Real.cpp
+    RealArray.cpp
+    Reference.cpp
+    opalstr.cpp
+    StringArray.cpp
+    TableRow.cpp
+    TokenList.cpp
+    TokenListArray.cpp
+)
 
 include_directories (
   ${CMAKE_CURRENT_SOURCE_DIR}
 )
 
-add_sources(${_SRCS})
+add_opal_sources(${_SRCS})
+
+set (HDRS
+    Attributes.h
+    BoolArray.h
+    Bool.h
+    opalstr.h
+    Place.h
+    Range.h
+    RealArray.h
+    Real.h
+    Reference.h
+    StringArray.h
+    TableRow.h
+    TokenListArray.h
+    TokenList.h
+)
+
+install (FILES ${HDRS} DESTINATION "${CMAKE_INSTALL_PREFIX}/include/Attributes")
\ No newline at end of file
diff --git a/src/BasicActions/CMakeLists.txt b/src/BasicActions/CMakeLists.txt
index 6b378528c78f5b51bbd2da3df9b6471f170d69f5..4d6e8d38fc72bdbda64725eaa78bcdd3b2fbb1ba 100644
--- a/src/BasicActions/CMakeLists.txt
+++ b/src/BasicActions/CMakeLists.txt
@@ -10,6 +10,7 @@ set (_SRCS
   Show.cpp
   Stop.cpp
   Quit.cpp
+  PSystem.cpp
   System.cpp
   Title.cpp
   Value.cpp
@@ -20,4 +21,25 @@ include_directories (
   ${CMAKE_CURRENT_SOURCE_DIR}
 )
 
-add_sources(${_SRCS})
+add_opal_sources(${_SRCS})
+
+set (HDRS
+    Call.h
+    DumpFields.h
+    Dump.h
+    Echo.h
+    Help.h
+    Option.h
+    PSystem.h
+    Quit.h
+    Save.h
+    Select.h
+    Show.h
+    Stop.h
+    System.h
+    Title.h
+    Value.h
+    What.h
+)
+
+install (FILES ${HDRS} DESTINATION "${CMAKE_INSTALL_PREFIX}/include/BasicActions")
\ No newline at end of file
diff --git a/src/BasicActions/DumpFields.cpp b/src/BasicActions/DumpFields.cpp
index f2efb0ef563be0aeec281b60595aa340c466b2b0..1ef88961bc10f98f379a6825bda9107bee0d48cb 100644
--- a/src/BasicActions/DumpFields.cpp
+++ b/src/BasicActions/DumpFields.cpp
@@ -1,27 +1,27 @@
-/* 
+/*
  *  Copyright (c) 2016, Chris Rogers
  *  All rights reserved.
- *  Redistribution and use in source and binary forms, with or without 
- *  modification, are permitted provided that the following conditions are met: 
+ *  Redistribution and use in source and binary forms, with or without
+ *  modification, are permitted provided that the following conditions are met:
  *  1. Redistributions of source code must retain the above copyright notice,
- *     this list of conditions and the following disclaimer. 
- *  2. Redistributions in binary form must reproduce the above copyright notice, 
- *     this list of conditions and the following disclaimer in the documentation 
+ *     this list of conditions and the following disclaimer.
+ *  2. Redistributions in binary form must reproduce the above copyright notice,
+ *     this list of conditions and the following disclaimer in the documentation
  *     and/or other materials provided with the distribution.
- *  3. Neither the name of STFC nor the names of its contributors may be used to 
- *     endorse or promote products derived from this software without specific 
+ *  3. Neither the name of STFC nor the names of its contributors may be used to
+ *     endorse or promote products derived from this software without specific
  *     prior written permission.
  *
- *  THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" 
- *  AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE 
- *  IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE 
- *  ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE 
- *  LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR 
- *  CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF 
- *  SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS 
- *  INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN 
- *  CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) 
- *  ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE 
+ *  THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
+ *  AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ *  IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ *  ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
+ *  LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+ *  CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+ *  SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
+ *  INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+ *  CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ *  ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
  *  POSSIBILITY OF SUCH DAMAGE.
  */
 
@@ -38,7 +38,7 @@
 
 std::unordered_set<DumpFields*> DumpFields::dumpsSet_m;
 
-std::string DumpFields::dumpfields_docstring = 
+std::string DumpFields::dumpfields_docstring =
 std::string("The \"DUMPFIELDS\" statement dumps a field map to a user-defined")+
 std::string(" field file, for checking that fields are read in correctly")+
 std::string(" from disk. The fields are written out on a Cartesian grid.");
@@ -137,11 +137,11 @@ void DumpFields::checkInt(double real, std::string name, double tolerance) {
     if (fabs(floor(real) - real) > tolerance) {
         throw OpalException("DumpFields::checkInt",
                             "Value for "+name+
-                            " should be an integer but a real value was found"); 
+                            " should be an integer but a real value was found");
     }
     if (floor(real) < 0.5) {
         throw OpalException("DumpFields::checkInt",
-                            "Value for "+name+" should be 1 or more"); 
+                            "Value for "+name+" should be 1 or more");
     }
 }
 
diff --git a/src/BasicActions/DumpFields.h b/src/BasicActions/DumpFields.h
index 175c3a1fbc550f496631b9d0ee672af9c5207f1c..739f482c5aec713facc6ac015baf561c244a1fb0 100644
--- a/src/BasicActions/DumpFields.h
+++ b/src/BasicActions/DumpFields.h
@@ -1,27 +1,27 @@
-/* 
+/*
  *  Copyright (c) 2016, Chris Rogers
  *  All rights reserved.
- *  Redistribution and use in source and binary forms, with or without 
- *  modification, are permitted provided that the following conditions are met: 
+ *  Redistribution and use in source and binary forms, with or without
+ *  modification, are permitted provided that the following conditions are met:
  *  1. Redistributions of source code must retain the above copyright notice,
- *     this list of conditions and the following disclaimer. 
- *  2. Redistributions in binary form must reproduce the above copyright notice, 
- *     this list of conditions and the following disclaimer in the documentation 
+ *     this list of conditions and the following disclaimer.
+ *  2. Redistributions in binary form must reproduce the above copyright notice,
+ *     this list of conditions and the following disclaimer in the documentation
  *     and/or other materials provided with the distribution.
- *  3. Neither the name of STFC nor the names of its contributors may be used to 
- *     endorse or promote products derived from this software without specific 
+ *  3. Neither the name of STFC nor the names of its contributors may be used to
+ *     endorse or promote products derived from this software without specific
  *     prior written permission.
  *
- *  THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" 
- *  AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE 
- *  IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE 
- *  ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE 
- *  LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR 
- *  CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF 
- *  SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS 
- *  INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN 
- *  CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) 
- *  ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE 
+ *  THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
+ *  AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ *  IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ *  ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
+ *  LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+ *  CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+ *  SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
+ *  INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+ *  CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ *  ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
  *  POSSIBILITY OF SUCH DAMAGE.
  */
 
@@ -46,10 +46,10 @@ class Component;
  *  actual field map writing (where we need to somehow let DumpFields know what
  *  the field maps are). So for each  DumpFields object created, we store in a
  *  set. When the execute() method is called, DumpFields builds a grid using
- *  the parsed information. 
+ *  the parsed information.
  *
  *  When the ParallelCyclotronTracker is about to start tracking, it calls
- *  writeFields method which loops over the static set of DumpFields and writes 
+ *  writeFields method which loops over the static set of DumpFields and writes
  *  each one. It is not the cleanest implementation, but I can't see a better
  *  way.
  *
diff --git a/src/BasicActions/Option.cpp b/src/BasicActions/Option.cpp
index 1d98312e0c7fedfcdb76d62b0410b17497247f62..297ef29ed9d7bde4c08acdf3571f85a94ad8055d 100644
--- a/src/BasicActions/Option.cpp
+++ b/src/BasicActions/Option.cpp
@@ -20,12 +20,14 @@
 #include "Attributes/Attributes.h"
 #include "Parser/FileStream.h"
 #include "Utilities/Options.h"
-#include "Utilities/Options.h"
-#include "Utilities/Random.h"
+#include "Utilities/ClassicRandom.h"
+#include "Utility/IpplInfo.h"
+
 #include <ctime>
 #include <iostream>
 #include <limits>
 #include <cstddef>
+
 extern Inform *gmsg;
 
 using namespace Options;
@@ -65,13 +67,14 @@ namespace {
         NLHS,
         CZERO,
         RNGTYPE,
-        SCHOTTKYCORR,
-        SCHOTTKYRENO,
         ENABLEHDF5,
         ASCIIDUMP,
         BOUNDPDESTROYFQ,
 	BEAMHALOBOUNDARY,
-	CLOTUNEONLY,
+        CLOTUNEONLY,
+        IDEALIZED,
+        LOGBENDTRAJECTORY,
+        VERSION,
         SIZE
     };
 }
@@ -80,37 +83,54 @@ namespace {
 Option::Option():
     Action(SIZE, "OPTION",
            "The \"OPTION\" statement defines OPAL execution options.") {
+
     itsAttr[ECHO] = Attributes::makeBool
                     ("ECHO", "If true, give echo of input", echo);
+
     itsAttr[INFO] = Attributes::makeBool
                     ("INFO", "If true, print information messages", info);
+
     itsAttr[TRACE] = Attributes::makeBool
                      ("TRACE", "If true, print execution trace", mtrace);
+
     itsAttr[VERIFY] = Attributes::makeBool
                       ("VERIFY", "If true, print warnings about assumptions", verify);
+
     itsAttr[WARN] = Attributes::makeBool
                     ("WARN", "If true, print warning messages", warn);
+
     itsAttr[SEED] = Attributes::makeReal
                     ("SEED", "The seed for the random generator, -1 will use time(0) as seed ");
+
     itsAttr[TELL] = Attributes::makeBool
                     ("TELL", "If true, print the current settings", false);
+
     itsAttr[PSDUMPFREQ] = Attributes::makeReal
                           ("PSDUMPFREQ", "The frequency to dump the phase space, i.e.dump data when step%psDumpFreq==0, its default value is 10.");
+
     itsAttr[STATDUMPFREQ] = Attributes::makeReal
                             ("STATDUMPFREQ", "The frequency to dump statistical data (e.g. RMS beam quantities), i.e. dump data when step%statDumpFreq == 0, its default value is 10.");
+
     itsAttr[PSDUMPEACHTURN] = Attributes::makeBool
                               ("PSDUMPEACHTURN", "If true, dump phase space after each turn ,only aviable for OPAL-cycl, its default value is false");
+
     itsAttr[SCSOLVEFREQ] = Attributes::makeReal
                            ("SCSOLVEFREQ", "The frequency to solve space charge fields. its default value is 1");
+
     itsAttr[MTSSUBSTEPS] = Attributes::makeReal("MTSSUBSTEPS", "How many small timesteps are inside the large timestep used in multiple time stepping (MTS) integrator");
+
     itsAttr[REMOTEPARTDEL] = Attributes::makeReal
       ("REMOTEPARTDEL", "Artifically delete the remote particle if its distance to the beam mass is larger than REMOTEPARTDEL times of the beam rms size, its default values is 0 (no delete) ",0.0);
+
     itsAttr[PSDUMPLOCALFRAME] = Attributes::makeBool
                                 ("PSDUMPLOCALFRAME", "If true, in local Cartesian frame, otherwise in global Cartesian frame, only aviable for OPAL-cycl, its default value is false");
+
     itsAttr[SPTDUMPFREQ] = Attributes::makeReal
                            ("SPTDUMPFREQ", "The frequency to dump single particle trajectory of particles with ID = 0 & 1, its default value is 1. ");
+
     itsAttr[REPARTFREQ] = Attributes::makeReal
                           ("REPARTFREQ", "The frequency to do particles repartition for better load balance between nodes,its default value is 10. ");
+
     itsAttr[REBINFREQ] = Attributes::makeReal
                          ("REBINFREQ", "The frequency to reset energy bin ID for all particles, its default value is 100. ");
 
@@ -131,6 +151,7 @@ Option::Option():
 
     itsAttr[PPDEBUG] = Attributes::makeBool
                        ("PPDEBUG", "If true, use special initial velocity distribution for parallel plate and print special debug output", ppdebug);
+
     itsAttr[SURFDUMPFREQ] =  Attributes::makeReal
                              ("SURFDUMPFREQ", "The frequency to dump surface-partcle interaction data, its default value is -1 (no dump). ");
 
@@ -140,16 +161,10 @@ Option::Option():
     itsAttr[RNGTYPE] =  Attributes::makeString
                         ("RNGTYPE", "RANDOM (default), Quasi-random number gernerators: HALTON, SOBOL, NIEDERREITER (Gsl ref manual 18.5)", rngtype);
 
-    itsAttr[SCHOTTKYCORR] =  Attributes::makeBool
-                                   ("SCHOTTKYCORR", "If set to true a Schottky correction to the charge is applied ", schottkyCorrection);
 
     itsAttr[CLOTUNEONLY] =  Attributes::makeBool
                                    ("CLOTUNEONLY", "If set to true stop after CLO and tune calculation ", cloTuneOnly);
 
-    itsAttr[SCHOTTKYRENO] =  Attributes::makeReal
-                                         ("SCHOTTKYRENO", "IF set to a value greater than 0.0 the Schottky correction scan is disabled and the value is used for charge renormalization ", schottkyRennormalization);
-
-
     itsAttr[NUMBLOCKS] = Attributes::makeReal
                           ("NUMBLOCKS", "Maximum number of vectors in the Krylov space (for RCGSolMgr). Default value is 0 and BlockCGSolMgr will be used.");
     itsAttr[RECYCLEBLOCKS] = Attributes::makeReal
@@ -167,7 +182,16 @@ Option::Option():
       ("BOUNDPDESTROYFQ", "The frequency to do boundp_destroy to delete lost particles. Default 10",10.0);
 
     itsAttr[BEAMHALOBOUNDARY] = Attributes::makeReal
-      ("BEAMHALOBOUNDARY", "Defines in therms of sigma where the halo starts Default 0.0",0.0);
+      ("BEAMHALOBOUNDARY", "Defines in therms of sigma where the halo starts. Default 0.0",0.0);
+
+    itsAttr[IDEALIZED] = Attributes::makeBool
+        ("IDEALIZED", "Using the hard edge model for the calculation of path length. Default: false", false);
+
+    itsAttr[LOGBENDTRAJECTORY] = Attributes::makeBool
+        ("LOGBENDTRAJECTORY", "Writing the trajectory of every bend to disk. Default: false", false);
+
+    itsAttr[VERSION] = Attributes::makeReal
+        ("VERSION", "Version of OPAL for which input file was written", 10000);
 
     FileStream::setEcho(echo);
     rangen.init55(seed);
@@ -200,17 +224,18 @@ Option::Option(const std::string &name, Option *parent):
     Attributes::setBool(itsAttr[PPDEBUG], ppdebug);
     Attributes::setReal(itsAttr[SURFDUMPFREQ], surfDumpFreq);
     Attributes::setBool(itsAttr[CZERO], cZero);
-    Attributes::setBool(itsAttr[SCHOTTKYCORR], schottkyCorrection);
     Attributes::setBool(itsAttr[CLOTUNEONLY], cloTuneOnly);
     Attributes::setString(itsAttr[RNGTYPE], std::string(rngtype));
-    Attributes::setReal(itsAttr[SCHOTTKYRENO], schottkyRennormalization);
     Attributes::setReal(itsAttr[NUMBLOCKS], numBlocks);
     Attributes::setReal(itsAttr[RECYCLEBLOCKS], recycleBlocks);
     Attributes::setReal(itsAttr[NLHS], nLHS);
     Attributes::setBool(itsAttr[ENABLEHDF5], enableHDF5);
     Attributes::setBool(itsAttr[ASCIIDUMP], asciidump);
-    Attributes::setReal(itsAttr[BOUNDPDESTROYFQ], 10);
-    Attributes::setReal(itsAttr[BEAMHALOBOUNDARY], 0);
+    Attributes::setReal(itsAttr[BOUNDPDESTROYFQ], boundpDestroyFreq);
+    Attributes::setReal(itsAttr[BEAMHALOBOUNDARY], beamHaloBoundary);
+    Attributes::setBool(itsAttr[IDEALIZED], idealized);
+    Attributes::setBool(itsAttr[LOGBENDTRAJECTORY], writeBendTrajectories);
+    Attributes::setReal(itsAttr[VERSION], version);
 }
 
 
@@ -238,6 +263,10 @@ void Option::execute() {
     csrDump = Attributes::getBool(itsAttr[CSRDUMP]);
     ppdebug = Attributes::getBool(itsAttr[PPDEBUG]);
     enableHDF5 = Attributes::getBool(itsAttr[ENABLEHDF5]);
+    version = Attributes::getReal(itsAttr[VERSION]);
+
+    IpplInfo::Info->on(info);
+    IpplInfo::Warn->on(warn);
 
     if(itsAttr[ASCIIDUMP]) {
         asciidump = Attributes::getBool(itsAttr[ASCIIDUMP]);
@@ -312,18 +341,6 @@ void Option::execute() {
         cZero = bool(Attributes::getBool(itsAttr[CZERO]));
     }
 
-    if(itsAttr[SCHOTTKYCORR]) {
-        schottkyCorrection = bool(Attributes::getBool(itsAttr[SCHOTTKYCORR]));
-    } else {
-        schottkyCorrection = false;
-    }
-
-    if(itsAttr[SCHOTTKYRENO]) {
-        schottkyRennormalization = double(Attributes::getReal(itsAttr[SCHOTTKYRENO]));
-    } else {
-        schottkyRennormalization = -1.0;
-    }
-
     if(itsAttr[RNGTYPE]) {
         rngtype = std::string(Attributes::getString(itsAttr[RNGTYPE]));
     } else {
@@ -337,6 +354,10 @@ void Option::execute() {
         beamHaloBoundary = 0;
     }
 
+    idealized = Attributes::getBool(itsAttr[IDEALIZED]);
+
+    writeBendTrajectories = Attributes::getBool(itsAttr[LOGBENDTRAJECTORY]);
+
     if(itsAttr[CLOTUNEONLY]) {
         cloTuneOnly = bool(Attributes::getBool(itsAttr[CLOTUNEONLY]));
     } else {
@@ -349,5 +370,4 @@ void Option::execute() {
     if(Attributes::getBool(itsAttr[TELL])) {
         *gmsg << "\nCurrent settings of options:\n" << *this << endl;
     }
-
-}
+}
\ No newline at end of file
diff --git a/src/BasicActions/Save.cpp b/src/BasicActions/Save.cpp
index d894a2f5528fed784f106152526c0419f7d6f223..21097730703bd96a412d53c56b9c4a11b18ef59b 100644
--- a/src/BasicActions/Save.cpp
+++ b/src/BasicActions/Save.cpp
@@ -34,10 +34,10 @@
 #include "Attributes/Attributes.h"
 #include "Utilities/OpalException.h"
 #include "Utilities/Options.h"
+#include "Utilities/Util.h"
 #include <fstream>
 #include <string>
-#include "config.h"
-#include "revision.h"
+#include "OPALconfig.h"
 
 extern Inform *gmsg;
 
@@ -161,8 +161,8 @@ void Save::execute() {
 
         std::string comchar = "// ";
 
-        os << comchar << "<OPAL Version " << PACKAGE_VERSION << " GIT version "
-           << GIT_VERSION << "  (c) PSI, http://amas.web.psi.ch"
+        os << comchar << "<OPAL Version " << PACKAGE_VERSION_STR << " GIT version "
+           << Util::getGitRevision() << "  (c) PSI, http://amas.web.psi.ch"
            << std::endl << ";" << std::endl ;
 
         os << comchar << "<Parameter definitions> ;" << std::endl ;
@@ -186,8 +186,8 @@ void Save::execute() {
         os << comchar << "</Special definitions> ;"
            << std::endl << ";" << std::endl ;
 
-        os << comchar << "<OPAL Version " << PACKAGE_VERSION << " GIT version "
-           << GIT_VERSION << "  (c) PSI, http://amas.web.psi.ch"
+        os << comchar << "<OPAL Version " << PACKAGE_VERSION_STR << " GIT version "
+           << Util::getGitRevision() << "  (c) PSI, http://amas.web.psi.ch"
            << std::endl << ";" << std::endl ;
     }
 }
@@ -195,4 +195,4 @@ void Save::execute() {
 
 void Save::parse(Statement &statement) {
     parseShortcut(statement);
-}
+}
\ No newline at end of file
diff --git a/src/BasicActions/System.cpp b/src/BasicActions/System.cpp
index eb46ceac2ff88d9d4c2d2a464c757dfa2856e48e..059caa2000fb133ebee802916430e34dff40e16c 100644
--- a/src/BasicActions/System.cpp
+++ b/src/BasicActions/System.cpp
@@ -20,9 +20,12 @@
 
 #include "Ippl.h"
 #include "Attributes/Attributes.h"
+#include "AbstractObjects/Object.h"
+#include "AbstractObjects/OpalData.h"
 
 #include <cstdlib>
-
+#include <boost/regex.hpp>
+#include <boost/algorithm/string.hpp>
 // Class System
 // ------------------------------------------------------------------------
 
@@ -48,15 +51,39 @@ System *System::clone(const std::string &name) {
     return new System(name, this);
 }
 
-/// node 0 is executing only
+
 void System::execute() {
-  if(Ippl::myNode() == 0) {
-    int res = system(Attributes::getString(itsAttr[0]).c_str());
-    if (res!=0)
-      ERRORMSG("System call failed" << endl);
-  }
+    if (Ippl::myNode() == 0) {
+        std::string command = Attributes::getString(itsAttr[0]);
+        boost::regex variablesRe("\\$\\$\\{([^\\}]+?)\\}");
+        boost::smatch match;
+        OpalData *OPAL = OpalData::getInstance();
+        while (boost::regex_search(command, match, variablesRe)) {
+            Object *object = 0;
+
+            std::string variableName = match[1];
+            boost::to_upper(variableName);
+            if ((object = OPAL->find(variableName)) == 0) {
+                ERRORMSG("SYSTEM: Could not replace $${" << match[1] << "}, "
+                         << "unknown variable" << endl);
+
+                std::string unknownReplacement = "\\\\$\\\\${" + match[1] + "}";
+                boost::regex unknownRe("\\$\\$\\{" + match[1] + "\\}");
+                command = boost::regex_replace(command, unknownRe, unknownReplacement);
+                continue;
+            }
+            std::ostringstream os;
+            object->printValue(os);
+            boost::regex variableRe("\\$\\$\\{" + match[1] + "\\}");
+            command = boost::regex_replace(command, variableRe, os.str());
+        }
+
+        int res = system(command.c_str());
+        if (res!=0)
+            ERRORMSG("SYSTEM call failed" << endl);
+    }
 }
 
 void System::parse(Statement &statement) {
     parseShortcut(statement);
-}
+}
\ No newline at end of file
diff --git a/src/CMakeLists.txt b/src/CMakeLists.txt
index 2e05334e1997b6bcb5b593591febb82e5b7266f1..cc59f45a575688ff5f77ed94b7b870e1d6e29f0e 100644
--- a/src/CMakeLists.txt
+++ b/src/CMakeLists.txt
@@ -1,8 +1,8 @@
 cmake_minimum_required (VERSION 2.8.10)
 set (DKS_VERSION \"1.0.0\")
 
-configure_file(config.h.in ${CMAKE_CURRENT_SOURCE_DIR}/config.h)
-configure_file(revision.h.in ${CMAKE_CURRENT_SOURCE_DIR}/revision.h)
+configure_file(config.h.in ${CMAKE_CURRENT_SOURCE_DIR}/OPALconfig.h)
+configure_file(revision.h.in ${CMAKE_CURRENT_SOURCE_DIR}/OPALrevision.h)
 
 set (CMAKE_CXX_FLAGS
     "${IPPL_CMAKE_CXX_FLAGS} -DUSEH5FEDV2 -DPARALLEL_IO ${CMAKE_CXX_FLAGS}"
@@ -24,15 +24,16 @@ IF(ENABLE_AMR_SOLVER)
     # FIXME Find a better solution!
     # We get otherwise a "undefined reference" to "getLevelBld()" and "probinit_"
     set (CBOXLIB -lcboxlib)
-    
+
     IF(NOT ${HOSTNAME_BASE} MATCHES "edison" AND NOT ${HOSTNAME_BASE} MATCHES "cori")
         set (CBOXLIB "-lmpi -lmpi_mpifh ${CBOXLIB}")
     ENDIF(NOT ${HOSTNAME_BASE} MATCHES "edison" AND NOT ${HOSTNAME_BASE} MATCHES "cori")
-    
+
 ENDIF(ENABLE_AMR_SOLVER)
 
-set (OPAL_SRC_DIR ${CMAKE_CURRENT_SOURCE_DIR})
-macro (add_sources)
+SET (OPAL_SRC_DIR ${CMAKE_CURRENT_SOURCE_DIR})
+SET (OPAL_SRCS )
+macro (ADD_OPAL_SOURCES)
     file (RELATIVE_PATH _relPath "${OPAL_SRC_DIR}" "${CMAKE_CURRENT_SOURCE_DIR}")
     foreach (_src ${ARGN})
         if (_relPath)
@@ -47,6 +48,21 @@ macro (add_sources)
     endif()
 endmacro()
 
+MACRO (ADD_OPAL_HEADERS )
+    FILE (RELATIVE_PATH _relPath "${OPAL_SRC_DIR}" "${CMAKE_CURRENT_SOURCE_DIR}")
+    FOREACH (_hdr ${ARGN})
+        IF (_relPath)
+            LIST (APPEND OPAL_HDRS "${_relPath}/${_hdr}")
+        ELSE ()
+            LIST (APPEND OPAL_HDRS "${_hdr}")
+        ENDIF ()
+    ENDFOREACH ()
+    IF (_relPath)
+        # propagate HDRS to parent directory
+        SET (OPAL_HDRS ${OPAL_HDRS} PARENT_SCOPE)
+    ENDIF ()
+ENDMACRO ()
+
 add_subdirectory (AbstractObjects)
 add_subdirectory (Algebra)
 add_subdirectory (Algorithms)
@@ -71,7 +87,8 @@ add_subdirectory (Track)
 add_subdirectory (Utilities)
 add_subdirectory (ValueDefinitions)
 
-add_sources (opal.cpp)
+ADD_OPAL_SOURCES(opal.cpp)
+ADD_OPAL_SOURCES(changes.cpp)
 
 include_directories ( BEFORE
     ${OPAL_SRC_DIR}
@@ -82,6 +99,7 @@ include_directories ( BEFORE
     ${GSL_INCLUDE_DIR}
     ${Trilinos_INCLUDE_DIRS}
     ${Trilinos_TPL_INCLUDE_DIRS}
+    ${IPPL_SOURCE_DIRS}
     ${CCSE_INCLUDE_DIRS}
     ${GTEST_INCLUDE_DIR}
 )
@@ -123,26 +141,28 @@ ELSE()
 ENDIF(${HOSTNAME_BASE} MATCHES "edison" OR ${HOSTNAME_BASE} MATCHES "cori")
 
 
-
 IF (ENABLE_DKS)
    set (OPAL_LIBS
        ${OPAL_LIBS}
-       ${DKS_LIBRARY_DIR}/libdks.a
-       )
+       ${DKS_LIBRARY_DIR}/libdks.a)
 ENDIF (ENABLE_DKS)
 
-add_library( OPALib ${OPAL_SRCS})
+add_library( OPALib ${OPAL_SRCS} )
 set_target_properties( OPALib PROPERTIES OUTPUT_NAME OPAL )
-target_link_libraries( OPALib ${OPAL_LIBS} ${Trilinos_LIBRARIES} ${Trilinos_TPL_LIBRARIES} ${CCSE_LIBRARIES} ${CBOXLIB} ${OTHER_CMAKE_EXE_LINKER_FLAGS} )
+target_link_libraries( OPALib ${OPAL_LIBS} ${Trilinos_LIBRARIES} ${CCSE_LIBRARIES} ${OTHER_CMAKE_EXE_LINKER_FLAGS} )
 
 add_executable( opal Main.cpp)
-target_link_libraries( opal OPALib ${OTHER_CMAKE_EXE_LINKER_FLAGS} ${CMAKE_DL_LIBS})
+target_link_libraries( opal OPALib ${OPAL_LIBS} ${Trilinos_LIBRARIES} ${Trilinos_TPL_LIBRARIES} -lgfortran ${CCSE_LIBRARIES} ${CBOXLIB} ${OTHER_CMAKE_EXE_LINKER_FLAGS} ${CMAKE_DL_LIBS})
 
 install (TARGETS ${TEST_EXE} RUNTIME DESTINATION "${CMAKE_INSTALL_PREFIX}/bin")
 install (TARGETS opal RUNTIME DESTINATION "${CMAKE_INSTALL_PREFIX}/bin")
 install (TARGETS OPALib DESTINATION "${CMAKE_INSTALL_PREFIX}/lib")
-install (FILES opal.h DESTINATION "${CMAKE_INSTALL_PREFIX}/include")
-install (FILES Utilities/OpalException.h DESTINATION "${CMAKE_INSTALL_PREFIX}/include/Utilities")
 
-set (OPAL_LIBS ${OPAL_LIBS} PARENT_SCOPE)
-set (OPAL_CXX_FLAGS ${CMAKE_CXX_FLAGS} PARENT_SCOPE)
+set (HDRS
+    config.h
+    opal.h
+    revision.h
+    changes.h
+)
+
+install (FILES ${HDRS} DESTINATION "${CMAKE_INSTALL_PREFIX}/include/src")
\ No newline at end of file
diff --git a/src/Classic/AbsBeamline/BeamBeam.cpp b/src/Classic/AbsBeamline/BeamBeam.cpp
index 06e5f4290692608d1a44a1e63a4df95ac7a9c6ce..e9db382e2ccd9a3ad7575a04927c97bc3434182a 100644
--- a/src/Classic/AbsBeamline/BeamBeam.cpp
+++ b/src/Classic/AbsBeamline/BeamBeam.cpp
@@ -48,19 +48,7 @@ void BeamBeam::accept(BeamlineVisitor &visitor) const {
     visitor.visitBeamBeam(*this);
 }
 
-bool BeamBeam::apply(const size_t &i, const double &t, double E[], double B[]) {
-    return false;
-}
-
-bool BeamBeam::apply(const size_t &i, const double &t, Vector_t &E, Vector_t &B) {
-    return false;
-}
-
-bool BeamBeam::apply(const Vector_t &R, const Vector_t &centroid, const double &t, Vector_t &E, Vector_t &B) {
-    return false;
-}
-
-void BeamBeam::initialise(PartBunch *bunch, double &startField, double &endField, const double &scaleFactor) {
+void BeamBeam::initialise(PartBunch *bunch, double &startField, double &endField) {
     RefPartBunch_m = bunch;
 }
 
@@ -78,4 +66,4 @@ void BeamBeam::getDimensions(double &zBegin, double &zEnd) const {
 
 ElementBase::ElementType BeamBeam::getType() const {
     return BEAMBEAM;
-}
+}
\ No newline at end of file
diff --git a/src/Classic/AbsBeamline/BeamBeam.h b/src/Classic/AbsBeamline/BeamBeam.h
index 0b4adca5ee8b08ccbee43ef9702f07f4819ec53e..50474491c57bfe1b8d36d880fdbf3621ce65fc61 100644
--- a/src/Classic/AbsBeamline/BeamBeam.h
+++ b/src/Classic/AbsBeamline/BeamBeam.h
@@ -63,13 +63,7 @@ public:
     //  Units are metres.
     virtual const Vector3D &getBunchDisplacement() const = 0;
 
-    virtual bool apply(const size_t &i, const double &t, double E[], double B[]);
-
-    virtual bool apply(const size_t &i, const double &t, Vector_t &E, Vector_t &B);
-
-    virtual bool apply(const Vector_t &R, const Vector_t &centroid, const double &t, Vector_t &E, Vector_t &B);
-
-    virtual void initialise(PartBunch *bunch, double &startField, double &endField, const double &scaleFactor);
+    virtual void initialise(PartBunch *bunch, double &startField, double &endField);
 
     virtual void finalise();
 
@@ -85,4 +79,4 @@ private:
     void operator=(const BeamBeam &);
 };
 
-#endif // CLASSIC_BeamBeam_HH
+#endif // CLASSIC_BeamBeam_HH
\ No newline at end of file
diff --git a/src/Classic/AbsBeamline/BeamlineVisitor.h b/src/Classic/AbsBeamline/BeamlineVisitor.h
index 51c29dca86ef48a11a9c2a6901e2a4172b74bd37..394f4bc65d922137fd7ce0bd33de72514ddc3162 100644
--- a/src/Classic/AbsBeamline/BeamlineVisitor.h
+++ b/src/Classic/AbsBeamline/BeamlineVisitor.h
@@ -50,6 +50,7 @@ class Offset;
 class Patch;
 class Probe;
 class RBend;
+class RBend3D;
 class RFCavity;
 class VariableRFCavity;
 class TravelingWave;
@@ -60,6 +61,7 @@ class Cyclotron;
 class Separator;
 class Septum;
 class Solenoid;
+class Source;
 class ParallelPlate;
 class CyclotronValley;
 class Stripper;
@@ -152,6 +154,9 @@ public:
     /// Apply the algorithm to a rectangular bend.
     virtual void visitRBend(const RBend &) = 0;
 
+    /// Apply the algorithm to a rectangular bend.
+    virtual void visitRBend3D(const RBend3D &);
+
     /// Apply the algorithm to a RF cavity.
     virtual void visitRFCavity(const RFCavity &) = 0;
 
@@ -179,6 +184,9 @@ public:
     /// Apply the algorithm to a solenoid.
     virtual void visitSolenoid(const Solenoid &) = 0;
 
+    /// Apply the algorithm to a source.
+    virtual void visitSource(const Source &) = 0;
+
     /// Apply the algorithm to a Beamline.
     virtual void visitBeamline(const Beamline &) = 0;
 
@@ -228,4 +236,9 @@ private:
     void operator=(const BeamlineVisitor &);
 };
 
-#endif // CLASSIC_BeamlineVisitor_HH
+inline
+void BeamlineVisitor::visitRBend3D(const RBend3D &) {
+
+}
+
+#endif // CLASSIC_BeamlineVisitor_HH
\ No newline at end of file
diff --git a/src/Classic/AbsBeamline/Bend.cpp b/src/Classic/AbsBeamline/Bend.cpp
index 1e8f37d8ba99ecf374030b6a1ac96f90f024ac20..f009ae96806e92f3a7a83e53db62e4138ace2697 100644
--- a/src/Classic/AbsBeamline/Bend.cpp
+++ b/src/Classic/AbsBeamline/Bend.cpp
@@ -23,8 +23,13 @@
 #include "Algorithms/PartBunch.h"
 #include "AbsBeamline/BeamlineVisitor.h"
 #include "Utilities/Options.h"
+#include "Utilities/Util.h"
 #include "Fields/Fieldmap.h"
 #include "AbstractObjects/OpalData.h"
+#include "Structure/MeshGenerator.h"
+
+#include "gsl/gsl_poly.h"
+
 #include <iostream>
 #include <fstream>
 
@@ -34,176 +39,147 @@ extern Inform *gmsg;
 // ------------------------------------------------------------------------
 
 Bend::Bend():
-    Component(),
+    BendBase(),
     messageHeader_m(" * "),
     pusher_m(),
-    fileName_m(""),
     fieldmap_m(NULL),
     fast_m(false),
-    angle_m(0.0),
-    aperture_m(0.0),
-    designEnergy_m(0.0),
+    // aperture_m(0.0),
     designRadius_m(0.0),
-    fieldAmplitude_m(0.0),
-    bX_m(0.0),
-    bY_m(0.0),
-    angleGreaterThanPi_m(false),
-    entranceAngle_m(0.0),
     exitAngle_m(0.0),
     fieldIndex_m(0.0),
-    elementEdge_m(0.0),
     startField_m(0.0),
     endField_m(0.0),
     reinitialize_m(false),
     recalcRefTraj_m(false),
-    length_m(0.0),
-    gap_m(0.0),
-    refTrajMapSize_m(0),
-    refTrajMapStepSize_m(0.0),
     entranceParameter1_m(0.0),
     entranceParameter2_m(0.0),
     entranceParameter3_m(0.0),
     exitParameter1_m(0.0),
     exitParameter2_m(0.0),
     exitParameter3_m(0.0),
-    xOriginEngeEntry_m(0.0),
-    zOriginEngeEntry_m(0.0),
+    entryFieldValues_m(NULL),
+    exitFieldValues_m(NULL),
+    entryFieldAccel_m(NULL),
+    exitFieldAccel_m(NULL),
     deltaBeginEntry_m(0.0),
     deltaEndEntry_m(0.0),
     polyOrderEntry_m(0),
     xExit_m(0.0),
     zExit_m(0.0),
-    xOriginEngeExit_m(0.0),
-    zOriginEngeExit_m(0.0),
     deltaBeginExit_m(0.0),
     deltaEndExit_m(0.0),
     polyOrderExit_m(0),
     cosEntranceAngle_m(1.0),
     sinEntranceAngle_m(0.0),
-    exitEdgeAngle_m(0.0),
-    cosExitAngle_m(1.0),
-    sinExitAngle_m(0.0) {
+    tanEntranceAngle_m(0.0),
+    tanExitAngle_m(0.0) {
 
     setElType(isDipole);
 
 }
 
 Bend::Bend(const Bend &right):
-    Component(right),
+    BendBase(right),
     messageHeader_m(" * "),
     pusher_m(right.pusher_m),
-    fileName_m(right.fileName_m),
     fieldmap_m(right.fieldmap_m),
     fast_m(right.fast_m),
-    angle_m(right.angle_m),
-    aperture_m(right.aperture_m),
-    designEnergy_m(right.designEnergy_m),
+    // aperture_m(right.aperture_m),
     designRadius_m(right.designRadius_m),
-    fieldAmplitude_m(right.fieldAmplitude_m),
-    bX_m(right.bX_m),
-    bY_m(right.bY_m),
-    angleGreaterThanPi_m(right.angleGreaterThanPi_m),
-    entranceAngle_m(right.entranceAngle_m),
     exitAngle_m(right.exitAngle_m),
     fieldIndex_m(right.fieldIndex_m),
-    elementEdge_m(right.elementEdge_m),
     startField_m(right.startField_m),
     endField_m(right.endField_m),
     reinitialize_m(right.reinitialize_m),
     recalcRefTraj_m(right.recalcRefTraj_m),
-    length_m(right.length_m),
-    gap_m(right.gap_m),
-    refTrajMapX_m(right.refTrajMapX_m),
-    refTrajMapY_m(right.refTrajMapY_m),
-    refTrajMapZ_m(right.refTrajMapZ_m),
-    refTrajMapSize_m(right.refTrajMapSize_m),
-    refTrajMapStepSize_m(right.refTrajMapStepSize_m),
     entranceParameter1_m(right.entranceParameter1_m),
     entranceParameter2_m(right.entranceParameter2_m),
     entranceParameter3_m(right.entranceParameter3_m),
     exitParameter1_m(right.exitParameter1_m),
     exitParameter2_m(right.exitParameter2_m),
     exitParameter3_m(right.exitParameter3_m),
-    xOriginEngeEntry_m(right.xOriginEngeEntry_m),
-    zOriginEngeEntry_m(right.zOriginEngeEntry_m),
+    entryFieldValues_m(NULL),
+    exitFieldValues_m(NULL),
+    entryFieldAccel_m(NULL),
+    exitFieldAccel_m(NULL),
     deltaBeginEntry_m(right.deltaBeginEntry_m),
     deltaEndEntry_m(right.deltaEndEntry_m),
     polyOrderEntry_m(right.polyOrderEntry_m),
     xExit_m(right.xExit_m),
     zExit_m(right.zExit_m),
-    xOriginEngeExit_m(right.xOriginEngeExit_m),
-    zOriginEngeExit_m(right.zOriginEngeExit_m),
     deltaBeginExit_m(right.deltaBeginExit_m),
     deltaEndExit_m(right.deltaEndExit_m),
     polyOrderExit_m(right.polyOrderExit_m),
     cosEntranceAngle_m(right.cosEntranceAngle_m),
     sinEntranceAngle_m(right.sinEntranceAngle_m),
-    exitEdgeAngle_m(right.exitEdgeAngle_m),
-    cosExitAngle_m(right.cosExitAngle_m),
-    sinExitAngle_m(right.sinExitAngle_m) {
+    tanEntranceAngle_m(right.tanEntranceAngle_m),
+    tanExitAngle_m(right.tanExitAngle_m) {
 
     setElType(isDipole);
 
 }
 
 Bend::Bend(const std::string &name):
-    Component(name),
+    BendBase(name),
     messageHeader_m(" * "),
     pusher_m(),
-    fileName_m(""),
     fieldmap_m(NULL),
     fast_m(false),
-    angle_m(0.0),
-    aperture_m(0.0),
-    designEnergy_m(0.0),
+    // aperture_m(0.0),
     designRadius_m(0.0),
-    fieldAmplitude_m(0.0),
-    bX_m(0.0),
-    bY_m(0.0),
-    angleGreaterThanPi_m(false),
-    entranceAngle_m(0.0),
     exitAngle_m(0.0),
     fieldIndex_m(0.0),
-    elementEdge_m(0.0),
     startField_m(0.0),
     endField_m(0.0),
     reinitialize_m(false),
     recalcRefTraj_m(false),
-    length_m(0.0),
-    gap_m(0.0),
-    refTrajMapSize_m(0),
-    refTrajMapStepSize_m(0.0),
     entranceParameter1_m(0.0),
     entranceParameter2_m(0.0),
     entranceParameter3_m(0.0),
     exitParameter1_m(0.0),
     exitParameter2_m(0.0),
     exitParameter3_m(0.0),
-    xOriginEngeEntry_m(0.0),
-    zOriginEngeEntry_m(0.0),
+    entryFieldValues_m(NULL),
+    exitFieldValues_m(NULL),
+    entryFieldAccel_m(NULL),
+    exitFieldAccel_m(NULL),
     deltaBeginEntry_m(0.0),
     deltaEndEntry_m(0.0),
     polyOrderEntry_m(0),
     xExit_m(0.0),
     zExit_m(0.0),
-    xOriginEngeExit_m(0.0),
-    zOriginEngeExit_m(0.0),
     deltaBeginExit_m(0.0),
     deltaEndExit_m(0.0),
     polyOrderExit_m(0),
     cosEntranceAngle_m(1.0),
     sinEntranceAngle_m(0.0),
-    exitEdgeAngle_m(0.0),
-    cosExitAngle_m(1.0),
-    sinExitAngle_m(0.0) {
+    tanEntranceAngle_m(0.0),
+    tanExitAngle_m(0.0) {
 
     setElType(isDipole);
 
 }
 
 Bend::~Bend() {
+    if (entryFieldAccel_m != NULL) {
+        for (unsigned int i = 0; i < 3u; ++ i) {
+            gsl_spline_free(entryFieldValues_m[i]);
+            gsl_spline_free(exitFieldValues_m[i]);
+            entryFieldValues_m[i] = NULL;
+            exitFieldValues_m[i] = NULL;
+        }
+        delete[] entryFieldValues_m;
+        delete[] exitFieldValues_m;
+        entryFieldValues_m = NULL;
+        exitFieldValues_m = NULL;
+
+        gsl_interp_accel_free(entryFieldAccel_m);
+        gsl_interp_accel_free(exitFieldAccel_m);
+        entryFieldAccel_m = NULL;
+        exitFieldAccel_m = NULL;
+    }
 }
-
 /*
  * OPAL-T Methods.
  * ===============
@@ -213,168 +189,138 @@ Bend::~Bend() {
  *  This function merely repackages the field arrays as type Vector_t and calls
  *  the equivalent method but with the Vector_t data types.
  */
-bool Bend::apply(const size_t &i, const double &t, double E[], double B[]) {
-
-    Vector_t Ev(0.0, 0.0, 0.0);
-    Vector_t Bv(0.0, 0.0, 0.0);
-    if(apply(RefPartBunch_m->R[i], RefPartBunch_m->get_rmean(), t, Ev, Bv))
-        return true;
-
-    E[0] = Ev(0);
-    E[1] = Ev(1);
-    E[2] = Ev(2);
-    B[0] = Bv(0);
-    B[1] = Bv(1);
-    B[2] = Bv(2);
-
-    return false;
-}
-
-bool Bend::apply(const size_t &i, const double &t, Vector_t &E, Vector_t &B) {
+bool Bend::apply(const size_t &i,
+                 const double &t,
+                 Vector_t &E,
+                 Vector_t &B) {
 
     if(designRadius_m > 0.0) {
 
         // Shift position to magnet frame.
-        Vector_t X = RefPartBunch_m->X[i];
-        X(2) += startField_m - elementEdge_m;
+        Vector_t X = RefPartBunch_m->R[i];
 
-        /*
-         * Add in transverse bend displacements. (ds is already
-         * accounted for.)
-         */
-        X(0) -= dx_m;
-        X(1) -= dy_m;
+        Vector_t bField(0.0);
+        if (!calculateMapField(X, bField)) {
 
-        // Get field from field map.
-        Vector_t eField(0.0, 0.0, 0.0);
-        Vector_t bField(0.0, 0.0, 0.0);
-        CalculateMapField(X, eField, bField);
-        bField *= fieldAmplitude_m;
+            B += fieldAmplitude_m * bField;
 
-        B(0) += bField(0);
-        B(1) += bField(1);
-        B(2) += bField(2);
+            return false;
+        }
 
+        return true;
     }
 
     return false;
 }
 
 bool Bend::apply(const Vector_t &R,
-                  const Vector_t &centroid,
-                  const double &t,
-                  Vector_t &E,
-                  Vector_t &B) {
+                 const Vector_t &P,
+                 const double &t,
+                 Vector_t &E,
+                 Vector_t &B) {
 
     if(designRadius_m > 0.0) {
 
-        int index = static_cast<int>
-            (std::floor((R(2) - startField_m) / refTrajMapStepSize_m));
-
-        if(index > 0 && index + 1 < refTrajMapSize_m) {
-
-            // Find indices for position in pre-computed central trajectory map.
-            double lever = (R(2) - startField_m) / refTrajMapStepSize_m - index;
-            double x = (1.0 - lever) * refTrajMapX_m.at(index)
-                + lever * refTrajMapX_m.at(index + 1);
-            double y = (1.0 - lever) * refTrajMapY_m.at(index)
-                + lever * refTrajMapY_m.at(index + 1);
-            double z = (1.0 - lever) * refTrajMapZ_m.at(index)
-                + lever * refTrajMapZ_m.at(index + 1);
-
-            // Adjust position relative to pre-computed central trajectory map.
-            Vector_t X(0.0, 0.0, 0.0);
-            X(0) = R(0) + x;
-            X(1) = R(1) + y;
-            X(2) = z;
+        Vector_t X = R;
 
-            Vector_t tempE(0.0, 0.0, 0.0);
-            Vector_t tempB(0.0, 0.0, 0.0);
-            Vector_t XInBendFrame = RotateToBendFrame(X);
+        Vector_t bField(0.0);
+        if (!calculateMapField(X, bField)) {
 
-            /*
-             * Add in transverse bend displacements. (ds is already
-             * accounted for.)
-             */
-            XInBendFrame(0) -= dx_m;
-            XInBendFrame(1) -= dy_m;
-
-            CalculateMapField(XInBendFrame, tempE, tempB);
-            tempB = fieldAmplitude_m * RotateOutOfBendFrame(tempB);
-
-            B(0) += tempB(0);
-            B(1) += tempB(1);
-            B(2) += tempB(2);
+            B += fieldAmplitude_m * bField;
 
+            return false;
         }
+
+        return true;
     }
 
     return false;
 
 }
 
-bool Bend::bends() const {
-    return true;
-}
+bool Bend::applyToReferenceParticle(const Vector_t &R,
+                                    const Vector_t &P,
+                                    const double &t,
+                                    Vector_t &E,
+                                    Vector_t &B) {
+    if(designRadius_m > 0.0) {
 
-void Bend::finalise() {
-    online_m = false;
-}
+        // Get field from field map.
+        Vector_t bField(0.0);
+        Vector_t X = R;// + Vector_t(0, 0, startField_m/* - elementEdge_m*/);
+        if (!calculateMapField(X, bField)) {
 
-void Bend::goOnline(const double &) {
+            B += fieldAmplitude_m * bField;
 
-    // Check if we need to reinitialize the bend field amplitude.
-    if(reinitialize_m) {
-        reinitialize_m = Reinitialize();
-        recalcRefTraj_m = false;
-    }
+            return false;
+        }
 
-    /*
-     * Always recalculate the reference trajectory on first call even
-     * if we do not reinitialize the bend. The reference trajectory
-     * has to be calculated at the same energy as the actual beam or
-     * we do not get accurate values for the magnetic field in the output
-     * file.
-     */
-    if(recalcRefTraj_m) {
-        double angleX = 0.0;
-        double angleY = 0.0;
-        CalculateRefTrajectory(angleX, angleY);
-        recalcRefTraj_m = false;
+        return true;
     }
 
-    online_m = true;
+    return false;
 }
 
-void Bend::getDimensions(double &sBegin, double &sEnd) const {
-    sBegin = startField_m;
-    sEnd = endField_m;
+void Bend::goOnline(const double &) {
+
+    // // Check if we need to reinitialize the bend field amplitude.
+    // if(reinitialize_m) {
+    //     reinitialize_m = reinitialize();
+    //     recalcRefTraj_m = false;
+    // }
+
+    // /*
+    //  * Always recalculate the reference trajectory on first call even
+    //  * if we do not reinitialize the bend. The reference trajectory
+    //  * has to be calculated at the same energy as the actual beam or
+    //  * we do not get accurate values for the magnetic field in the output
+    //  * file.
+    //  */
+    // if(recalcRefTraj_m) {
+    //     double angleX = 0.0;
+    //     double angleY = 0.0;
+    //     calculateRefTrajectory(angleX, angleY);
+    //     recalcRefTraj_m = false;
+    // }
+
+    online_m = true;
 }
 
 void Bend::initialise(PartBunch *bunch,
                        double &startField,
-                       double &endField,
-                       const double &scaleFactor) {
+                       double &endField) {
 
     Inform msg(messageHeader_m.c_str(), *gmsg);
 
-    if(InitializeFieldMap(msg)) {
-        retrieveDesignEnergy(startField);
+    if(initializeFieldMap(msg)) {
+        std::string name = Util::toUpper(getName()) + " ";
+        msg << level2
+            << "======================================================================\n"
+            << "===== " << std::left << std::setw(64) << std::setfill('=') << name << "\n"
+            << "======================================================================\n";
 
-        SetupPusher(bunch);
-        ReadFieldMap(msg);
-        SetupBendGeometry(msg, startField, endField);
+        setupPusher(bunch);
+        readFieldMap(msg);
+        setupBendGeometry(msg, startField, endField);
 
         double bendAngleX = 0.0;
         double bendAngleY = 0.0;
-        CalculateRefTrajectory(bendAngleX, bendAngleY);
+        calculateRefTrajectory(bendAngleX, bendAngleY);
         recalcRefTraj_m = true;
-        Print(msg, bendAngleX, bendAngleY);
+        print(msg, bendAngleX, bendAngleY);
 
         // Pass start and end of field to calling function.
         startField = startField_m;
         endField = endField_m;
 
+        startField_m -= elementEdge_m;
+        endField_m -= elementEdge_m;
+        elementEdge_m = 0.0;
+
+        msg << level2
+            << "======================================================================\n"
+            << "======================================================================\n"
+            << endl;
     } else {
         ERRORMSG("There is something wrong with your field map \""
                  << fileName_m
@@ -383,84 +329,7 @@ void Bend::initialise(PartBunch *bunch,
     }
 }
 
-double Bend::GetBendAngle() const {
-    return angle_m;
-}
-
-double Bend::GetBendRadius() const {
-    return designRadius_m;
-}
-
-double Bend::GetEffectiveCenter() const {
-    return elementEdge_m + designRadius_m * angle_m / 2.0;
-}
-
-double Bend::GetEffectiveLength() const {
-    return designRadius_m * angle_m;
-}
-
-std::string Bend::GetFieldMapFN() const {
-    return fileName_m;
-}
-
-double Bend::GetStartElement() const {
-    return elementEdge_m;
-}
-
-void Bend::SetAngleGreaterThanPiFlag(bool angleGreaterThanPi) {
-    angleGreaterThanPi_m = angleGreaterThanPi;
-}
-
-void Bend::SetAperture(double aperture) {
-    aperture_m = std::abs(aperture);
-}
-
-void Bend::SetBendAngle(double angle) {
-    angle_m = angle;
-}
-
-void Bend::SetBeta(double beta) {
-    Orientation_m(1) = beta;
-}
-
-void Bend::SetDesignEnergy(double energy) {
-    designEnergy_m = std::abs(energy);
-}
-
-void Bend::SetEntranceAngle(double entranceAngle) {
-    entranceAngle_m = entranceAngle;
-}
-
-void Bend::setExitAngle(double exitAngle) {
-    exitAngle_m = exitAngle;
-}
-
-void Bend::SetFieldAmplitude(double k0, double k0s) {
-    bY_m = k0;
-    bX_m = k0s;
-}
-
-void Bend::SetFieldMapFN(std::string fileName) {
-    fileName_m = fileName;
-}
-
-void Bend::SetFullGap(double gap) {
-    gap_m = std::abs(gap);
-}
-
-void Bend::SetK1(double k1) {
-    fieldIndex_m = k1;
-}
-
-void Bend::SetLength(double length) {
-    length_m = std::abs(length);
-}
-
-void Bend::SetRotationAboutZ(double rotation) {
-    Orientation_m(2) = rotation;
-}
-
-void Bend::AdjustFringeFields(double ratio) {
+void Bend::adjustFringeFields(double ratio) {
 
     double delta = std::abs(entranceParameter1_m - entranceParameter2_m);
     entranceParameter1_m = entranceParameter2_m - delta * ratio;
@@ -476,63 +345,49 @@ void Bend::AdjustFringeFields(double ratio) {
 
 }
 
-double Bend::CalculateBendAngle() {
+double Bend::calculateBendAngle() {
 
     const double mass = RefPartBunch_m->getM();
     const double gamma = designEnergy_m / mass + 1.0;
     const double betaGamma = sqrt(pow(gamma, 2.0) - 1.0);
-    const double beta = betaGamma / gamma;
+    // const double beta = betaGamma / gamma;
     const double deltaT = RefPartBunch_m->getdT();
-
+    const double cdt = Physics::c * deltaT;
     // Integrate through field for initial angle.
-    Vector_t X(0.0, 0.0, startField_m - elementEdge_m);
-    Vector_t P(0.0, 0.0, betaGamma);
+    Vector_t oldX;
+    Vector_t X = -deltaBeginEntry_m * Vector_t(tan(entranceAngle_m), 0.0, 1.0);
+    Vector_t P = betaGamma * Vector_t(sin(entranceAngle_m), 0.0, cos(entranceAngle_m));
     double deltaS = 0.0;
     double bendLength = endField_m - startField_m;
+    const Vector_t eField(0.0);
 
     while(deltaS < bendLength) {
-
-        X /= Vector_t(Physics::c * deltaT);
+        oldX = X;
+        X /= cdt;
         pusher_m.push(X, P, deltaT);
-        X *= Vector_t(Physics::c * deltaT);
+        X *= cdt;
 
-        Vector_t eField(0.0, 0.0, 0.0);
         Vector_t bField(0.0, 0.0, 0.0);
-        CalculateMapField(X, eField, bField);
+        calculateMapField(X, bField);
         bField = fieldAmplitude_m * bField;
 
-        X /= Vector_t(Physics::c * deltaT);
+        X /= cdt;
         pusher_m.kick(X, P, eField, bField, deltaT);
 
         pusher_m.push(X, P, deltaT);
-        X *= Vector_t(Physics::c * deltaT);
+        X *= cdt;
 
-        deltaS += deltaT * beta * Physics::c;
+        deltaS += euclidian_norm(X - oldX);
 
     }
 
-    double angle =  -atan2(P(0), P(2));
+    double angle =  -atan2(P(0), P(2)) + entranceAngle_m;
 
     return angle;
 
 }
 
-void Bend::CalcCentralField(const Vector_t &R,
-                             double deltaX,
-                             double angle,
-                             Vector_t &B) {
-
-    double nOverRho = fieldIndex_m / designRadius_m;
-    double expFactor = exp(-nOverRho * deltaX);
-    double bxBzFactor = expFactor * nOverRho * R(1);
-
-    B(0) = -bxBzFactor * cos(angle);
-    B(1) = expFactor * (1.0 - pow(nOverRho * R(1), 2.0) / 2.0);
-    B(2) = -bxBzFactor * sin(angle);
-
-}
-
-void Bend::CalcEngeFunction(double zNormalized,
+void Bend::calcEngeFunction(double zNormalized,
                              const std::vector<double> &engeCoeff,
                              int polyOrder,
                              double &engeFunc,
@@ -596,295 +451,238 @@ void Bend::CalcEngeFunction(double zNormalized,
     }
 }
 
-void Bend::CalcEntranceFringeField(const Vector_t &REntrance,
-                                    double deltaX,
-                                    Vector_t &B) {
-
-    double zNormalized = -REntrance(2) / gap_m;
-    double engeFunc = 0.0;
-    double engeFuncDeriv = 0.0;
-    double engeFuncSecDerivNorm = 0.0;
-
-    CalcEngeFunction(zNormalized,
-                     engeCoeffsEntry_m,
-                     polyOrderEntry_m,
-                     engeFunc,
-                     engeFuncDeriv,
-                     engeFuncSecDerivNorm);
-
-    double nOverRho = fieldIndex_m / designRadius_m;
-    double expFactor = exp(-nOverRho * deltaX);
-    double trigFactor = pow(nOverRho, 2.0) + engeFuncSecDerivNorm;
-
-    double bXEntrance = -engeFunc * nOverRho * expFactor* REntrance(1);
-    double bYEntrance = expFactor * engeFunc
-        * (1.0  - trigFactor * pow(REntrance(1), 2.0) / 2.0);
-    double bZEntrance = -expFactor * engeFuncDeriv * REntrance(1);
-
-    B(0) = bXEntrance * cosEntranceAngle_m - bZEntrance * sinEntranceAngle_m;
-    B(1) = bYEntrance;
-    B(2) = bXEntrance * sinEntranceAngle_m + bZEntrance * cosEntranceAngle_m;
-}
+Vector_t Bend::calcCentralField(const Vector_t &R,
+                                double deltaX) {
 
-void Bend::CalcExitFringeField(const Vector_t &RExit, double deltaX, Vector_t &B) {
-
-    double zNormalized = RExit(2) / gap_m;
-    double engeFunc = 0.0;
-    double engeFuncDeriv = 0.0;
-    double engeFuncSecDerivNorm = 0.0;
-    CalcEngeFunction(zNormalized,
-                     engeCoeffsExit_m,
-                     polyOrderExit_m,
-                     engeFunc,
-                     engeFuncDeriv,
-                     engeFuncSecDerivNorm);
-
-    double nOverRho = fieldIndex_m / designRadius_m;
-    double expFactor = exp(-nOverRho * deltaX);
-    double trigFactor = pow(nOverRho, 2.0) + engeFuncSecDerivNorm;
-
-    double bXExit = -engeFunc * nOverRho * expFactor* RExit(1);
-    double bYExit = expFactor * engeFunc
-        * (1.0 - trigFactor * pow(RExit(1), 2.0) / 2.0);
-    double bZExit = expFactor * engeFuncDeriv * RExit(1);
-
-    B(0) = bXExit * cosExitAngle_m - bZExit * sinExitAngle_m;
-    B(1) = bYExit;
-    B(2) = bXExit * sinExitAngle_m + bZExit * cosExitAngle_m;
-}
+    Vector_t B(0, 0, 0);
+    // double nOverRho = fieldIndex_m / designRadius_m;
+    // double expFactor = exp(-nOverRho * deltaX);
+    // double bxBzFactor = expFactor * nOverRho * R(1);
+    // Vector_t rotationCenter(-designRadius_m, R(1), 0.0);
+    // double cosangle = dot(R - rotationCenter, Vector_t(1, 0, 0)) / euclidian_norm(R - rotationCenter);
 
-void Bend::CalculateMapField(const Vector_t &R, Vector_t &E, Vector_t &B) {
+    // B(0) = -bxBzFactor * cosangle;
+    // B(1) = expFactor * (1.0 - pow(nOverRho * R(1), 2.0) / 2.0);
+    // B(2) = -bxBzFactor * sqrt(1 - std::pow(cosangle, 2));
 
-    E = Vector_t(0.0);
-    B = Vector_t(0.0);
+    B(1) = 1.0;
 
-    //    Vector_t REntrance(0.0, 0.0, 0.0);
-    //    Vector_t RExit(0.0, 0.0, 0.0);
-    //    if (IsPositionInEntranceField(R, REntrance)) {
-    //        CalcEntranceFringeField(REntrance, 0.0, B);
-    //    } else if (IsPositionInExitField(R, RExit)) {
-    //        CalcExitFringeField(RExit, 0.0, B);
-    //    } else {
-    //        CalcCentralField(R, 0.0, 0.0, B);
-    //    }
+    return B;
+}
 
-    double deltaXEntrance = 0.0;
-    double deltaXExit = 0.0;
-    bool inEntranceRegion = InMagnetEntranceRegion(R, deltaXEntrance);
-    bool inExitRegion = InMagnetExitRegion(R, deltaXExit);
+Vector_t Bend::calcEntranceFringeField(const Vector_t &R,
+                                       double deltaX) {
 
-    if(!inEntranceRegion && !inExitRegion) {
+    const CoordinateSystemTrafo toEntranceRegion(Vector_t(0, 0, entranceParameter2_m),
+                                                 Quaternion(0, 0, 1, 0));
+    const Vector_t Rprime = toEntranceRegion.transformTo(R);
 
-        double deltaX = 0.0;
-        double angle = 0.0;
-        if(InMagnetCentralRegion(R, deltaX, angle)) {
-            Vector_t REntrance(0.0, 0.0, 0.0);
-            Vector_t RExit(0.0, 0.0, 0.0);
-            if(IsPositionInEntranceField(R, REntrance))
-                CalcEntranceFringeField(REntrance, deltaX, B);
-            else if(IsPositionInExitField(R, RExit))
-                CalcExitFringeField(RExit, deltaX, B);
-            else
-                CalcCentralField(R, deltaX, angle, B);
+    Vector_t B(0.0);
 
-        }
+    if (Rprime(2) <= -entranceParameter3_m) {
+        B(1) = 1;
+    } else if (Rprime(2) < -entranceParameter1_m) {
+        double engeFunc = gsl_spline_eval(entryFieldValues_m[0], Rprime(2), entryFieldAccel_m);
+        double engeFuncDeriv = gsl_spline_eval(entryFieldValues_m[1], Rprime(2), entryFieldAccel_m);
+        double engeFuncSecDeriv = gsl_spline_eval(entryFieldValues_m[2], Rprime(2), entryFieldAccel_m);
+        // double nOverRho = fieldIndex_m / designRadius_m;
+        // double expFactor = exp(-nOverRho * deltaX);
+        // double trigFactor = pow(nOverRho, 2.0) + engeFuncSecDerivNorm;
 
-    } else if(inEntranceRegion && !inExitRegion) {
+        // double bXEntrance = -nOverRho * expFactor * Rprime(1) * engeFunc;
+        // double bYEntrance = (expFactor * engeFunc *
+        //                      (1.0  - 0.5 * trigFactor * pow(Rprime(1), 2.0)));
+        // double bZEntrance = -expFactor * Rprime(1) * engeFuncDeriv;
 
-        Vector_t REntrance(0.0, 0.0, 0.0);
-        if(IsPositionInEntranceField(R, REntrance)) {
-            CalcEntranceFringeField(REntrance, deltaXEntrance, B);
-        } else if(REntrance(2) > 0.0)
-            CalcCentralField(R, deltaXEntrance, 0.0, B);
+        // B(1) = (engeFunc *
+        //         (1.0 - 0.5 * engeFuncSecDerivNorm * pow(Rprime(1), 2.0)));
+        B(1) = (engeFunc - 0.5 * engeFuncSecDeriv * pow(Rprime(1), 2.0));
+        B(2) = engeFuncDeriv * Rprime(1);
+    }
 
-    } else if(!inEntranceRegion && inExitRegion) {
+    return toEntranceRegion.rotateFrom(B);
+}
 
-        Vector_t RExit(0.0, 0.0, 0.0);
-        if(IsPositionInExitField(R, RExit)) {
-            CalcExitFringeField(RExit, deltaXExit, B);
-        } else if(RExit(2) < 0.0)
-            CalcCentralField(R, deltaXExit, angle_m, B);
+Vector_t Bend::calcExitFringeField(const Vector_t &R,
+                                   double deltaX) {
 
-    } else if(inEntranceRegion && inExitRegion) {
+    const CoordinateSystemTrafo fromEndToExitRegion(Vector_t(0, 0, exitParameter2_m),
+                                                    Quaternion(1, 0, 0, 0));
+    const CoordinateSystemTrafo toExitRegion = (fromEndToExitRegion *
+                                                getBeginToEnd_local());
+    const Vector_t Rprime = toExitRegion.transformTo(R);
 
-        /*
-         * This is an unusual condition and should only happen with
-         * a sector magnet that bends more than 180 degrees. Here, we
-         * have the possibility that the particle sees both the
-         * entrance and exit fringe fields.
-         */
-        Vector_t BEntrance(0.0, 0.0, 0.0);
-        Vector_t REntrance(0.0, 0.0, 0.0);
-        if(IsPositionInEntranceField(R, REntrance))
-            CalcEntranceFringeField(REntrance, deltaXEntrance, BEntrance);
+    Vector_t B(0.0);
 
-        Vector_t BExit(0.0, 0.0, 0.0);
-        Vector_t RExit(0.0, 0.0, 0.0);
-        if(IsPositionInExitField(R, RExit))
-            CalcExitFringeField(RExit, deltaXExit, BExit);
+    if (Rprime(2) <= exitParameter1_m) {
+        B(1) = 1;
+    } else if (Rprime(2) < exitParameter3_m) {
+        double engeFunc = gsl_spline_eval(exitFieldValues_m[0], Rprime(2), exitFieldAccel_m);
+        double engeFuncDeriv = gsl_spline_eval(exitFieldValues_m[1], Rprime(2), exitFieldAccel_m);
+        double engeFuncSecDeriv = gsl_spline_eval(exitFieldValues_m[2], Rprime(2), exitFieldAccel_m);
+        // double nOverRho = fieldIndex_m / designRadius_m;
+        // double expFactor = exp(-nOverRho * deltaX);
+        // double trigFactor = pow(nOverRho, 2.0) + engeFuncSecDerivNorm;
 
-        B(0) = BEntrance(0) + BExit(0);
-        B(1) = BEntrance(1) + BExit(1);
-        B(2) = BEntrance(2) + BExit(2);
+        // double bXExit = -nOverRho * expFactor * Rprime(1) * engeFunc;
+        // double bYExit = (expFactor * engeFunc *
+        //                  (1.0 - 0.5 * trigFactor * pow(Rprime(1), 2.0)));
+        // double bZExit = expFactor * Rprime(1) * engeFuncDeriv;
 
+        // B(1) = (engeFunc *
+        //         (1.0 - 0.5 * engeFuncSecDerivNorm * pow(Rprime(1), 2.0)));
+        B(1) = (engeFunc - 0.5 * engeFuncSecDeriv * pow(Rprime(1), 2.0));
+        B(2) = engeFuncDeriv * Rprime(1);
     }
+    return toExitRegion.rotateFrom(B);
 }
 
-void Bend::CalculateRefTrajectory(double &angleX, double &angleY) {
-
-    const double mass = RefPartBunch_m->getM();
-    const double gamma = designEnergy_m / mass + 1.;
-    const double betaGamma = sqrt(gamma * gamma - 1.);
-    const double dt = RefPartBunch_m->getdT();
-
-    Vector_t X(0.0, 0.0, startField_m - elementEdge_m);
-    Vector_t P(0.0, 0.0, betaGamma);
+bool Bend::calculateMapField(const Vector_t &R, Vector_t &B) {
 
-    if(!refTrajMapX_m.empty())
-        refTrajMapX_m.clear();
-    if(!refTrajMapY_m.empty())
-        refTrajMapY_m.clear();
-    if(!refTrajMapZ_m.empty())
-        refTrajMapZ_m.clear();
+    B = Vector_t(0.0);
 
-    refTrajMapX_m.push_back(X(0));
-    refTrajMapY_m.push_back(X(1));
-    refTrajMapZ_m.push_back(X(2));
+    bool verticallyInside = (std::abs(R(1)) < 0.5 * gap_m);
+    bool horizontallyInside = false;
+    Vector_t rotationCenter(-designRadius_m * cosEntranceAngle_m, R(1), designRadius_m * sinEntranceAngle_m);
+
+    if(inMagnetCentralRegion(R)) {
+        if (verticallyInside) {
+            double deltaX = 0.0;//euclidian_norm(R - rotationCenter) - designRadius_m;
+            if (isPositionInEntranceField(R)) {
+                B = calcEntranceFringeField(R, deltaX);
+            } else if (isPositionInExitField(R)) {
+                B = calcExitFringeField(R, deltaX);
+            } else {
+                B = calcCentralField(R, deltaX);
+            }
 
-    refTrajMapStepSize_m = betaGamma / gamma * Physics::c * dt;
-    double deltaS = 0.0;
-    double bendLength = endField_m - startField_m;
+            return false;
+        }
+        return true;
+    }
 
-    while(deltaS < bendLength) {
+    Vector_t BEntrance(0.0), BExit(0.0);
+    verticallyInside = (std::abs(R(1)) < gap_m);
 
-        X /= Vector_t(Physics::c * dt);
-        pusher_m.push(X, P, dt);
-        X *= Vector_t(Physics::c * dt);
-
-        Vector_t eField(0.0, 0.0, 0.0);
-        Vector_t bField(0.0, 0.0, 0.0);
-        Vector_t XInBendFrame = RotateToBendFrame(X);
+    if (inMagnetEntranceRegion(R)) {
+        horizontallyInside = true;
+        if (verticallyInside) {
+            BEntrance = calcEntranceFringeField(R, R(0));
+        }
+    }
 
-        /*
-         * Add in transverse bend displacements. (ds is already
-         * accounted for.)
-         */
-        XInBendFrame(0) -= dx_m;
-        XInBendFrame(1) -= dy_m;
+    if (inMagnetExitRegion(R)) {
+        horizontallyInside = true;
+        if (verticallyInside) {
+            Vector_t Rprime = getBeginToEnd_local().transformTo(R);
 
-        CalculateMapField(XInBendFrame, eField, bField);
-        bField = fieldAmplitude_m * RotateOutOfBendFrame(bField);
+            BExit = calcExitFringeField(R, Rprime(0));
+        }
+    }
 
-        X /= Vector_t(Physics::c * dt);
-        pusher_m.kick(X, P, eField, bField, dt);
+    B = BEntrance + BExit;
 
-        pusher_m.push(X, P, dt);
-        X *= Vector_t(Physics::c * dt);
+    bool hitMaterial = (horizontallyInside && (!verticallyInside));
+    return hitMaterial;
+}
 
-        refTrajMapX_m.push_back(X(0));
-        refTrajMapY_m.push_back(X(1));
-        refTrajMapZ_m.push_back(X(2));
+void Bend::calculateRefTrajectory(double &angleX, double &angleY) {
 
-        deltaS += refTrajMapStepSize_m;
+    const double mass = RefPartBunch_m->getM();
+    const double gamma = designEnergy_m / mass + 1.;
+    const double betaGamma = sqrt(gamma * gamma - 1.);
+    const double dt = RefPartBunch_m->getdT();
 
+    std::ofstream trajectoryOutput;
+    if (Options::writeBendTrajectories && Ippl::myNode() == 0) {
+        trajectoryOutput.open("data/" + OpalData::getInstance()->getInputBasename() + "_" + getName() + "_traj.dat");
+        trajectoryOutput.precision(12);
+        trajectoryOutput << "# " << std::setw(18) << "s"
+                         << std::setw(20) << "x"
+                         << std::setw(20) << "z"
+                         << std::setw(20) << "By"
+                         << std::endl;
     }
 
-    refTrajMapSize_m = refTrajMapX_m.size();
-
-    if(std::abs(Orientation_m(2)) == Physics::pi / 2.0
-       || Orientation_m(2) == 3.0 * Physics::pi / 2.0)
-        angleX = 0.0;
-    else
-        angleX = -atan2(P(0), P(2));
-
-    if(Orientation_m(2) == 0.0
-       || Orientation_m(2) == Physics::pi)
-        angleY = 0.0;
-    else
-        angleY = atan2(P(1), P(2));
+    double zRotation = rotationZAxis_m;
+    Quaternion toStandard = Quaternion(cos(0.5 * zRotation), sin(0.5 * zRotation) * Vector_t(0, 0, -1));
 
+    Vector_t X = -deltaBeginEntry_m * Vector_t(tan(entranceAngle_m), 0.0, 1.0);
+    Vector_t P = betaGamma * Vector_t(sin(entranceAngle_m), 0.0, cos(entranceAngle_m));
 
-    std::ofstream traj(std::string("data/") + getName() + std::string("_traj.dat"));
-    traj.precision(8);
+    if(!refTrajMap_m.empty())
+        refTrajMap_m.clear();
 
-    double E1 = getEntranceAngle();
-    double cosE1 = cos(0.5 * E1), sinE1 = sin(0.5 * E1);
-    double zRotation = Orientation_m(2);
-    Quaternion toStandard = (Quaternion(cosE1, sinE1 * Vector_t(0, 1, 0)) *
-                             Quaternion(cos(0.5 * zRotation), sin(0.5 * zRotation) * Vector_t(0, 0, -1)));
-
-    X = Vector_t(0.0, 0.0, startField_m - elementEdge_m);
-    P = Vector_t(0.0, 0.0, betaGamma);
-
-    deltaS = 0.0;
+    refTrajMap_m.push_back(X);
 
+    const Vector_t eField(0.0);
+    const double stepSize = betaGamma / gamma * Physics::c * dt;
+    const double bendLength = endField_m - startField_m;
+    double deltaS = 0.0;
     while(deltaS < bendLength) {
 
         X /= Vector_t(Physics::c * dt);
         pusher_m.push(X, P, dt);
         X *= Vector_t(Physics::c * dt);
 
-        Vector_t eField(0.0, 0.0, 0.0);
         Vector_t bField(0.0, 0.0, 0.0);
-        Vector_t XInBendFrame = RotateToBendFrame(X);
+        Vector_t XInBendFrame = X;
+
+        calculateMapField(XInBendFrame, bField);
+        bField = fieldAmplitude_m * bField;
 
-        /*
-         * Add in transverse bend displacements. (ds is already
-         * accounted for.)
-         */
-        CalculateMapField(XInBendFrame, eField, bField);
-        bField = fieldAmplitude_m * RotateOutOfBendFrame(bField);
+        if (Options::writeBendTrajectories && Ippl::myNode() == 0) {
+            trajectoryOutput << std::setw(20) << deltaS + 0.5 * stepSize
+                             << std::setw(20) << X(0)
+                             << std::setw(20) << X(2)
+                             << std::setw(20) << bField(1)
+                             << std::endl;
+        }
 
         X /= Vector_t(Physics::c * dt);
         pusher_m.kick(X, P, eField, bField, dt);
-        Vector_t R = toStandard.rotate(X * Physics::c * dt);
-        traj << std::setw(16) << R(0)
-             << std::setw(16) << R(2)
-             << std::setw(16) << bField(1)
-             << std::endl;
-
 
         pusher_m.push(X, P, dt);
         X *= Vector_t(Physics::c * dt);
 
-        deltaS += refTrajMapStepSize_m;
+        refTrajMap_m.push_back(X);
 
+        deltaS += stepSize;
     }
 
+    angleX = -atan2(P(0), P(2)) + entranceAngle_m;
 }
 
-double Bend::EstimateFieldAdjustmentStep(double actualBendAngle,
+double Bend::estimateFieldAdjustmentStep(double actualBendAngle,
                                           double mass,
                                           double betaGamma) {
 
-    double amplitude1 = fieldAmplitude_m;
-    double bendAngle1 = actualBendAngle;
-
     // Estimate field adjustment step.
     double effectiveLength = angle_m * designRadius_m;
-    double fieldStep = (angle_m - bendAngle1) * betaGamma * mass / (2.0 * effectiveLength * Physics::c);
-    if(pow(fieldAmplitude_m * effectiveLength * Physics::c / (betaGamma * mass), 2.0) < 1.0)
-        fieldStep = (angle_m - bendAngle1) * betaGamma * mass / (2.0 * effectiveLength * Physics::c)
-            * std::sqrt(1.0 - pow(fieldAmplitude_m * effectiveLength * Physics::c / (betaGamma * mass), 2.0));
-
-    fieldStep *= amplitude1 / std::abs(amplitude1);
+    double tmp1 = betaGamma * mass / (2.0 * effectiveLength * Physics::c);
+    double tmp2 = pow(fieldAmplitude_m / tmp1, 2.0);
+    double fieldStep = (angle_m - actualBendAngle) * tmp1;
+    if (tmp2 < 1.0) {
+        fieldStep = (angle_m - actualBendAngle) * tmp1 * std::sqrt(1.0 - tmp2);
+    }
+    fieldStep *= fieldAmplitude_m / std::abs(fieldAmplitude_m);
 
     return fieldStep;
 
 }
 
-void Bend::FindBendEffectiveLength(double startField, double endField) {
+void Bend::findBendEffectiveLength(double startField, double endField) {
 
     /*
      * Use an iterative procedure to set the width of the
      * default field map for the defined field amplitude
      * and bend angle.
      */
-    SetEngeOriginDelta(0.0);
-    SetFieldCalcParam(false);
-    SetFieldBoundaries(startField, endField);
+    setEngeOriginDelta(0.0);
+    setFieldCalcParam();
+    setFieldBoundaries(startField, endField);
 
-    double actualBendAngle = CalculateBendAngle();
+    double actualBendAngle = calculateBendAngle();
     double error = std::abs(actualBendAngle - angle_m);
 
     if(error > 1.0e-6) {
@@ -899,26 +697,26 @@ void Bend::FindBendEffectiveLength(double startField, double endField) {
         double bendAngle1 = actualBendAngle;
 
         double delta2 = deltaStep;
-        SetEngeOriginDelta(delta2);
-        SetFieldCalcParam(false);
-        SetFieldBoundaries(startField, endField);
-        double bendAngle2 = CalculateBendAngle();
+        setEngeOriginDelta(delta2);
+        setFieldCalcParam();
+        setFieldBoundaries(startField, endField);
+        double bendAngle2 = calculateBendAngle();
 
         if(std::abs(bendAngle1) > std::abs(angle_m)) {
             while(std::abs(bendAngle2) > std::abs(angle_m)) {
                 delta2 += deltaStep;
-                SetEngeOriginDelta(delta2);
-                SetFieldCalcParam(false);
-                SetFieldBoundaries(startField, endField);
-                bendAngle2 = CalculateBendAngle();
+                setEngeOriginDelta(delta2);
+                setFieldCalcParam();
+                setFieldBoundaries(startField, endField);
+                bendAngle2 = calculateBendAngle();
             }
         } else {
             while(std::abs(bendAngle2) < std::abs(angle_m)) {
                 delta2 += deltaStep;
-                SetEngeOriginDelta(delta2);
-                SetFieldCalcParam(false);
-                SetFieldBoundaries(startField, endField);
-                bendAngle2 = CalculateBendAngle();
+                setEngeOriginDelta(delta2);
+                setFieldCalcParam();
+                setFieldBoundaries(startField, endField);
+                bendAngle2 = calculateBendAngle();
             }
         }
 
@@ -929,10 +727,10 @@ void Bend::FindBendEffectiveLength(double startField, double endField) {
         while(error > 1.0e-6 && iterations < 100) {
 
             delta = (delta1 + delta2) / 2.0;
-            SetEngeOriginDelta(delta);
-            SetFieldCalcParam(false);
-            SetFieldBoundaries(startField, endField);
-            double newBendAngle = CalculateBendAngle();
+            setEngeOriginDelta(delta);
+            setFieldCalcParam();
+            setFieldBoundaries(startField, endField);
+            double newBendAngle = calculateBendAngle();
 
             error = std::abs(newBendAngle - angle_m);
 
@@ -964,17 +762,22 @@ void Bend::FindBendEffectiveLength(double startField, double endField) {
     }
 }
 
-void Bend::FindBendStrength(double mass,
-                             double gamma,
-                             double betaGamma,
-                             double charge) {
+void Bend::findBendStrength(double mass,
+                            double gamma,
+                            double betaGamma,
+                            double charge) {
 
     /*
      * Use an iterative procedure to set the magnet field amplitude
      * for the defined bend angle.
      */
-    double actualBendAngle = CalculateBendAngle();
-    double fieldStep = EstimateFieldAdjustmentStep(actualBendAngle,
+    const double tolerance = 1e-7;
+    double actualBendAngle = calculateBendAngle();
+    double error = std::abs(actualBendAngle - angle_m) * Physics::rad2deg;
+    if (error < tolerance)
+        return;
+
+    double fieldStep = estimateFieldAdjustmentStep(actualBendAngle,
                                                    mass,
                                                    betaGamma);
     double amplitude1 = fieldAmplitude_m;
@@ -982,33 +785,38 @@ void Bend::FindBendStrength(double mass,
 
     double amplitude2 = fieldAmplitude_m + fieldStep;
     fieldAmplitude_m = amplitude2;
-    double bendAngle2 = CalculateBendAngle();
+    double bendAngle2 = calculateBendAngle();
 
     if(std::abs(bendAngle1) > std::abs(angle_m)) {
         while(std::abs(bendAngle2) > std::abs(angle_m)) {
+            amplitude1 = amplitude2;
+            bendAngle1 = bendAngle2;
+
             amplitude2 += fieldStep;
             fieldAmplitude_m = amplitude2;
-            bendAngle2 = CalculateBendAngle();
+            bendAngle2 = calculateBendAngle();
         }
     } else {
         while(std::abs(bendAngle2) < std::abs(angle_m)) {
+            amplitude1 = amplitude2;
+            bendAngle1 = bendAngle2;
+
             amplitude2 += fieldStep;
             fieldAmplitude_m = amplitude2;
-            bendAngle2 = CalculateBendAngle();
+            bendAngle2 = calculateBendAngle();
         }
     }
 
     // Now we should have the proper field amplitude bracketed.
     unsigned int iterations = 1;
-    double error = std::abs(actualBendAngle - angle_m);
-    while(error > 1.0e-6 && iterations < 100) {
+    while(error > tolerance && iterations < 100) {
 
         fieldAmplitude_m = (amplitude1 + amplitude2) / 2.0;
-        double newBendAngle = CalculateBendAngle();
+        double newBendAngle = calculateBendAngle();
 
-        error = std::abs(newBendAngle - angle_m);
+        error = std::abs(newBendAngle - angle_m) * Physics::rad2deg;
 
-        if(error > 1.0e-6) {
+        if(error > tolerance) {
 
             if(bendAngle1 - angle_m < 0.0) {
 
@@ -1035,70 +843,49 @@ void Bend::FindBendStrength(double mass,
     }
 }
 
-bool Bend::FindIdealBendParameters(double chordLength) {
+bool Bend::findIdealBendParameters(double chordLength) {
 
     double refMass = RefPartBunch_m->getM();
     double refGamma = designEnergy_m / refMass + 1.0;
     double refBetaGamma = sqrt(pow(refGamma, 2.0) - 1.0);
     double refCharge = RefPartBunch_m->getQ();
+    bool reinitialize = false;
 
     if(angle_m != 0.0) {
 
         if(angle_m < 0.0) {
             // Negative angle is a positive bend rotated 180 degrees.
+            entranceAngle_m = copysign(1, angle_m) * entranceAngle_m;
+            exitAngle_m = copysign(1, angle_m) * exitAngle_m;
             angle_m = std::abs(angle_m);
-            fieldIndex_m *= -1.0;
-            Orientation_m(2) += Physics::pi;
+            rotationZAxis_m += Physics::pi;
         }
         designRadius_m = chordLength / (2.0 * std::sin(angle_m / 2.0));
-        fieldAmplitude_m = (refCharge / std::abs(refCharge))
-            * refBetaGamma * refMass
-            / (Physics::c * designRadius_m);
-        return true;
-
-    } else if(bX_m == 0.0) {
-
-        // Negative angle is a positive bend rotated 180 degrees.
-        if((refCharge > 0.0 && bY_m < 0.0)
-           || (refCharge < 0.0 && bY_m > 0.0)) {
-            fieldIndex_m *= -1.0;
-            Orientation_m(2) += Physics::pi;
-        }
-
-        fieldAmplitude_m = refCharge * std::abs(bY_m / refCharge);
-        designRadius_m = std::abs(refBetaGamma * refMass / (Physics::c * fieldAmplitude_m));
-        double bendAngle = 2.0 * std::asin(chordLength / (2.0 * designRadius_m));
-
-        if(angleGreaterThanPi_m)
-            bendAngle = 2.0 * Physics::pi - bendAngle;
-
-        angle_m = bendAngle;
-        return false;
-
+        fieldAmplitude_m = ((refCharge / std::abs(refCharge)) *
+                            refBetaGamma * refMass /
+                            (Physics::c * designRadius_m));
+        reinitialize = true;
     } else {
 
-        Orientation_m(2) += atan2(bX_m, bY_m);
+        rotationZAxis_m += atan2(bX_m, bY_m);
         if(refCharge < 0.0) {
-            fieldIndex_m *= -1.0;
-            Orientation_m(2) -= Physics::pi;
+            rotationZAxis_m -= Physics::pi;
         }
 
-        fieldAmplitude_m = refCharge
-            * std::abs(sqrt(pow(bY_m, 2.0) + pow(bX_m, 2.0))
-                       / refCharge);
+        fieldAmplitude_m = (refCharge *
+                            std::abs(sqrt(pow(bY_m, 2.0) + pow(bX_m, 2.0)) / refCharge));
         designRadius_m = std::abs(refBetaGamma * refMass / (Physics::c * fieldAmplitude_m));
         double bendAngle = 2.0 * std::asin(chordLength / (2.0 * designRadius_m));
 
-        if(angleGreaterThanPi_m)
-            bendAngle = 2.0 * Physics::pi - bendAngle;
-
         angle_m = bendAngle;
 
-        return false;
+        reinitialize = false;
     }
+
+    return reinitialize;
 }
 
-void Bend::FindReferenceExitOrigin(double &x, double &z) {
+void Bend::findReferenceExitOrigin(double &x, double &z) {
 
     /*
      * Find x,z coordinates of reference trajectory as it passes exit edge
@@ -1119,7 +906,7 @@ void Bend::FindReferenceExitOrigin(double &x, double &z) {
     }
 }
 
-bool Bend::InitializeFieldMap(Inform &msg) {
+bool Bend::initializeFieldMap(Inform &msg) {
 
     fieldmap_m = Fieldmap::getFieldmap(fileName_m, fast_m);
 
@@ -1127,104 +914,63 @@ bool Bend::InitializeFieldMap(Inform &msg) {
         if(fileName_m != "1DPROFILE1-DEFAULT")
             return true;
         else
-            return SetupDefaultFieldMap(msg);
+            return setupDefaultFieldMap(msg);
 
     } else
         return false;
 
 }
 
-bool Bend::InMagnetCentralRegion(const Vector_t &R, double &deltaX, double &angle) {
+bool Bend::inMagnetCentralRegion(const Vector_t &R) const {
 
-    deltaX = sqrt(pow(R(2), 2.0) + pow(R(0) + designRadius_m, 2.0)) - designRadius_m;
-    if(std::abs(deltaX) <= aperture_m / 2.0) {
+    Vector_t rotationCenter(-designRadius_m * cosEntranceAngle_m, R(1), designRadius_m * sinEntranceAngle_m);
+    double distFromRotCenter = euclidian_norm(R - rotationCenter);
+    Vector_t Rprime = getBeginToEnd_local().transformTo(R);
+    Vector_t Rpprime = computeAngleTrafo_m.transformTo(R);
 
-        angle = atan2(R(2), R(0) + designRadius_m);
-        return true;
+    double effectiveAngle = fmod(Physics::two_pi - atan2(Rpprime(0), Rpprime(2)), Physics::two_pi);
 
-    } else
-        return false;
+    if (std::abs(distFromRotCenter - designRadius_m) < 0.5 * aperture_m.second[0] &&
+        effectiveAngle >= 0.0 && effectiveAngle < maxAngle_m) {
+        if (effectiveAngle < 0.5 * maxAngle_m) return R(2) >= 0.0;
+        return Rprime(2) < 0.0;
+    }
 
+    return false;
 }
 
-bool Bend::InMagnetEntranceRegion(const Vector_t &R, double &deltaX) {
-
-    if(std::abs(R(0)) <= aperture_m / 2.0) {
-
-        Vector_t RTransformed(0.0, R(1), 0.0);
-        RTransformed(0) = (R(0) - xOriginEngeEntry_m) * cosEntranceAngle_m
-            + (R(2) - zOriginEngeEntry_m) * sinEntranceAngle_m;
-        RTransformed(2) = -(R(0) - xOriginEngeEntry_m) * sinEntranceAngle_m
-            + (R(2) - zOriginEngeEntry_m) * cosEntranceAngle_m;
-
-        if(RTransformed(2) <= 0.0) {
-            deltaX = R(0);
-            return true;
-        } else
-            return false;
-
-    } else
-        return false;
+bool Bend::inMagnetEntranceRegion(const Vector_t &R) const {
 
+    return (R(2) >= entranceParameter1_m &&
+            R(2) < 0.0 &&
+            std::abs(R(0)) < aperture_m.second[0]);
 }
 
-bool Bend::InMagnetExitRegion(const Vector_t &R, double &deltaX) {
-
-    Vector_t RTransformed(0.0, R(1), 0.0);
-    RTransformed(0) = (R(0) - xExit_m) * cosExitAngle_m
-        + (R(2) - zExit_m) * sinExitAngle_m;
-    RTransformed(2) = -(R(0) - xExit_m) * sinExitAngle_m
-        + (R(2) - zExit_m) * cosExitAngle_m;
+bool Bend::inMagnetExitRegion(const Vector_t &R) const {
 
-    if(RTransformed(2) >= 0.0) {
+    Vector_t Rprime = getBeginToEnd_local().transformTo(R);
 
-        deltaX = (R(0) - xExit_m) * cos(angle_m)
-            + (R(2) - zExit_m) * sin(angle_m);
-        if(std::abs(deltaX) <= aperture_m / 2.0)
-            return true;
-        else
-            return false;
-
-    } else
-        return false;
+    return (Rprime(2) >= 0 &&
+            Rprime(2) < exitParameter3_m &&
+            std::abs(Rprime(0)) < aperture_m.second[0]);
 }
 
-bool Bend::IsPositionInEntranceField(const Vector_t &R, Vector_t &REntrance) {
-    if (polyOrderEntry_m < 0)
-        return false;
-
-    REntrance(1) = R(1);
+bool Bend::isPositionInEntranceField(const Vector_t &R) const {
 
-    REntrance(0) = (R(0) - xOriginEngeEntry_m) * cosEntranceAngle_m
-        + (R(2) - zOriginEngeEntry_m) * sinEntranceAngle_m;
-    REntrance(2) = -(R(0) - xOriginEngeEntry_m) * sinEntranceAngle_m
-        + (R(2) - zOriginEngeEntry_m) * cosEntranceAngle_m;
-
-    if(REntrance(2) >= -deltaBeginEntry_m && REntrance(2) <= deltaEndEntry_m)
-        return true;
-    else
-        return false;
+    return (polyOrderEntry_m >= 0 &&
+            R(2) >= entranceParameter1_m &&
+            R(2) < entranceParameter3_m);
 }
 
-bool Bend::IsPositionInExitField(const Vector_t &R, Vector_t &RExit) {
-    if (polyOrderExit_m < 0)
-        return false;
-
-    RExit(1) = R(1);
-
-    RExit(0) = (R(0) - xOriginEngeExit_m) * cosExitAngle_m
-        + (R(2) - zOriginEngeExit_m) * sinExitAngle_m;
-    RExit(2) = -(R(0) - xOriginEngeExit_m) * sinExitAngle_m
-        + (R(2) - zOriginEngeExit_m) * cosExitAngle_m;
-
-    if(RExit(2) >= -deltaBeginExit_m && RExit(2) <= deltaEndExit_m)
-        return true;
-    else
-        return false;
+bool Bend::isPositionInExitField(const Vector_t &R) const {
+    Vector_t Rprime = getBeginToEnd_local().transformTo(R);
 
+    return (polyOrderExit_m >= 0 &&
+            Rprime(2) >= exitParameter1_m &&
+            Rprime(2) < exitParameter3_m);
 }
 
-void Bend::Print(Inform &msg, double bendAngleX, double bendAngleY) {
+void Bend::print(Inform &msg, double bendAngleX, double bendAngleY) {
     msg << level2 << "\n"
         << "Start of field map:      "
         << startField_m
@@ -1241,7 +987,7 @@ void Bend::Print(Inform &msg, double bendAngleX, double bendAngleY) {
     msg << "\n"
         << "Reference Trajectory Properties"
         << "\n"
-        << "==============================="
+        << "======================================================================"
         << "\n\n";
     msg << "Bend angle magnitude:    "
         << angle_m
@@ -1272,7 +1018,7 @@ void Bend::Print(Inform &msg, double bendAngleX, double bendAngleY) {
     msg << "\n"
         << "Bend Field and Rotation Properties"
         << "\n"
-        << "=================================="
+        << "======================================================================"
         << "\n\n";
     msg << "Field amplitude:         "
         << fieldAmplitude_m
@@ -1281,22 +1027,10 @@ void Bend::Print(Inform &msg, double bendAngleX, double bendAngleY) {
     msg << "Field index:  "
         << fieldIndex_m
         << "\n";
-    msg << "Rotation about x axis:   "
-        << Orientation_m(1)
-        << " rad ("
-        << Orientation_m(1) * 180.0 / Physics::pi
-        << " degrees)"
-        << "\n";
-    msg << "Rotation about y axis:   "
-        << Orientation_m(0)
-        << " rad ("
-        << Orientation_m(0) * 180.0 / Physics::pi
-        << " degrees)"
-        << "\n";
     msg << "Rotation about z axis:   "
-        << Orientation_m(2)
+        << rotationZAxis_m
         << " rad ("
-        << Orientation_m(2) * 180.0 / Physics::pi
+        << rotationZAxis_m * 180.0 / Physics::pi
         << " degrees)"
         << "\n";
     msg << "\n"
@@ -1315,124 +1049,135 @@ void Bend::Print(Inform &msg, double bendAngleX, double bendAngleY) {
         << " rad ("
         << bendAngleY * 180.0 / Physics::pi
         << " degrees) in y plane"
-        << "\n" << endl;
+        << "\n";
+
+    if(fileName_m == "1DPROFILE1-DEFAULT") {
+        msg << "\n"
+            << "Effective Field Map\n"
+            << "======================================================================\n"
+            << "\n"
+            << "1DProfile1 " << polyOrderEntry_m << " " << polyOrderExit_m << " " << gap_m * 100 << "\n"
+            << entranceParameter1_m * 100 << " " << entranceParameter2_m * 100 << " " << entranceParameter3_m * 100 << " 0\n"
+            << exitParameter1_m * 100 << " " << exitParameter2_m * 100 << " " << exitParameter3_m * 100 << " 0\n";
+        for (auto coef: engeCoeffsEntry_m) {
+            msg << coef << "\n";
+        }
+        for (auto coef: engeCoeffsExit_m) {
+            msg << coef << "\n";
+        }
+    }
+
+    msg << endl;
 }
 
-void Bend::ReadFieldMap(Inform &msg) {
+void Bend::readFieldMap(Inform &msg) {
     msg << level2 << getName() << " using file ";
     fieldmap_m->getInfo(&msg);
 
     Fieldmap::readMap(fileName_m);
-    fieldmap_m->Get1DProfile1EntranceParam(entranceParameter1_m,
+    fieldmap_m->get1DProfile1EntranceParam(entranceParameter1_m,
                                            entranceParameter2_m,
                                            entranceParameter3_m);
-    fieldmap_m->Get1DProfile1ExitParam(exitParameter1_m,
+    fieldmap_m->get1DProfile1ExitParam(exitParameter1_m,
                                        exitParameter2_m,
                                        exitParameter3_m);
-    SetGapFromFieldMap();
-    fieldmap_m->Get1DProfile1EngeCoeffs(engeCoeffsEntry_m,
+    setGapFromFieldMap();
+    fieldmap_m->get1DProfile1EngeCoeffs(engeCoeffsEntry_m,
                                         engeCoeffsExit_m);
     polyOrderEntry_m = engeCoeffsEntry_m.size() - 1;
     polyOrderExit_m = engeCoeffsExit_m.size() - 1;
 
-}
-
-bool Bend::Reinitialize() {
+    double stepSize = Physics::c * 1e-12;
+    double entryLength = std::abs(entranceParameter3_m - entranceParameter1_m);
+    unsigned int numStepsEntry = std::ceil(entryLength / stepSize) + 3;
+    double stepSizeEntry = entryLength / (numStepsEntry - 3);
+    std::vector<double> zvalsEntry(numStepsEntry);
+    std::vector<std::vector<double> > fieldValuesEntry(3);
+
+    double exitLength = std::abs(exitParameter3_m - exitParameter1_m);
+    unsigned int numStepsExit = std::ceil(exitLength / stepSize) + 3;
+    double stepSizeExit = exitLength / (numStepsExit - 3);
+    std::vector<double> zvalsExit(numStepsExit);
+    std::vector<std::vector<double> > fieldValuesExit(3);
+
+    entryFieldValues_m = new gsl_spline*[3];
+    exitFieldValues_m = new gsl_spline*[3];
+    entryFieldAccel_m = gsl_interp_accel_alloc();
+    exitFieldAccel_m = gsl_interp_accel_alloc();
+
+    for (unsigned int i = 0; i < 3u; ++ i) {
+        fieldValuesEntry[i].resize(numStepsEntry);
+        fieldValuesExit[i].resize(numStepsExit);
+
+        entryFieldValues_m[i] = gsl_spline_alloc(gsl_interp_cspline, numStepsEntry);
+        exitFieldValues_m[i] = gsl_spline_alloc(gsl_interp_cspline, numStepsExit);
+    }
 
-    designEnergy_m = RefPartBunch_m->get_meanEnergy() * 1.0e6;
-    SetBendStrength();
-    double bendAngleX = 0.0;
-    double bendAngleY = 0.0;
-    CalculateRefTrajectory(bendAngleX, bendAngleY);
+    for (unsigned int j = 0; j < numStepsEntry; ++ j) {
+        if (j == 0) {
+            zvalsEntry[j] = -entranceParameter3_m - stepSizeEntry;
+        } else {
+            zvalsEntry[j] = zvalsEntry[j - 1] + stepSizeEntry;
+        }
+        calcEngeFunction(zvalsEntry[j] / gap_m,
+                         engeCoeffsEntry_m,
+                         polyOrderEntry_m,
+                         fieldValuesEntry[0][j],
+                         fieldValuesEntry[1][j],
+                         fieldValuesEntry[2][j]);
+        fieldValuesEntry[2][j] *= fieldValuesEntry[0][j];
+    }
 
-    INFOMSG(level2 << "Bend design energy changed to: "
-            << designEnergy_m * 1.0e-6
-            << " MeV"
-            << endl);
-    Print(*Ippl::Info, bendAngleX, bendAngleY);
+    for (unsigned int j = 0; j < numStepsExit; ++ j) {
+        if (j == 0) {
+            zvalsExit[j] = exitParameter1_m - stepSizeExit;
+        } else {
+            zvalsExit[j] = zvalsExit[j - 1] + stepSizeExit;
+        }
+        calcEngeFunction(zvalsExit[j] / gap_m,
+                         engeCoeffsExit_m,
+                         polyOrderExit_m,
+                         fieldValuesExit[0][j],
+                         fieldValuesExit[1][j],
+                         fieldValuesExit[2][j]);
+        fieldValuesExit[2][j] *= fieldValuesExit[0][j];
+    }
 
-    return false;
+    for (unsigned int i = 0; i < 3u; ++ i) {
+        gsl_spline_init(entryFieldValues_m[i], &(zvalsEntry[0]), &(fieldValuesEntry[i][0]), numStepsEntry);
+        gsl_spline_init(exitFieldValues_m[i], &(zvalsExit[0]), &(fieldValuesExit[i][0]), numStepsExit);
+    }
 }
 
-Vector_t Bend::RotateOutOfBendFrame(const Vector_t &X) {
-
-    /*
-     * Rotate vector out of the bend's local coordinate system back to
-     * the lab frame.
-     *
-     * 1) Rotate about the x axis by angle negative Orientation_m(1).
-     * 2) Rotate about the y axis by angle Orientation_m(0).
-     * 3) Rotate about the z axis by angle Orientation_m(3).
-     */
-
-    double sina = sin(Orientation_m(0));
-    double cosa = cos(Orientation_m(0));
-    double sinb = sin(Orientation_m(1));
-    double cosb = cos(Orientation_m(1));
-    double sinc = sin(Orientation_m(2));
-    double cosc = cos(Orientation_m(2));
-
-    Vector_t temp(0.0, 0.0, 0.0);
+bool Bend::reinitialize() {
 
-    temp(0) = (cosa * cosc) *                       X(0)
-        + (-sina * sinb * cosc - cosb * sinc) * X(1)
-        + (sina * cosb * cosc - sinb * sinc)  * X(2);
-    temp(1) = (cosa * sinc) *                       X(0)
-        + (-sina * sinb * sinc + cosb * cosc) * X(1)
-        + (sina * cosb * sinc + sinb * cosc)  * X(2);
-    temp(2) =   -sina *                               X(0)
-        + (-cosa * sinb) *                      X(1)
-        + (cosa * cosb) *                       X(2);
-
-    return temp;
-
-}
-
-Vector_t Bend::RotateToBendFrame(const Vector_t &X) {
+    setBendStrength();
+    double bendAngleX = 0.0;
+    double bendAngleY = 0.0;
+    calculateRefTrajectory(bendAngleX, bendAngleY);
 
-    /*
-     * Rotate vector to the bend's local coordinate system.
-     *
-     * 1) Rotate about the z axis by angle negative Orientation_m(2).
-     * 2) Rotate about the y axis by angle negative Orientation_m(0).
-     * 3) Rotate about the x axis by angle Orientation_m(1).
-     */
+    // INFOMSG(level2 << "Bend design energy changed to: "
+    //         << designEnergy_m * 1.0e-6
+    //         << " MeV"
+    //         << endl);
+    print(*Ippl::Info, bendAngleX, bendAngleY);
 
-    double sina = sin(Orientation_m(0));
-    double cosa = cos(Orientation_m(0));
-    double sinb = sin(Orientation_m(1));
-    double cosb = cos(Orientation_m(1));
-    double sinc = sin(Orientation_m(2));
-    double cosc = cos(Orientation_m(2));
-
-    Vector_t temp(0.0, 0.0, 0.0);
-
-    temp(0) = (cosa * cosc) * X(0)
-        + (cosa * sinc) * X(1)
-        -  sina *         X(2);
-    temp(1) = (-cosb * sinc - sina * sinb * cosc) * X(0)
-        + (cosb * cosc - sina * sinb * sinc)  * X(1)
-        -  cosa * sinb *                        X(2);
-    temp(2) = (-sinb * sinc + sina * cosb * cosc) * X(0)
-        + (sinb * cosc + sina * cosb * sinc)  * X(1)
-        + cosa * cosb *                         X(2);
-
-    return temp;
+    return false;
 }
 
-void Bend::SetBendEffectiveLength(double startField, double endField) {
+void Bend::setBendEffectiveLength(double startField, double endField) {
 
     // Find initial angle.
-    double actualBendAngle = CalculateBendAngle();
+    double actualBendAngle = calculateBendAngle();
 
     // Adjust field map to match bend angle.
     double error = std::abs(actualBendAngle - angle_m);
     if(error > 1.0e-6)
-        FindBendEffectiveLength(startField, endField);
+        findBendEffectiveLength(startField, endField);
 
 }
 
-void Bend::SetBendStrength() {
+void Bend::setBendStrength() {
 
     // Estimate bend field magnitude.
     double mass = RefPartBunch_m->getM();
@@ -1440,20 +1185,14 @@ void Bend::SetBendStrength() {
     double betaGamma = sqrt(pow(gamma, 2.0) - 1.0);
     double charge = RefPartBunch_m->getQ();
 
-    fieldAmplitude_m = (charge / std::abs(charge)) * betaGamma * mass
-        / (Physics::c * designRadius_m);
-
-    // Find initial angle.
-    double actualBendAngle = CalculateBendAngle();
+    fieldAmplitude_m = ((charge / std::abs(charge)) * betaGamma * mass /
+                        (Physics::c * designRadius_m));
 
     // Search for angle if initial guess is not good enough.
-    double error = std::abs(actualBendAngle - angle_m);
-    if(error > 1.0e-6)
-        FindBendStrength(mass, gamma, betaGamma, charge);
-
+    findBendStrength(mass, gamma, betaGamma, charge);
 }
 
-void Bend::SetEngeOriginDelta(double delta) {
+void Bend::setEngeOriginDelta(double delta) {
     /*
      * This function is used to shift the perpendicular distance of the
      * entrance and exit Enge function origins with respect to the entrance
@@ -1471,81 +1210,124 @@ void Bend::SetEngeOriginDelta(double delta) {
     exitParameter2_m = -delta;
 }
 
-void Bend::SetFieldCalcParam(bool chordLengthFromMap) {
+void Bend::setFieldCalcParam() {
 
     cosEntranceAngle_m = cos(entranceAngle_m);
     sinEntranceAngle_m = sin(entranceAngle_m);
+    tanEntranceAngle_m = tan(entranceAngle_m);
 
     deltaBeginEntry_m = std::abs(entranceParameter1_m - entranceParameter2_m);
     deltaEndEntry_m = std::abs(entranceParameter2_m - entranceParameter3_m);
 
-    exitEdgeAngle_m = angle_m - exitAngle_m;
-    cosExitAngle_m = cos(exitEdgeAngle_m);
-    sinExitAngle_m = sin(exitEdgeAngle_m);
-
     deltaBeginExit_m = std::abs(exitParameter1_m - exitParameter2_m);
     deltaEndExit_m = std::abs(exitParameter2_m - exitParameter3_m);
 
-    if(chordLengthFromMap) {
-        /*
-         * The magnet chord length is taken from this field map. In this case,
-         * we assume that the origin points for the entrance and exit Enge
-         * functions correspond to the physical edges of the bend magnet. These
-         * are the points where the ideal reference particle trajectory intercepts
-         * the entrance and exit edges.
-         */
-        xOriginEngeEntry_m = 0.0;
-        zOriginEngeEntry_m = 0.0;
-        xOriginEngeExit_m = xExit_m;
-        zOriginEngeExit_m = zExit_m;
-
+    double bendAngle = getBendAngle();
+    double entranceAngle = getEntranceAngle();
+    double exitAngle = getExitAngle();
+    tanExitAngle_m = tan(exitAngle);
+
+    double rotationAngleAboutZ = getRotationAboutZ();
+    Quaternion_t rotationAboutZ(cos(0.5 * rotationAngleAboutZ),
+                                sin(0.5 * rotationAngleAboutZ) * Vector_t(0, 0, 1));
+
+    Vector_t rotationAxis(0, -1, 0);
+    Quaternion_t halfRotationAboutAxis(cos(0.5 * (0.5 * bendAngle - entranceAngle)),
+                                       sin(0.5 * (0.5 * bendAngle - entranceAngle)) * rotationAxis);
+    Quaternion_t exitFaceRotation(cos(0.5 * (bendAngle - entranceAngle - exitAngle)),
+                                  sin(0.5 * (bendAngle - entranceAngle - exitAngle)) * rotationAxis);
+    Vector_t chord = getChordLength() * halfRotationAboutAxis.rotate(Vector_t(0, 0, 1));
+    beginToEnd_lcs_m = CoordinateSystemTrafo(chord, exitFaceRotation.conjugate());
+    beginToEnd_m = beginToEnd_lcs_m * CoordinateSystemTrafo(Vector_t(0.0), rotationAboutZ.conjugate());
+
+    Vector_t rotationCenter = Vector_t(-designRadius_m * cosEntranceAngle_m, 0.0, designRadius_m * sinEntranceAngle_m);
+
+    Vector_t maxAngleEntranceAperture;
+    if (rotationCenter(2) < 0.0) {
+        double tau, tmp;
+        Vector_t P(0.5 * aperture_m.second[0], 0.0, 0.0), &R = rotationCenter;
+        gsl_poly_solve_quadratic(dot(P,P),
+                                 -2 * dot(P,R),
+                                 dot(R,R) - std::pow(designRadius_m + 0.5 * aperture_m.second[0], 2),
+                                 &tau,
+                                 &tmp);
+        tau = (std::abs(1.0 - tmp) < std::abs(1.0 - tau)? tmp: tau);
+        maxAngleEntranceAperture = tau * P;
     } else {
-        /*
-         * In this case, the chord length of the magnet is set in the input file
-         * and is not taken from the field map file. This allows us to set the
-         * origin points for the entrance and exit Enge functions some perpendicular
-         * distance away from the physical edges of the magnet.
-         */
-        xOriginEngeEntry_m = -entranceParameter2_m * sinEntranceAngle_m;
-        zOriginEngeEntry_m = entranceParameter2_m * cosEntranceAngle_m;
-
-        xOriginEngeExit_m = xExit_m - exitParameter2_m * sinExitAngle_m;
-        zOriginEngeExit_m = zExit_m + exitParameter2_m * cosExitAngle_m;
-
+        double tau, tmp;
+        Vector_t P(-0.5 * aperture_m.second[0], 0.0, 0.0), &R = rotationCenter;
+        gsl_poly_solve_quadratic(dot(P,P),
+                                 -2 * dot(P,R),
+                                 dot(R,R) - std::pow(designRadius_m - 0.5 * aperture_m.second[0], 2),
+                                 &tau,
+                                 &tmp);
+        tau = (std::abs(1.0 - tmp) < std::abs(1.0 - tau)? tmp: tau);
+        maxAngleEntranceAperture = tau * P;
+    }
+    Vector_t maxAngleExitAperture;
+    if (getBeginToEnd_local().transformTo(rotationCenter)(2) > 0.0) {
+        double tau, tmp;
+        Vector_t P(0.5 * aperture_m.second[0], 0.0, 0.0), R = getBeginToEnd_local().transformTo(rotationCenter);
+        gsl_poly_solve_quadratic(dot(P,P),
+                                 -2 * dot(P,R),
+                                 dot(R,R) - std::pow(designRadius_m + 0.5 * aperture_m.second[0], 2),
+                                 &tau,
+                                 &tmp);
+        tau = (std::abs(1.0 - tmp) < std::abs(1.0 - tau)? tmp: tau);
+        maxAngleExitAperture = getBeginToEnd_local().transformFrom(tau * P);
+    } else {
+        double tau, tmp;
+        Vector_t P(-0.5 * aperture_m.second[0], 0.0, 0.0), R = getBeginToEnd_local().transformTo(rotationCenter);
+        gsl_poly_solve_quadratic(dot(P,P),
+                                 -2 * dot(P,R),
+                                 dot(R,R) - std::pow(designRadius_m - 0.5 * aperture_m.second[0], 2),
+                                 &tau,
+                                 &tmp);
+        tau = (std::abs(1.0 - tmp) < std::abs(1.0 - tau)? tmp: tau);
+        maxAngleExitAperture = getBeginToEnd_local().transformFrom(tau * P);
     }
+
+    maxAngleEntranceAperture -= rotationCenter;
+
+    Quaternion rotation = getQuaternion(maxAngleEntranceAperture, Vector_t(0, 0, 1));
+    computeAngleTrafo_m = CoordinateSystemTrafo(rotationCenter,
+                                                rotation);
+    Vector_t tmp = computeAngleTrafo_m.transformTo(maxAngleExitAperture);
+    maxAngle_m = fmod(Physics::two_pi - atan2(tmp(0), tmp(2)), Physics::two_pi);
+
+    maxAngleExitAperture -= rotationCenter;
 }
 
-void Bend::SetGapFromFieldMap() {
+void Bend::setGapFromFieldMap() {
 
     if(gap_m <= 0.0)
-        gap_m = fieldmap_m->GetFieldGap();
-    else if(gap_m != fieldmap_m->GetFieldGap())
-        AdjustFringeFields(gap_m / fieldmap_m->GetFieldGap());
+        gap_m = fieldmap_m->getFieldGap();
+    else if(gap_m != fieldmap_m->getFieldGap())
+        adjustFringeFields(gap_m / fieldmap_m->getFieldGap());
 
 }
 
-bool Bend::SetupBendGeometry(Inform &msg, double &startField, double &endField) {
+bool Bend::setupBendGeometry(Inform &msg, double &startField, double &endField) {
 
-    double chordLength = 0.0;
-    bool chordLengthFromMap = false;
-    if(!FindChordLength(msg, chordLength, chordLengthFromMap))
+    chordLength_m = 0.0;
+    if(!findChordLength(msg, chordLength_m))
         return false;
 
-    if(TreatAsDrift(msg, chordLength)) {
+    if(treatAsDrift(msg, chordLength_m)) {
         startField_m = startField;
-        endField_m = startField + chordLength;
+        endField_m = startField + chordLength_m;
         return true;
     }
 
-    reinitialize_m = FindIdealBendParameters(chordLength);
-    FindReferenceExitOrigin(xExit_m, zExit_m);
+    reinitialize_m = findIdealBendParameters(chordLength_m);
+    findReferenceExitOrigin(xExit_m, zExit_m);
 
     /*
      * Set field map geometry.
      */
-    if(aperture_m <= 0.0)
-        aperture_m = designRadius_m / 2.0;
-    SetFieldCalcParam(chordLengthFromMap);
+    if(aperture_m.second[0] <= 0.0)
+        aperture_m.second[0] = designRadius_m / 2.0;
+    setFieldCalcParam();
 
     /*
      * If we are using the default field map, then the origins for the
@@ -1558,14 +1340,14 @@ bool Bend::SetupBendGeometry(Inform &msg, double &startField, double &endField)
      * the bend strength) or we adjust the bend field to get the right
      * angle.
      */
-    elementEdge_m = startField + ds_m;
-    SetFieldBoundaries(startField, endField);
+    elementEdge_m = startField;
+    setFieldBoundaries(startField, endField);
 
     if(fileName_m != "1DPROFILE1-DEFAULT") {
         if(reinitialize_m)
-            SetBendStrength();
+            setBendStrength();
     } else {
-        SetBendEffectiveLength(startField, endField);
+        setBendEffectiveLength(startField, endField);
     }
 
     startField = startField_m;
@@ -1574,7 +1356,7 @@ bool Bend::SetupBendGeometry(Inform &msg, double &startField, double &endField)
 
 }
 
-bool Bend::SetupDefaultFieldMap(Inform &msg) {
+bool Bend::setupDefaultFieldMap(Inform &msg) {
 
     if(length_m <= 0.0) {
         ERRORMSG("If using \"1DPROFILE1-DEFAULT\" field map you must set the "
@@ -1583,30 +1365,29 @@ bool Bend::SetupDefaultFieldMap(Inform &msg) {
                  << endl);
         return false;
     } else {
-        msg << level2;
-        fieldmap_m->getInfo(&msg);
+        // msg << level2;
+        // fieldmap_m->getInfo(&msg);
         return true;
     }
 
 }
 
-void Bend::SetFieldBoundaries(double startField, double endField) {
+void Bend::setFieldBoundaries(double startField, double endField) {
 
-    startField_m = startField - deltaBeginEntry_m / cos(entranceAngle_m) + ds_m;
-    endField_m = startField + angle_m * designRadius_m
-        + deltaEndExit_m / cos(exitAngle_m)
-        + ds_m;
+    startField_m = startField - deltaBeginEntry_m / cos(entranceAngle_m);
+    endField_m = (startField + angle_m * designRadius_m +
+                  deltaEndExit_m / cos(exitAngle_m));
 
 }
 
-void Bend::SetupPusher(PartBunch *bunch) {
+void Bend::setupPusher(PartBunch *bunch) {
 
     RefPartBunch_m = bunch;
     pusher_m.initialise(bunch->getReference());
 
 }
 
-bool Bend::TreatAsDrift(Inform &msg, double chordLength) {
+bool Bend::treatAsDrift(Inform &msg, double chordLength) {
     if(designEnergy_m <= 0.0) {
         WARNMSG("Warning: bend design energy is zero. Treating as drift."
                 << endl);
@@ -1644,10 +1425,357 @@ bool Bend::TreatAsDrift(Inform &msg, double chordLength) {
 }
 
 void Bend::retrieveDesignEnergy(double startField) {
-    energyEvolution_t::iterator it = OpalData::getInstance()->getFirstEnergyData();
-    energyEvolution_t::iterator end = OpalData::getInstance()->getLastEnergyData();
-    for (; it != end; ++ it) {
-        if ((*it).first > startField) break;
-        designEnergy_m = (*it).second;
+    // energyEvolution_t::iterator it = OpalData::getInstance()->getFirstEnergyData();
+    // energyEvolution_t::iterator end = OpalData::getInstance()->getLastEnergyData();
+    // for (; it != end; ++ it) {
+    //     if ((*it).first > startField) break;
+    //     designEnergy_m = (*it).second;
+    // }
+}
+
+std::pair<Vector_t, Vector_t> Bend::getDesignPathSecant(double startsAtDistFromEdge, double length) const {
+
+    length = std::abs(length);
+    Vector_t startPosition(0.0);
+    Vector_t tangent(0, 0, 1);
+
+    double pathLength = refTrajMap_m[0](2);
+    unsigned int size = refTrajMap_m.size();
+
+    for (unsigned int i = 1; i < size; ++ i) {
+        Vector_t step = refTrajMap_m[i] - refTrajMap_m[i-1];
+        double stepSize = euclidian_norm(step);
+        if (pathLength + stepSize > startsAtDistFromEdge) {
+            double diff = startsAtDistFromEdge - pathLength;
+            tangent = step / stepSize;
+            startPosition = refTrajMap_m[i-1] + diff * tangent;
+
+
+            if (length <= 1e-12) {
+                return std::make_pair(startPosition, tangent);
+            }
+
+            for (unsigned j = i; j < size; ++ j) {
+                Vector_t position = refTrajMap_m[j];
+
+                if (euclidian_norm(position - startPosition) >= length) {
+                    step = refTrajMap_m[j-1] - refTrajMap_m[j];
+                    double tau = (dot(startPosition - position, step) - sqrt(std::pow(dot(startPosition - position, step), 2) - dot(step, step) * (dot(startPosition - position, startPosition - position) - std::pow(length, 2)))) / dot(step, step);
+
+                    tangent = position + tau * step - startPosition;
+                    tangent /= euclidian_norm(tangent);
+
+                    return std::make_pair(startPosition, tangent);
+                }
+            }
+
+            Vector_t position = refTrajMap_m[size - 1];
+            Vector_t step = position - refTrajMap_m[size - 2];
+            step /= euclidian_norm(step);
+            double tau = (dot(startPosition - position, step) + sqrt(std::pow(dot(startPosition - position, step), 2) - dot(step, step) * (dot(startPosition - position, startPosition - position) - std::pow(length, 2)))) / dot(step, step);
+
+            tangent = position + tau * step - startPosition;
+            tangent /= euclidian_norm(tangent);
+
+            return std::make_pair(startPosition, tangent);
+        }
+
+        pathLength += stepSize;
+    }
+
+    double diff = startsAtDistFromEdge - pathLength;
+    unsigned int i = size - 1;
+    Vector_t step = refTrajMap_m[i] - refTrajMap_m[i-1];
+    double stepSize = euclidian_norm(step);
+    tangent = step / stepSize;
+    startPosition = refTrajMap_m[i] + diff * tangent;
+    tangent = tangent;
+
+    return std::make_pair(startPosition, tangent);
+}
+
+std::vector<Vector_t> Bend::getOutline() const {
+    std::vector<Vector_t> outline;
+    Vector_t rotationCenter = Vector_t(-designRadius_m * cosEntranceAngle_m, 0.0, designRadius_m * sinEntranceAngle_m);
+    unsigned int numSteps = 2;
+
+    outline.push_back(Vector_t(-aperture_m.second[0], 0.0, 0.0));
+    outline.push_back(Vector_t(-aperture_m.second[0] + entranceParameter1_m * tanEntranceAngle_m, 0.0, entranceParameter1_m));
+    outline.push_back(Vector_t(entranceParameter1_m * tanEntranceAngle_m, 0.0, entranceParameter1_m));
+    outline.push_back(Vector_t(aperture_m.second[0] + entranceParameter1_m * tanEntranceAngle_m, 0.0, entranceParameter1_m));
+    outline.push_back(Vector_t(aperture_m.second[0], 0.0, 0.0));
+
+    {
+        double tau1, tau2;
+        Vector_t P(0.5 * aperture_m.second[0], 0.0, 0.0), R = rotationCenter;
+        gsl_poly_solve_quadratic(dot(P,P),
+                                 -2 * dot(P,R),
+                                 dot(R,R) - std::pow(designRadius_m + 0.5 * aperture_m.second[0], 2),
+                                 &tau1,
+                                 &tau2);
+        tau1 = (std::abs(1.0 - tau2) < std::abs(1.0 - tau1)? tau2: tau1);
+        Vector_t upperCornerAtEntry = tau1 * P;
+
+        R = getBeginToEnd_local().transformTo(rotationCenter);
+        gsl_poly_solve_quadratic(dot(P,P),
+                                 -2 * dot(P,R),
+                                 dot(R,R) - std::pow(designRadius_m + 0.5 * aperture_m.second[0], 2),
+                                 &tau1,
+                                 &tau2);
+        tau1 = (std::abs(1.0 - tau2) < std::abs(1.0 - tau1)? tau2: tau1);
+        Vector_t upperCornerAtExit = getBeginToEnd_local().transformFrom(tau1 * P);
+
+        Quaternion rotation = getQuaternion(upperCornerAtEntry - rotationCenter, Vector_t(0,0,1));
+        Vector_t tmp = CoordinateSystemTrafo(rotationCenter, rotation).transformTo(upperCornerAtExit);
+        double totalAngle = -fmod(Physics::two_pi - atan2(tmp(0), tmp(2)), Physics::two_pi);
+        numSteps = std::max(2.0, std::ceil(-totalAngle / (5.0 * Physics::deg2rad)));
+        double dAngle = 0.5 * totalAngle / (1.0 * numSteps - 1.0);
+
+        outline.push_back(upperCornerAtEntry);
+        double angle = 0.0;
+        for (unsigned int i = 0; i < numSteps; ++ i, angle += dAngle) {
+            Quaternion rot(cos(angle), 0.0, sin(angle), 0.0);
+            outline.push_back(rot.rotate(upperCornerAtEntry - rotationCenter) + rotationCenter);
+        }
+        outline.push_back(upperCornerAtExit);
+    }
+
+    outline.push_back(getBeginToEnd_local().transformFrom(Vector_t(aperture_m.second[0], 0.0, 0.0)));
+    outline.push_back(getBeginToEnd_local().transformFrom(Vector_t(aperture_m.second[0] - exitParameter3_m * tanExitAngle_m, 0.0, exitParameter3_m)));
+    outline.push_back(getBeginToEnd_local().transformFrom(Vector_t(-exitParameter3_m * tanExitAngle_m, 0.0, exitParameter3_m)));
+    outline.push_back(getBeginToEnd_local().transformFrom(Vector_t(-aperture_m.second[0] - exitParameter3_m * tanExitAngle_m, 0.0, exitParameter3_m)));
+    outline.push_back(getBeginToEnd_local().transformFrom(Vector_t(-aperture_m.second[0], 0.0, 0.0)));
+
+    {
+        double tau1, tau2;
+        Vector_t P(-0.5 * aperture_m.second[0], 0.0, 0.0), R = rotationCenter;
+        gsl_poly_solve_quadratic(dot(P,P),
+                                 -2 * dot(P,R),
+                                 dot(R,R) - std::pow(designRadius_m - 0.5 * aperture_m.second[0], 2),
+                                 &tau1,
+                                 &tau2);
+        tau1 = (std::abs(1.0 - tau2) < std::abs(1.0 - tau1)? tau2: tau1);
+        Vector_t lowerCornerAtEntry = tau1 * P;
+
+        R = getBeginToEnd_local().transformTo(rotationCenter);
+        gsl_poly_solve_quadratic(dot(P,P),
+                                 -2 * dot(P,R),
+                                 dot(R,R) - std::pow(designRadius_m - 0.5 * aperture_m.second[0], 2),
+                                 &tau1,
+                                 &tau2);
+        tau1 = (std::abs(1.0 - tau2) < std::abs(1.0 - tau1)? tau2: tau1);
+        Vector_t lowerCornerAtExit = getBeginToEnd_local().transformFrom(tau1 * P);
+
+        Quaternion rotation = getQuaternion(lowerCornerAtEntry - rotationCenter, Vector_t(0,0,1));
+        Vector_t tmp = CoordinateSystemTrafo(rotationCenter, rotation).transformTo(lowerCornerAtExit);
+        double totalAngle = -fmod(Physics::two_pi - atan2(tmp(0), tmp(2)), Physics::two_pi);
+        double dAngle = 0.5 * totalAngle / (1.0 * numSteps - 1.0);
+
+        outline.push_back(lowerCornerAtExit);
+        double angle = 0.5 * totalAngle;
+        for (unsigned int i = 0; i < numSteps; ++ i, angle -= dAngle) {
+            Quaternion rot(cos(angle), 0.0, sin(angle), 0.0);
+            outline.push_back(rot.rotate(lowerCornerAtEntry - rotationCenter) + rotationCenter);
+        }
+        outline.push_back(lowerCornerAtEntry);
+    }
+
+    std::ofstream outlineOutput;
+    if (Options::writeBendTrajectories && Ippl::myNode() == 0) {
+        outlineOutput.open("data/" + OpalData::getInstance()->getInputBasename() + "_" + getName() + "_outline.dat");
+        outlineOutput.precision(8);
+
+        for (auto a: outline) {
+            outlineOutput << std::setw(18) << a(2)
+                          << std::setw(18) << a(0)
+                          << "\n";
+        }
+        outlineOutput << std::setw(18) << outline.front()(2)
+                      << std::setw(18) << outline.front()(0)
+                      << std::endl;
+    }
+    return outline;
+}
+
+MeshData Bend::getSurfaceMesh() const {
+    MeshData mesh;
+    const Vector_t hgap(0, 0.5 * getFullGap(), 0);
+    std::vector<Vector_t> outline = getOutline();
+
+    unsigned int size = outline.size();
+    unsigned int last = size - 1;
+    unsigned int numSteps = (size - 14) / 2;
+    unsigned int midIdx = numSteps + 7;
+
+    for (unsigned int i = 0; i < 6; ++ i) {
+        mesh.vertices_m.push_back(outline[i] + 2 * hgap);
     }
+    for (unsigned int i = 6; i < 6 + numSteps; ++ i) {
+        mesh.vertices_m.push_back(outline[i] + hgap);
+    }
+    for (unsigned int i = 6 + numSteps; i < 13 + numSteps; ++ i) {
+        mesh.vertices_m.push_back(outline[i] + 2 * hgap);
+    }
+    for (unsigned int i = 13 + numSteps; i < 13 + 2 * numSteps; ++ i) {
+        mesh.vertices_m.push_back(outline[i] + hgap);
+    }
+    mesh.vertices_m.push_back(outline[last] + 2 * hgap);
+
+    for (unsigned int i = 0; i < 6; ++ i) {
+        mesh.vertices_m.push_back(outline[i] - 2 * hgap);
+    }
+    for (unsigned int i = 6; i < 6 + numSteps; ++ i) {
+        mesh.vertices_m.push_back(outline[i] - hgap);
+    }
+    for (unsigned int i = 6 + numSteps; i < 13 + numSteps; ++ i) {
+        mesh.vertices_m.push_back(outline[i] - 2 * hgap);
+    }
+    for (unsigned int i = 13 + numSteps; i < 13 + 2 * numSteps; ++ i) {
+        mesh.vertices_m.push_back(outline[i] - hgap);
+    }
+    mesh.vertices_m.push_back(outline[last] - 2 * hgap);
+
+    mesh.vertices_m.push_back(outline[0]);
+    mesh.vertices_m.push_back(outline[4]);
+    mesh.vertices_m.push_back(outline[midIdx]);
+    mesh.vertices_m.push_back(outline[midIdx + 4]);
+
+    mesh.triangles_m.push_back(Vektor<unsigned int, 3>(2, 1, 0));
+    mesh.triangles_m.push_back(Vektor<unsigned int, 3>(2, 4, 3));
+    mesh.triangles_m.push_back(Vektor<unsigned int, 3>(2, 5, 4));
+    mesh.triangles_m.push_back(Vektor<unsigned int, 3>(2, 0, last));
+    mesh.triangles_m.push_back(Vektor<unsigned int, 3>(2, last, 5));
+    mesh.triangles_m.push_back(Vektor<unsigned int, 3>(last, last - 1, 5));
+    mesh.triangles_m.push_back(Vektor<unsigned int, 3>(5, last - 1, 6));
+
+    // exit region top
+    mesh.triangles_m.push_back(Vektor<unsigned int, 3>(midIdx + 2, midIdx + 1, midIdx));
+    mesh.triangles_m.push_back(Vektor<unsigned int, 3>(midIdx + 2, midIdx + 4, midIdx + 3));
+    mesh.triangles_m.push_back(Vektor<unsigned int, 3>(midIdx + 2, midIdx + 5, midIdx + 4));
+    mesh.triangles_m.push_back(Vektor<unsigned int, 3>(midIdx + 2, midIdx, midIdx - 1));
+    mesh.triangles_m.push_back(Vektor<unsigned int, 3>(midIdx + 2, midIdx - 1, midIdx + 5));
+    mesh.triangles_m.push_back(Vektor<unsigned int, 3>(midIdx - 1, midIdx - 2, midIdx + 5));
+    mesh.triangles_m.push_back(Vektor<unsigned int, 3>(midIdx + 5, midIdx - 2, midIdx + 6));
+
+    // entry region bottom
+    mesh.triangles_m.push_back(Vektor<unsigned int, 3>(size + 2, size + 0, size + 1));
+    mesh.triangles_m.push_back(Vektor<unsigned int, 3>(size + 2, size + 3, size + 4));
+    mesh.triangles_m.push_back(Vektor<unsigned int, 3>(size + 2, size + 4, size + 5));
+    mesh.triangles_m.push_back(Vektor<unsigned int, 3>(size + 2, size + last, size + 0));
+    mesh.triangles_m.push_back(Vektor<unsigned int, 3>(size + 2, size + 5, size + last));
+    mesh.triangles_m.push_back(Vektor<unsigned int, 3>(size + last, size + 5, size + last - 1));
+    mesh.triangles_m.push_back(Vektor<unsigned int, 3>(size + 5, size + 6, size + last - 1));
+
+    // exit region bottom
+    mesh.triangles_m.push_back(Vektor<unsigned int, 3>(size + midIdx + 2, size + midIdx + 0, size + midIdx + 1));
+    mesh.triangles_m.push_back(Vektor<unsigned int, 3>(size + midIdx + 2, size + midIdx + 3, size + midIdx + 4));
+    mesh.triangles_m.push_back(Vektor<unsigned int, 3>(size + midIdx + 2, size + midIdx + 4, size + midIdx + 5));
+    mesh.triangles_m.push_back(Vektor<unsigned int, 3>(size + midIdx + 2, size + midIdx - 1, size + midIdx + 0));
+    mesh.triangles_m.push_back(Vektor<unsigned int, 3>(size + midIdx + 2, size + midIdx + 5, size + midIdx - 1));
+    mesh.triangles_m.push_back(Vektor<unsigned int, 3>(size + midIdx - 1, size + midIdx + 5, size + midIdx - 2));
+    mesh.triangles_m.push_back(Vektor<unsigned int, 3>(size + midIdx + 5, size + midIdx + 6, size + midIdx - 2));
+
+    // central region
+    for (unsigned int i = 6; i < 5 + numSteps; ++ i) {
+        mesh.triangles_m.push_back(Vektor<unsigned int, 3>(i, last + 5 - i, i + 1));
+        mesh.triangles_m.push_back(Vektor<unsigned int, 3>(last + 5 - i, last + 4 - i, i + 1));
+
+        mesh.triangles_m.push_back(Vektor<unsigned int, 3>(size + i, size + i + 1, size + last + 5 - i));
+        mesh.triangles_m.push_back(Vektor<unsigned int, 3>(size + last + 5 - i, size + i + 1, size + last + 4 - i));
+    }
+
+    // side
+    for (unsigned int i = 0; i < size - 2; ++ i) {
+        if (i == 4u || i == 5u ||
+            i == 5 + numSteps || i == 6 + numSteps ||
+            i == 11 + numSteps || i == 12 + numSteps) continue;
+
+        unsigned int next = (i + 1) % size;
+        mesh.triangles_m.push_back(Vektor<unsigned int, 3>(i, next, next + size));
+        mesh.triangles_m.push_back(Vektor<unsigned int, 3>(i, next + size, i + size));
+    }
+
+    mesh.triangles_m.push_back(Vektor<unsigned int, 3>(last, 0, last-1));
+    mesh.triangles_m.push_back(Vektor<unsigned int, 3>(2*size, last - 1, 0));
+    mesh.triangles_m.push_back(Vektor<unsigned int, 3>(2*size, size + last - 1, last - 1));
+    mesh.triangles_m.push_back(Vektor<unsigned int, 3>(2*size, size, size + last - 1));
+    mesh.triangles_m.push_back(Vektor<unsigned int, 3>(size + last, size + last - 1, size));
+
+    mesh.triangles_m.push_back(Vektor<unsigned int, 3>(4, 5, 6));
+    mesh.triangles_m.push_back(Vektor<unsigned int, 3>(4, 6, 2*size + 1));
+    mesh.triangles_m.push_back(Vektor<unsigned int, 3>(2*size + 1, 6, size + 6));
+    mesh.triangles_m.push_back(Vektor<unsigned int, 3>(size + 4, 2*size + 1, size + 6));
+    mesh.triangles_m.push_back(Vektor<unsigned int, 3>(size + 4, size + 6, size + 5));
+
+    mesh.triangles_m.push_back(Vektor<unsigned int, 3>(6 + numSteps, midIdx, 5 + numSteps));
+    mesh.triangles_m.push_back(Vektor<unsigned int, 3>(5 + numSteps, midIdx, 2*size + 2));
+    mesh.triangles_m.push_back(Vektor<unsigned int, 3>(5 + numSteps, 2*size + 2, size + 5 + numSteps));
+    mesh.triangles_m.push_back(Vektor<unsigned int, 3>(size + 5 + numSteps, 2*size + 2, size + midIdx));
+    mesh.triangles_m.push_back(Vektor<unsigned int, 3>(size + 6 + numSteps, size + 5 + numSteps, size + midIdx));
+
+    mesh.triangles_m.push_back(Vektor<unsigned int, 3>(6 + midIdx, 4 + midIdx, 5 + midIdx));
+    mesh.triangles_m.push_back(Vektor<unsigned int, 3>(6 + midIdx, 2*size + 3, 4 + midIdx));
+    mesh.triangles_m.push_back(Vektor<unsigned int, 3>(2*size + 3, 6 + midIdx, size + 6 + midIdx));
+    mesh.triangles_m.push_back(Vektor<unsigned int, 3>(size + 4 + midIdx,  2*size + 3, size + 6 + midIdx));
+    mesh.triangles_m.push_back(Vektor<unsigned int, 3>(size + 4 + midIdx, size + 6 + midIdx, size + 5 + midIdx));
+
+    double tau1, tau2;
+    Vector_t rotationCenter(-designRadius_m * cosEntranceAngle_m, 0.0, designRadius_m * sinEntranceAngle_m);
+    Vector_t P(-0.5 * aperture_m.second[0], 0.0, 0.0);
+    Vector_t R = Vector_t(0, 0, entranceParameter3_m) - rotationCenter;
+    gsl_poly_solve_quadratic(dot(P,P),
+                             2 * dot(P,R),
+                             dot(R,R) - std::pow(designRadius_m - 0.5 * aperture_m.second[0],2),
+                             &tau1,
+                             &tau2);
+    tau1 = (std::abs(1.0 - tau2) < std::abs(1.0 - tau1)? tau2: tau1);
+    Vector_t lowerCornerFringeLimitEntrance = Vector_t(0, 0, entranceParameter3_m) + tau1 * P;
+
+    gsl_poly_solve_quadratic(dot(P,P),
+                             -2 * dot(P,R),
+                             dot(R,R) - std::pow(designRadius_m + 0.5 * aperture_m.second[0],2),
+                             &tau1,
+                             &tau2);
+    tau1 = (std::abs(1.0 - tau2) < std::abs(1.0 - tau1)? tau2: tau1);
+    Vector_t upperCornerFringeLimitEntrance = Vector_t(0, 0, entranceParameter3_m) - tau1 * P;
+
+    P = Vector_t(0.5 * aperture_m.second[0], 0.0, 0.0);
+    R = Vector_t(0, 0, exitParameter1_m) - getBeginToEnd_local().transformTo(rotationCenter);
+    gsl_poly_solve_quadratic(dot(P,P),
+                             2 * dot(P,R),
+                             dot(R,R) - std::pow(designRadius_m + 0.5 * aperture_m.second[0],2),
+                             &tau1,
+                             &tau2);
+    tau1 = (std::abs(1.0 - tau2) < std::abs(1.0 - tau1)? tau2: tau1);
+    Vector_t upperCornerFringeLimitExit = getBeginToEnd_local().transformFrom(Vector_t(0, 0, exitParameter1_m) + tau1 * P);
+
+    gsl_poly_solve_quadratic(dot(P,P),
+                             -2 * dot(P,R),
+                             dot(R,R) - std::pow(designRadius_m - 0.5 * aperture_m.second[0],2),
+                             &tau1,
+                             &tau2);
+    tau1 = (std::abs(1.0 - tau2) < std::abs(1.0 - tau1)? tau2: tau1);
+    Vector_t lowerCornerFringeLimitExit = getBeginToEnd_local().transformFrom(Vector_t(0, 0, exitParameter1_m) - tau1 * P);
+
+    mesh.decorations_m.push_back(std::make_pair(lowerCornerFringeLimitEntrance, upperCornerFringeLimitEntrance));
+    mesh.decorations_m.push_back(std::make_pair(lowerCornerFringeLimitExit, upperCornerFringeLimitExit));
+    mesh.decorations_m.push_back(std::make_pair(Vector_t(entranceParameter1_m * tanEntranceAngle_m, 0.0, entranceParameter1_m),
+                                                Vector_t(0.0)));
+    mesh.decorations_m.push_back(std::make_pair(getBeginToEnd_local().transformFrom(Vector_t(0.0)),
+                                                getBeginToEnd_local().transformFrom(Vector_t(-exitParameter3_m * tanExitAngle_m, 0.0, exitParameter3_m))));
+    return mesh;
+}
+
+bool Bend::isInside(const Vector_t &R) const {
+    if (std::abs(R(1)) > gap_m) return false;
+
+    if (inMagnetEntranceRegion(R)) {
+        return true;
+    }
+
+    if (inMagnetExitRegion(R)) {
+        return true;
+    }
+
+    return (std::abs(R(1)) < 0.5 * gap_m && inMagnetCentralRegion(R));
 }
\ No newline at end of file
diff --git a/src/Classic/AbsBeamline/Bend.h b/src/Classic/AbsBeamline/Bend.h
index b75bae1de07df838700d6c0458b7641280a2d38e..e465423a5c40be0be4f34346f1a0a8a658f2b29b 100644
--- a/src/Classic/AbsBeamline/Bend.h
+++ b/src/Classic/AbsBeamline/Bend.h
@@ -21,14 +21,19 @@
 //
 // ------------------------------------------------------------------------
 
-#include "AbsBeamline/Component.h"
+#include "AbsBeamline/BendBase.h"
 #include "Fields/BMultipoleField.h"
 #include "Algorithms/PartPusher.h"
 #include "Physics/Physics.h"
-#include <vector>
+#include "Utilities/GeneralClassicException.h"
+
+#include "gsl/gsl_spline.h"
+#include "gsl/gsl_interp.h"
 
+#include <vector>
 
 class Fieldmap;
+class MeshData;
 
 /*
  * Class Bend
@@ -39,7 +44,7 @@ class Fieldmap;
  *
  */
 
-class Bend: public Component {
+class Bend: public BendBase {
 
 public:
 
@@ -66,10 +71,6 @@ public:
      */
 
     /// Apply field to particles with coordinates in magnet frame.
-    virtual bool apply(const size_t &i,
-                       const double &t,
-                       double E[],
-                       double B[]);
     virtual bool apply(const size_t &i,
                        const double &t,
                        Vector_t &E,
@@ -77,13 +78,16 @@ public:
 
     /// Apply field to particles in beam frame.
     virtual bool apply(const Vector_t &R,
-                       const Vector_t &centroid,
+                       const Vector_t &P,
                        const double &t,
                        Vector_t &E,
                        Vector_t &B);
 
-    /// Indicates that element bends the beam.
-    virtual bool bends() const;
+    virtual bool applyToReferenceParticle(const Vector_t &R,
+                                          const Vector_t &P,
+                                          const double &t,
+                                          Vector_t &E,
+                                          Vector_t &B);
 
     virtual void goOnline(const double &kineticEnergy);
 
@@ -92,23 +96,16 @@ public:
     virtual ElementBase::ElementType getType() const = 0;
     virtual void initialise(PartBunch *bunch,
                             double &startField,
-                            double &endField,
-                            const double &scaleFactor);
-
-    double GetBendAngle() const;
-    double GetBendRadius() const;
-    double GetEffectiveCenter() const;
-    double GetEffectiveLength() const;
-    std::string GetFieldMapFN() const;
-    double GetStartElement() const;
-    void SetAngleGreaterThanPiFlag(bool angleGreaterThanPi);
-    void SetAperture(double aperture);
-    virtual void SetBendAngle(double angle);
-    void SetBeta(double beta);
-    void SetDesignEnergy(double energy);
-    virtual void SetEntranceAngle(double entranceAngle);
+                            double &endField);
+
+    // double getBendAngle() const;
+    double getBendRadius() const;
+    double getEffectiveCenter() const;
+    double getEffectiveLength() const;
+
+    double getStartElement() const;
+
     void setExitAngle(double exitAngle);
-    void SetFieldAmplitude(double k0, double k0s);
 
     /*
      * Set the name of the field map.
@@ -116,117 +113,101 @@ public:
      * For now this means a file that contains Enge function coefficients
      * that describe the fringe fields at the entrance and exit.
      */
-    void SetFieldMapFN(std::string fileName);
-    void SetFullGap(double gap);
-
     /// Set quadrupole field component.
-    void SetK1(double k1);
-    void SetLength(double length);
-
-    /// Set rotation about z axis in bend frame.
-    void SetRotationAboutZ(double rotation);
+    void setK1(double k1);
 
     void resetReinitializeFlag();
     void resetRecalcRefTrajFlag();
 
+    double getExitAngle() const;
+    double getMapLength() const;
+
+    std::pair<Vector_t, Vector_t> getDesignPathSecant(double startsAtDistFromEdge, double length) const;
+
+    std::vector<Vector_t> getOutline() const;
+    MeshData getSurfaceMesh() const;
+
+    virtual CoordinateSystemTrafo getBeginToEnd() const;
+
+    virtual bool isInside(const Vector_t &r) const;
 protected:
     void setMessageHeader(const std::string & header);
     double getStartField() const;
     Fieldmap* getFieldmap();
-    double getFieldAmplitude() const;
-
-    double & getAngle();
-    double & getEntranceAngle();
-    double & getExitAngle();
-    double getLength();
-    double getMapLength();
 
 private:
 
     // Not implemented.
     void operator=(const Bend &);
 
-    void AdjustFringeFields(double ratio);
-    double CalculateBendAngle();
-    void CalcCentralField(const Vector_t &R,
-                          double deltaX,
-                          double angle,
-                          Vector_t &B);
-    void CalcDistFromRefOrbitCentralField(const Vector_t &R,
-                                          double &deltaX,
-                                          double &angle);
-    void CalcEngeFunction(double zNormalized,
+    void adjustFringeFields(double ratio);
+    double calculateBendAngle();
+    void calcEngeFunction(double zNormalized,
                           const std::vector<double> &engeCoeff,
                           int polyOrder,
                           double &engeFunc,
                           double &engeFuncDeriv,
                           double &engeFuncSecDerivNorm);
-    void CalcEntranceFringeField(const Vector_t &REntrance,
-                                 double deltaX,
-                                 Vector_t &B);
-    void CalcExitFringeField(const Vector_t &RExit, double deltaX, Vector_t &B);
-    void CalculateMapField(const Vector_t &R, Vector_t &E, Vector_t &B);
-    void CalculateRefTrajectory(double &angleX, double &angleY);
-    double EstimateFieldAdjustmentStep(double actualBendAngle,
+    Vector_t calcCentralField(const Vector_t &R,
+                              double deltaX);
+    Vector_t calcEntranceFringeField(const Vector_t &R,
+                                     double deltaX);
+    Vector_t calcExitFringeField(const Vector_t &R,
+                                 double deltaX);
+    bool calculateMapField(const Vector_t &R,
+                           Vector_t &B);
+    void calculateRefTrajectory(double &angleX,
+                                double &angleY);
+    double estimateFieldAdjustmentStep(double actualBendAngle,
                                        double mass,
                                        double betaGamma);
-    void FindBendEffectiveLength(double startField, double endField);
-    void FindBendStrength(double mass,
+    void findBendEffectiveLength(double startField,
+                                 double endField);
+    void findBendStrength(double mass,
                           double gamma,
                           double betaGamma,
                           double charge);
-    virtual bool FindChordLength(Inform &msg,
-                                 double &chordLength,
-                                 bool &chordLengthFromMap) = 0;
-    bool FindIdealBendParameters(double chordLength);
-    void FindReferenceExitOrigin(double &x, double &z);
-    bool InitializeFieldMap(Inform &msg);
-    bool InMagnetCentralRegion(const Vector_t &R, double &deltaX, double &angle);
-    bool InMagnetEntranceRegion(const Vector_t &R, double &deltaX);
-    bool InMagnetExitRegion(const Vector_t &R, double &deltaX);
-    bool IsPositionInEntranceField(const Vector_t &R, Vector_t &REntrance);
-    bool IsPositionInExitField(const Vector_t &R, Vector_t &RExit);
-    void Print(Inform &msg, double bendAngleX, double bendAngle);
-    void ReadFieldMap(Inform &msg);
-    bool Reinitialize();
-    Vector_t RotateOutOfBendFrame(const Vector_t &X);
-    Vector_t RotateToBendFrame(const Vector_t &X);
-    void SetBendEffectiveLength(double startField, double endField);
-    void SetBendStrength();
-    void SetEngeOriginDelta(double delta);
-    void SetFieldCalcParam(bool chordLengthFromMap);
-    void SetGapFromFieldMap();
-    bool SetupBendGeometry(Inform &msg, double &startField, double &endField);
-    bool SetupDefaultFieldMap(Inform &msg);
-    void SetFieldBoundaries(double startField, double endField);
-    void SetupPusher(PartBunch *bunch);
-    bool TreatAsDrift(Inform &msg, double chordlength);
+    virtual bool findChordLength(Inform &msg,
+                                 double &chordLength) = 0;
+    bool findIdealBendParameters(double chordLength);
+    void findReferenceExitOrigin(double &x, double &z);
+    bool initializeFieldMap(Inform &msg);
+    bool inMagnetCentralRegion(const Vector_t &R) const;
+    bool inMagnetEntranceRegion(const Vector_t &R) const;
+    bool inMagnetExitRegion(const Vector_t &R) const;
+    bool isPositionInEntranceField(const Vector_t &R) const;
+    bool isPositionInExitField(const Vector_t &R) const;
+    void print(Inform &msg, double bendAngleX, double bendAngle);
+    void readFieldMap(Inform &msg);
+    bool reinitialize();
+    void setBendEffectiveLength(double startField, double endField);
+    void setBendStrength();
+    void setEngeOriginDelta(double delta);
+    void setFieldCalcParam();
+    void setGapFromFieldMap();
+    bool setupBendGeometry(Inform &msg, double &startField, double &endField);
+    bool setupDefaultFieldMap(Inform &msg);
+    void setFieldBoundaries(double startField, double endField);
+    void setupPusher(PartBunch *bunch);
+    bool treatAsDrift(Inform &msg, double chordlength);
     void retrieveDesignEnergy(double startField);
 
+    CoordinateSystemTrafo getBeginToEnd_local() const;
+
     std::string messageHeader_m;
 
     BorisPusher pusher_m;       /// Pusher used to integrate reference particle
     /// through the bend.
-    std::string fileName_m;     /// Name of field map that defines magnet.
+
     Fieldmap *fieldmap_m;       /// Magnet field map.
     bool fast_m;                /// Flag to turn on fast field calculation.
-    /// (Not currently used.)
-    double angle_m;             /// Bend angle for reference particle with bend
-    /// design energy (radians).
-    double aperture_m;          /// Aperture of magnet in non-bend plane.
-    double designEnergy_m;      /// Bend design energy (eV).
+
     double designRadius_m;      /// Bend design radius (m).
-    double fieldAmplitude_m;    /// Amplitude of magnet field (T).
-    double bX_m;                /// Amplitude of Bx field (T).
-    double bY_m;                /// Amplitude of By field (T).
-    bool angleGreaterThanPi_m;  /// Set to true if bend angle is greater than
-    /// 180 degrees.
-    double entranceAngle_m;     /// Angle between incoming reference trajectory
+
     /// and the entrance face of the magnet (radians).
     double exitAngle_m;         /// Angle between outgoing reference trajectory
     /// and the exit face of the magnet (radians).
     double fieldIndex_m;        /// Dipole field index.
-    double elementEdge_m;       /// Physical start of magnet in s coordinates (m).
     double startField_m;        /// Start of magnet field map in s coordinates (m).
     double endField_m;          /// End of magnet field map in s coordinates (m).
 
@@ -240,28 +221,6 @@ private:
 
     bool recalcRefTraj_m;       /// Re-calculate reference trajectory.
 
-    /*
-     * These two parameters are used to set up the bend geometry.
-     *
-     * When using the default, internal field map, the gap of the
-     * magnet must be set in the input file.
-     *
-     * The magnet length is used initially to define the chord length of
-     * the reference particle arc length. It is used at the start to
-     * define the magnet's geometry. This parameter must be set in the
-     * input file when using the default, internal field map. Otherwise
-     * defining it is optional.
-     */
-    double length_m;
-    double gap_m;
-
-    /// Map of reference particle trajectory.
-    std::vector<double> refTrajMapX_m;
-    std::vector<double> refTrajMapY_m;
-    std::vector<double> refTrajMapZ_m;
-    int refTrajMapSize_m;
-    double refTrajMapStepSize_m;
-
     /*
      * Enge function field map members.
      */
@@ -284,12 +243,15 @@ private:
     std::vector<double> engeCoeffsEntry_m;
     std::vector<double> engeCoeffsExit_m;
 
+    gsl_spline** entryFieldValues_m;
+    gsl_spline** exitFieldValues_m;
+    gsl_interp_accel *entryFieldAccel_m;
+    gsl_interp_accel *exitFieldAccel_m;
+
     /*
      * All coordinates are with respect to (x, z) = (0, 0). It is
      * assumed the ideal reference trajectory passes through this point.
      */
-    double xOriginEngeEntry_m;      /// x coordinate of entry Enge function origin.
-    double zOriginEngeEntry_m;      /// z coordinate of entry Enge function origin.
     double deltaBeginEntry_m;       /// Perpendicular distance from entrance Enge
     /// function origin where Enge function starts.
     double deltaEndEntry_m;         /// Perpendicular distance from entrance Enge
@@ -302,8 +264,6 @@ private:
     double xExit_m;
     double zExit_m;
 
-    double xOriginEngeExit_m;       /// x coordinate of exit Enge function origin.
-    double zOriginEngeExit_m;       /// z coordinate of exit Enge function origin.
     double deltaBeginExit_m;        /// Perpendicular distance from exit Enge
     /// function origin that Enge function starts.
     double deltaEndExit_m;          /// Perpendicular distance from exit Enge
@@ -312,11 +272,57 @@ private:
 
     double cosEntranceAngle_m;
     double sinEntranceAngle_m;
-    double exitEdgeAngle_m;         /// Exit edge angle (radians.
-    double cosExitAngle_m;
-    double sinExitAngle_m;
+    double tanEntranceAngle_m;
+    double tanExitAngle_m;
+
+    CoordinateSystemTrafo beginToEnd_m;
+    CoordinateSystemTrafo beginToEnd_lcs_m; // local coordinate system
+
+    CoordinateSystemTrafo computeAngleTrafo_m;
+    double maxAngle_m;
 };
 
+
+inline
+void Bend::finalise() {
+    online_m = false;
+}
+
+inline
+void Bend::getDimensions(double &sBegin, double &sEnd) const {
+    sBegin = startField_m;
+    sEnd = endField_m;
+}
+
+inline
+double Bend::getBendRadius() const {
+    return designRadius_m;
+}
+
+inline
+double Bend::getEffectiveCenter() const {
+    return elementEdge_m + designRadius_m * angle_m / 2.0;
+}
+
+inline
+double Bend::getEffectiveLength() const {
+    return designRadius_m * angle_m;
+}
+
+inline
+double Bend::getStartElement() const {
+    return elementEdge_m;
+}
+
+inline
+void Bend::setK1(double k1) {
+    if (std::abs(k1) > 0.0) {
+        throw GeneralClassicException("Bend::setK1",
+                                      "Quadrupole field temporarily not supported");
+    }
+    fieldIndex_m = k1;
+}
+
 inline
 void Bend::resetReinitializeFlag() {
     reinitialize_m = true;
@@ -346,39 +352,33 @@ Fieldmap* Bend::getFieldmap()
 }
 
 inline
-double Bend::getFieldAmplitude() const
-{
-    return fieldAmplitude_m;
-}
-
-inline
-double & Bend::getAngle()
+double Bend::getExitAngle() const
 {
-    return angle_m;
+    return exitAngle_m;
 }
 
 inline
-double & Bend::getEntranceAngle()
+void Bend::setExitAngle(double angle)
 {
-    return entranceAngle_m;
+    exitAngle_m = angle;
 }
 
 inline
-double & Bend::getExitAngle()
+double Bend::getMapLength() const
 {
-    return exitAngle_m;
+    return exitParameter2_m - entranceParameter2_m;
 }
 
 inline
-double Bend::getLength()
+CoordinateSystemTrafo Bend::getBeginToEnd() const
 {
-    return length_m;
+    return beginToEnd_m;
 }
 
 inline
-double Bend::getMapLength()
+CoordinateSystemTrafo Bend::getBeginToEnd_local() const
 {
-    return exitParameter2_m - entranceParameter2_m;
+    return beginToEnd_lcs_m;
 }
 
-#endif // CLASSIC_SBend_HH
\ No newline at end of file
+#endif // CLASSIC_BEND_H
\ No newline at end of file
diff --git a/src/Classic/AbsBeamline/CMakeLists.txt b/src/Classic/AbsBeamline/CMakeLists.txt
index 92c50d5a4bfdce51a74f5961a470788fe949c81a..20062f9d17b455e8d0739befd1736b45f8813aed 100644
--- a/src/Classic/AbsBeamline/CMakeLists.txt
+++ b/src/Classic/AbsBeamline/CMakeLists.txt
@@ -4,6 +4,7 @@ set (_SRCS
   BeamBeam.cpp
   BeamlineVisitor.cpp
   Bend.cpp
+  BendBase.cpp
   Collimator.cpp
   Component.cpp
   Corrector.cpp
@@ -24,6 +25,7 @@ set (_SRCS
   Patch.cpp
   Probe.cpp
   RBend.cpp
+  RBend3D.cpp
   RFCavity.cpp
   RFQuadrupole.cpp
   Ring.cpp
@@ -32,6 +34,7 @@ set (_SRCS
   Separator.cpp
   Septum.cpp
   Solenoid.cpp
+  Source.cpp
   Stripper.cpp
   TravelingWave.cpp
   VariableRFCavity.cpp
@@ -41,4 +44,50 @@ include_directories (
   ${CMAKE_CURRENT_SOURCE_DIR}
   )
 
-add_sources(${_SRCS})
\ No newline at end of file
+ADD_OPAL_SOURCES(${_SRCS})
+
+set (HDRS
+    AlignWrapper.h
+    AttributeSet.h
+    BeamBeam.h
+    BeamlineVisitor.h
+    Bend.h
+    BendBase.h
+    Collimator.h
+    Component.h
+    Corrector.h
+    Cyclotron.h
+    CyclotronValley.h
+    Degrader.h
+    Diagnostic.h
+    Drift.h
+    ElementBase.h
+    ElementImage.h
+    Integrator.h
+    Lambertson.h
+    Marker.h
+    Monitor.h
+    Multipole.h
+    Offset.h
+    ParallelPlate.h
+    Patch.h
+    Probe.h
+    RBend.h
+    RBend3D.h
+    RFCavity.h
+    RFQuadrupole.h
+    Ring.h
+    SBend3D.h
+    SBend.h
+    SectorFieldMapComponent.h
+    Separator.h
+    Septum.h
+    Solenoid.h
+    Source.h
+    SpecificElementVisitor.h
+    Stripper.h
+    TravelingWave.h
+    VariableRFCavity.h
+)
+
+install (FILES ${HDRS} DESTINATION "${CMAKE_INSTALL_PREFIX}/include/AbsBeamline")
\ No newline at end of file
diff --git a/src/Classic/AbsBeamline/Collimator.cpp b/src/Classic/AbsBeamline/Collimator.cpp
index 493d7a0df3415172962a80801ef9fcf4d012fa15..8e41fc23026ba7cdb56ed559f97d673cc6e9b1b1 100644
--- a/src/Classic/AbsBeamline/Collimator.cpp
+++ b/src/Classic/AbsBeamline/Collimator.cpp
@@ -39,7 +39,6 @@ Collimator::Collimator():
     Component(),
     filename_m(""),
     plane_m(OFF),
-    position_m(0.0),
     PosX_m(0),
     PosY_m(0),
     PosZ_m(0),
@@ -77,7 +76,6 @@ Collimator::Collimator(const Collimator &right):
     Component(right),
     filename_m(right.filename_m),
     plane_m(right.plane_m),
-    position_m(right.position_m),
     PosX_m(right.PosX_m),
     PosY_m(right.PosY_m),
     PosZ_m(right.PosZ_m),
@@ -119,7 +117,6 @@ Collimator::Collimator(const std::string &name):
     Component(name),
     filename_m(""),
     plane_m(OFF),
-    position_m(0.0),
     PosX_m(0),
     PosY_m(0),
     PosZ_m(0),
@@ -173,7 +170,7 @@ inline bool Collimator::isInColl(Vector_t R, Vector_t P, double recpgamma) {
     */
     const double z = R(2) + P(2) * recpgamma;
 
-    if((z > position_m) && (z <= position_m + getElementLength())) {
+    if((z > 0.0) && (z <= getElementLength())) {
         if(isAPepperPot_m) {
 
             /**
@@ -220,29 +217,30 @@ inline bool Collimator::isInColl(Vector_t R, Vector_t P, double recpgamma) {
     return false;
 }
 
-bool Collimator::apply(const size_t &i, const double &t, double E[], double B[]) {
-    Vector_t Ev(0, 0, 0), Bv(0, 0, 0);
-    return apply(i, t, Ev, Bv);
-}
-
 bool Collimator::apply(const size_t &i, const double &t, Vector_t &E, Vector_t &B) {
-    const Vector_t &R = RefPartBunch_m->R[i] - Vector_t(dx_m, dy_m, ds_m); // including the missaligment
+    const Vector_t &R = RefPartBunch_m->R[i];
     const Vector_t &P = RefPartBunch_m->P[i];
-    const double recpgamma = Physics::c * RefPartBunch_m->getdT() / sqrt(1.0  + dot(P, P));
-    bool pdead = false;
-    pdead = isInColl(R,P,recpgamma);
+    const double &dt = RefPartBunch_m->dt[i];
+    const double recpgamma = Physics::c * dt / sqrt(1.0  + dot(P, P));
+    bool pdead = isInColl(R, P, recpgamma);
+
     if(pdead) {
-      if (lossDs_m) {
-	double frac = (R(2) - position_m) / P(2) * recpgamma;
-	lossDs_m->addParticle(R,P, RefPartBunch_m->ID[i], t + frac * RefPartBunch_m->getdT(), 0);
-      }
-      ++losses_m;
+        if (lossDs_m) {
+            double frac = -R(2) / P(2) * recpgamma;
+            lossDs_m->addParticle(R, P,
+                                  RefPartBunch_m->ID[i],
+                                  t + frac * dt, 0);
+        }
+        ++ losses_m;
     }
+
     return pdead;
 }
 
-bool Collimator::apply(const Vector_t &R, const Vector_t &centroid, const double &t, Vector_t &E, Vector_t &B) {
-    return false;
+bool Collimator::applyToReferenceParticle(const Vector_t &R, const Vector_t &P, const double &t, Vector_t &E, Vector_t &B) {
+    const double dt = RefPartBunch_m->getdT();
+    const double recpgamma = Physics::c * dt / sqrt(1.0  + dot(P, P));
+    return isInColl(R, P, recpgamma);
 }
 
 bool Collimator::checkCollimator(Vector_t r, Vector_t rmin, Vector_t rmax) {
@@ -300,35 +298,34 @@ bool Collimator::checkCollimator(PartBunch &bunch, const int turnnumber, const d
     return flagNeedUpdate;
 }
 
-void Collimator::initialise(PartBunch *bunch, double &startField, double &endField, const double &scaleFactor) {
+void Collimator::initialise(PartBunch *bunch, double &startField, double &endField) {
     RefPartBunch_m = bunch;
-    position_m = startField;
-    endField = position_m + getElementLength();
+    endField = startField + getElementLength();
 
     sphys_m = getSurfacePhysics();
 
-    //if (!sphys_m) {
+    // if (!sphys_m) {
     if (filename_m == std::string(""))
-      lossDs_m = std::unique_ptr<LossDataSink>(new LossDataSink(getName(), !Options::asciidump));
-    else 
-      lossDs_m = std::unique_ptr<LossDataSink>(new LossDataSink(filename_m.substr(0, filename_m.rfind(".")), !Options::asciidump));
-      //}
-    
+        lossDs_m = std::unique_ptr<LossDataSink>(new LossDataSink(getName(), !Options::asciidump));
+    else
+        lossDs_m = std::unique_ptr<LossDataSink>(new LossDataSink(filename_m.substr(0, filename_m.rfind(".")), !Options::asciidump));
+    // }
+
     goOnline(-1e6);
 }
 
-void Collimator::initialise(PartBunch *bunch, const double &scaleFactor) {
+void Collimator::initialise(PartBunch *bunch) {
     RefPartBunch_m = bunch;
 
     sphys_m = getSurfacePhysics();
 
-    //    if (!sphys_m) {
+    // if (!sphys_m) {
     if (filename_m == std::string(""))
-      lossDs_m = std::unique_ptr<LossDataSink>(new LossDataSink(getName(), !Options::asciidump));
+        lossDs_m = std::unique_ptr<LossDataSink>(new LossDataSink(getName(), !Options::asciidump));
     else
-      lossDs_m = std::unique_ptr<LossDataSink>(new LossDataSink(filename_m.substr(0, filename_m.rfind(".")), !Options::asciidump));
-    //    }
-    
+        lossDs_m = std::unique_ptr<LossDataSink>(new LossDataSink(filename_m.substr(0, filename_m.rfind(".")), !Options::asciidump));
+    // }
+
     goOnline(-1e6);
 }
 
@@ -374,10 +371,10 @@ void Collimator::print() {
               << " nx= " << nHolesX_m << " ny= " << nHolesY_m << " pitch= " << pitch_m << endl;
     else if(isASlit_m)
         *gmsg << "* Slit x= " << getXsize() << " Slit y= " << getYsize()
-              << " start= " << position_m << " fn= " << filename_m << endl;
+              << " fn= " << filename_m << endl;
     else if(isARColl_m)
         *gmsg << "* RCollimator a= " << getXsize() << " b= " << getYsize()
-              << " start= " << position_m << " fn= " << filename_m
+              << " fn= " << filename_m
               << " ny= " << nHolesY_m << " pitch= " << pitch_m << endl;
     else if(isACColl_m)
         *gmsg << "* CCollimator angle start " << xstart_m << " (Deg) angle end " << ystart_m << " (Deg) "
@@ -385,13 +382,14 @@ void Collimator::print() {
     else if(isAWire_m)
         *gmsg << "* Wire x= " << x0_m << " y= " << y0_m << endl;
     else
-        *gmsg << "* ECollimator a= " << getXsize() << " b= " << b_m << " start= " << position_m
-              << " fn= " << filename_m << " ny= " << nHolesY_m << " pitch= " << pitch_m << endl;
+        *gmsg << "* ECollimator a= " << getXsize() << " b= " << b_m << " fn= " << filename_m
+              << " ny= " << nHolesY_m << " pitch= " << pitch_m << endl;
 }
 
 void Collimator::goOffline() {
     if (online_m && lossDs_m)
         lossDs_m->save();
+    lossDs_m.reset(0);
     online_m = false;
 }
 
@@ -410,139 +408,9 @@ string Collimator::getOutputFN() {
         return filename_m.substr(0, filename_m.rfind("."));
 }
 
-unsigned int Collimator::getLosses() const {
-    return losses_m;
-}
-
-void Collimator::setXsize(double a) {
-    a_m = a;
-}
-
-void Collimator::setYsize(double b) {
-    b_m = b;
-}
-
-void Collimator::setXpos(double x0) {
-    x0_m = x0;
-}
-
-void Collimator::setYpos(double y0) {
-    y0_m = y0;
-}
-
-
-double Collimator::getXsize(double a) {
-    return a_m;
-}
-
-double Collimator::getYsize(double b) {
-    return b_m;
-}
-
-double Collimator::getXpos() {
-    return x0_m;
-}
-
-double Collimator::getYpos() {
-    return y0_m;
-
-    // --------Cyclotron collimator
-}
-void Collimator::setXStart(double xstart) {
-    xstart_m = xstart;
-}
-
-void Collimator::setXEnd(double xend) {
-    xend_m = xend;
-}
-
-void Collimator::setYStart(double ystart) {
-    ystart_m = ystart;
-}
-
-void Collimator::setYEnd(double yend) {
-    yend_m = yend;
-}
-
-void Collimator::setZStart(double zstart) {
-    zstart_m = zstart;
-}
-
-void Collimator::setZEnd(double zend) {
-    zend_m = zend;
-}
-
-void Collimator::setWidth(double width) {
-    width_m = width;
-}
-
-double Collimator::getXStart() {
-    return xstart_m;
-}
-
-double Collimator::getXEnd() {
-    return xend_m;
-}
-
-double Collimator::getYStart() {
-    return ystart_m;
-}
-
-double Collimator::getYEnd() {
-    return yend_m;
-}
-
-double Collimator::getZStart() {
-    return zstart_m;
-}
-
-double Collimator::getZEnd() {
-    return zend_m;
-}
-
-double Collimator::getWidth() {
-    return width_m;
-}
-
-//-------------------------------
-
-void Collimator::setRHole(double r) {
-    rHole_m = r;
-}
-void Collimator::setNHoles(unsigned int nx, unsigned int ny) {
-    nHolesX_m = nx;
-    nHolesY_m = ny;
-}
-void Collimator::setPitch(double p) {
-    pitch_m = p;
-}
-
-
-void Collimator::setPepperPot() {
-    isAPepperPot_m = true;
-}
-void Collimator::setSlit() {
-    isASlit_m = true;
-}
-
-void Collimator::setRColl() {
-    isARColl_m = true;
-}
-
-void Collimator::setCColl() {
-    isACColl_m = true;
-}
-
-void Collimator::setWire() {
-    isAWire_m = true;
-}
 void Collimator::getDimensions(double &zBegin, double &zEnd) const {
-    zBegin = position_m;
-    zEnd = position_m + getElementLength();
-
-    // zBegin = position_m - 0.005;
-    //  zEnd = position_m + 0.005;
-
+    zBegin = 0.0;
+    zEnd = getElementLength();
 }
 
 ElementBase::ElementType Collimator::getType() const {
@@ -612,4 +480,4 @@ int Collimator::checkPoint(const double &x, const double &y) {
         }
     }
     return (cn & 1);  // 0 if even (out), and 1 if odd (in)
-}
+}
\ No newline at end of file
diff --git a/src/Classic/AbsBeamline/Collimator.h b/src/Classic/AbsBeamline/Collimator.h
index f18963f6793fd651c2a18437803b967d9815b5f8..5c7654ad9bb0c73bd51238b744925088c5249d95 100644
--- a/src/Classic/AbsBeamline/Collimator.h
+++ b/src/Classic/AbsBeamline/Collimator.h
@@ -67,19 +67,17 @@ public:
     /// Return the vertical half-aperture.
     virtual double getYsize() const {return b_m;}
 
-    virtual bool apply(const size_t &i, const double &t, double E[], double B[]);
-
     virtual bool apply(const size_t &i, const double &t, Vector_t &E, Vector_t &B);
 
-    virtual bool apply(const Vector_t &R, const Vector_t &centroid, const double &t, Vector_t &E, Vector_t &B);
+    virtual bool applyToReferenceParticle(const Vector_t &R, const Vector_t &P, const double &t, Vector_t &E, Vector_t &B);
 
     virtual bool checkCollimator(PartBunch &bunch, const int turnnumber, const double t, const double tstep);
 
     virtual bool checkCollimator(Vector_t r, Vector_t rmin, Vector_t rmax);
 
-    virtual void initialise(PartBunch *bunch, double &startField, double &endField, const double &scaleFactor);
+    virtual void initialise(PartBunch *bunch, double &startField, double &endField);
 
-    virtual void initialise(PartBunch *bunch, const double &scaleFactor);
+    virtual void initialise(PartBunch *bunch);
 
     virtual void finalise();
 
@@ -159,7 +157,7 @@ private:
 
     std::string filename_m;               /**< The name of the outputfile*/
     Plane plane_m;
-    double position_m;
+
     std::vector<double> PosX_m;
     std::vector<double> PosY_m;
     std::vector<double> PosZ_m;
@@ -207,4 +205,160 @@ private:
 
 };
 
+inline
+unsigned int Collimator::getLosses() const {
+    return losses_m;
+}
+
+inline
+void Collimator::setXsize(double a) {
+    a_m = a;
+}
+
+inline
+void Collimator::setYsize(double b) {
+    b_m = b;
+}
+
+inline
+void Collimator::setXpos(double x0) {
+    x0_m = x0;
+}
+
+inline
+void Collimator::setYpos(double y0) {
+    y0_m = y0;
+}
+
+inline
+double Collimator::getXsize(double a) {
+    return a_m;
+}
+
+inline
+double Collimator::getYsize(double b) {
+    return b_m;
+}
+
+inline
+double Collimator::getXpos() {
+    return x0_m;
+}
+
+inline
+double Collimator::getYpos() {
+    return y0_m;
+}
+
+inline
+void Collimator::setXStart(double xstart) {
+    xstart_m = xstart;
+}
+
+inline
+void Collimator::setXEnd(double xend) {
+    xend_m = xend;
+}
+
+inline
+void Collimator::setYStart(double ystart) {
+    ystart_m = ystart;
+}
+
+inline
+void Collimator::setYEnd(double yend) {
+    yend_m = yend;
+}
+
+inline
+void Collimator::setZStart(double zstart) {
+    zstart_m = zstart;
+}
+
+inline
+void Collimator::setZEnd(double zend) {
+    zend_m = zend;
+}
+
+inline
+void Collimator::setWidth(double width) {
+    width_m = width;
+}
+
+inline
+double Collimator::getXStart() {
+    return xstart_m;
+}
+
+inline
+double Collimator::getXEnd() {
+    return xend_m;
+}
+
+inline
+double Collimator::getYStart() {
+    return ystart_m;
+}
+
+inline
+double Collimator::getYEnd() {
+    return yend_m;
+}
+
+inline
+double Collimator::getZStart() {
+    return zstart_m;
+}
+
+inline
+double Collimator::getZEnd() {
+    return zend_m;
+}
+
+inline
+double Collimator::getWidth() {
+    return width_m;
+}
+
+inline
+void Collimator::setRHole(double r) {
+    rHole_m = r;
+}
+
+inline
+void Collimator::setNHoles(unsigned int nx, unsigned int ny) {
+    nHolesX_m = nx;
+    nHolesY_m = ny;
+}
+
+inline
+void Collimator::setPitch(double p) {
+    pitch_m = p;
+}
+
+inline
+void Collimator::setPepperPot() {
+    isAPepperPot_m = true;
+}
+
+inline
+void Collimator::setSlit() {
+    isASlit_m = true;
+}
+
+inline
+void Collimator::setRColl() {
+    isARColl_m = true;
+}
+
+inline
+void Collimator::setCColl() {
+    isACColl_m = true;
+}
+
+inline
+void Collimator::setWire() {
+    isAWire_m = true;
+}
+
 #endif // CLASSIC_Collimator_HH
diff --git a/src/Classic/AbsBeamline/Component.cpp b/src/Classic/AbsBeamline/Component.cpp
index e47becf2bdd0fc9331c4e78a0c7d779bfd28be3a..14b1d1aaf68e00101e1dee9d80268ed05e58ae69 100644
--- a/src/Classic/AbsBeamline/Component.cpp
+++ b/src/Classic/AbsBeamline/Component.cpp
@@ -22,7 +22,7 @@
 
 #include "AbsBeamline/Component.h"
 #include "Utilities/LogicalError.h"
-
+#include "Algorithms/PartBunch.h"
 
 // Class Component
 // ------------------------------------------------------------------------
@@ -33,10 +33,6 @@
 
 Component::Component():
     ElementBase(),
-    dx_m(0.0),
-    dy_m(0.0),
-    ds_m(0.0),
-    Orientation_m(Vector_t(0.0, 0.0, 0.0)),
     exit_face_slope_m(0.0),
     RefPartBunch_m(NULL),
     online_m(false)
@@ -45,10 +41,6 @@ Component::Component():
 
 Component::Component(const Component &right):
     ElementBase(right),
-    dx_m(right.dx_m),
-    dy_m(right.dy_m),
-    ds_m(right.ds_m),
-    Orientation_m(right.Orientation_m),
     exit_face_slope_m(right.exit_face_slope_m),
     RefPartBunch_m(right.RefPartBunch_m),
     online_m(right.online_m)
@@ -57,10 +49,6 @@ Component::Component(const Component &right):
 
 Component::Component(const std::string &name):
     ElementBase(name),
-    dx_m(0.0),
-    dy_m(0.0),
-    ds_m(0.0),
-    Orientation_m(Vector_t(0.0, 0.0, 0.0)),
     exit_face_slope_m(0.0),
     RefPartBunch_m(NULL),
     online_m(false)
@@ -99,18 +87,39 @@ bool Component::Online() {
     return online_m;
 }
 
-void Component::setMisalignment(double x, double y, double s) {
-    dx_m = x;
-    dy_m = y;
-    ds_m = s;
+ElementBase::ElementType Component::getType() const {
+    return ElementBase::ANY;
 }
 
-void Component::getMisalignment(double &x, double &y, double &s) const {
-    x = dx_m;
-    y = dy_m;
-    s = ds_m;
+bool Component::apply(const size_t &i,
+                      const double &t,
+                      Vector_t &E,
+                      Vector_t &B) {
+    const Vector_t &R = RefPartBunch_m->R[i];
+    if (R(2) >= 0.0 && R(2) < getElementLength()) {
+        if (!isInsideTransverse(R)) return true;
+    }
+    return false;
 }
 
-ElementBase::ElementType Component::getType() const {
-    return ElementBase::ANY;
-}
\ No newline at end of file
+bool Component::apply(const Vector_t &R,
+                      const Vector_t &P,
+                      const double &t,
+                      Vector_t &E,
+                      Vector_t &B) {
+    if (R(2) >= 0.0 && R(2) < getElementLength()) {
+        if (!isInsideTransverse(R)) return true;
+    }
+    return false;
+}
+
+bool Component::applyToReferenceParticle(const Vector_t &R,
+                                         const Vector_t &P,
+                                         const double &t,
+                                         Vector_t &E,
+                                         Vector_t &B) {
+    if (R(2) >= 0.0 && R(2) < getElementLength()) {
+        if (!isInsideTransverse(R)) return true;
+    }
+    return false;
+}
diff --git a/src/Classic/AbsBeamline/Component.h b/src/Classic/AbsBeamline/Component.h
index bf6b5e73b2fd9a6e15e3e4a03090e50a61723e99..cd2117eb5e582f73370a562a00ec82d27f487ec2 100644
--- a/src/Classic/AbsBeamline/Component.h
+++ b/src/Classic/AbsBeamline/Component.h
@@ -102,13 +102,27 @@ public:
 
     virtual void addKT(int i, double t, Vector_t &K) {};
 
-    virtual bool apply(const size_t &i, const double &t, double E[], double B[]) = 0;
+    virtual bool apply(const size_t &i,
+                       const double &t,
+                       Vector_t &E,
+                       Vector_t &B);
 
-    virtual bool apply(const size_t &i, const double &t, Vector_t &E, Vector_t &B) = 0;
+    virtual bool apply(const Vector_t &R,
+                       const Vector_t &P,
+                       const double &t,
+                       Vector_t &E,
+                       Vector_t &B);
 
-    virtual bool apply(const Vector_t &R, const Vector_t &centroid, const double &t, Vector_t &E, Vector_t &B) = 0;
+    virtual bool applyToReferenceParticle(const Vector_t &R,
+                                          const Vector_t &P,
+                                          const double &t,
+                                          Vector_t &E,
+                                          Vector_t &B);
 
-    virtual void initialise(PartBunch *bunch, double &startField, double &endField, const double &scaleFactor) = 0;
+    virtual double getDesignEnergy() const;
+    virtual void setDesignEnergy(double energy, bool changeable = true);
+
+    virtual void initialise(PartBunch *bunch, double &startField, double &endField) = 0;
 
     virtual void finalise() = 0;
 
@@ -122,13 +136,13 @@ public:
 
     virtual bool Online();
 
-    void getOrientation(Vector_t &, double &) const;  // first component is alpha, second is beta. the third component is always neglected.
-    // alpha is defined as the angle between projection of the normal of the face of the element onto
-    // the s-u plane and the s vector. for beta the following is valid:
-    // beta = arccos(|n_{parallel}|) where n_{parallel} is the projection of the normal onto the s-u
-    // plane
+    // void getOrientation(Vector_t &, double &) const;  // first component is alpha, second is beta. the third component is always neglected.
+    // // alpha is defined as the angle between projection of the normal of the face of the element onto
+    // // the s-u plane and the s vector. for beta the following is valid:
+    // // beta = arccos(|n_{parallel}|) where n_{parallel} is the projection of the normal onto the s-u
+    // // plane
 
-    void setOrientation(const Vector_t &direction);
+    // void setOrientation(const Vector_t &direction);
 
     virtual void getDimensions(double &zBegin, double &zEnd) const = 0;
 
@@ -157,18 +171,11 @@ public:
     virtual void trackMap(FVps<double, 6> &map, const PartData &,
                           bool revBeam, bool revTrack) const;
 
-    void setMisalignment(double x, double y, double s);
-
-    void getMisalignment(double &x, double &y, double &s) const;
-
     void setExitFaceSlope(const double &);
 
 protected:
 
-    double dx_m;
-    double dy_m;
-    double ds_m;
-    Vector_t Orientation_m;
+    // Vector_t Orientation_m;
     double exit_face_slope_m;
 
     PartBunch *RefPartBunch_m;
@@ -197,14 +204,23 @@ inline EBVectors Component::EBfield(const Point3D &P) const
 inline EBVectors Component::EBfield(const Point3D &P, double t) const
 { return getField().EBfield(P, t); }
 
-inline void Component::getOrientation(Vector_t &ori, double &m) const {
-    ori = Orientation_m;
-    m = exit_face_slope_m;
-}
+// inline void Component::getOrientation(Vector_t &ori, double &m) const {
+//     ori = Orientation_m;
+//     m = exit_face_slope_m;
+// }
 
-inline void Component::setOrientation(const Vector_t &direction)
-{ Orientation_m = direction; }
+// inline void Component::setOrientation(const Vector_t &direction)
+// { Orientation_m = direction; }
 
 inline void Component::setExitFaceSlope(const double &m)
 { exit_face_slope_m = m; }
-#endif // CLASSIC_Component_HH
\ No newline at end of file
+
+inline void Component::setDesignEnergy(double , bool )
+{ }
+
+inline double Component::getDesignEnergy() const
+{
+    return -1.0;
+}
+
+#endif // CLASSIC_Component_HH
diff --git a/src/Classic/AbsBeamline/Corrector.cpp b/src/Classic/AbsBeamline/Corrector.cpp
index bad5eab3e7b6d56eda5cf4b37f2ef08fb2069658..5e8a8bf64be413571b4a450191fa486fe42a0f43 100644
--- a/src/Classic/AbsBeamline/Corrector.cpp
+++ b/src/Classic/AbsBeamline/Corrector.cpp
@@ -23,34 +23,43 @@
 #include "Algorithms/PartBunch.h"
 #include "Physics/Physics.h"
 #include "Utilities/GeneralClassicException.h"
+#include "Utilities/Util.h"
+
+extern Inform *gmsg;
 
 // Class Corrector
 // ------------------------------------------------------------------------
 
 Corrector::Corrector():
   Component(),
-  startField_m(0.0),
-  endField_m(0.0),
   kickX_m(0.0),
-  kickY_m(0.0)
+  kickY_m(0.0),
+  designEnergy_m(0.0),
+  designEnergyChangeable_m(true),
+  kickFieldSet_m(false),
+  kickField_m(0.0)
 { }
 
 
 Corrector::Corrector(const Corrector &right):
   Component(right),
-  startField_m(right.startField_m),
-  endField_m(right.endField_m),
   kickX_m(right.kickX_m),
-  kickY_m(right.kickY_m)
+  kickY_m(right.kickY_m),
+  designEnergy_m(right.designEnergy_m),
+  designEnergyChangeable_m(true),
+  kickFieldSet_m(right.kickFieldSet_m),
+  kickField_m(right.kickField_m)
 { }
 
 
 Corrector::Corrector(const std::string &name):
   Component(name),
-  startField_m(0.0),
-  endField_m(0.0),
   kickX_m(0.0),
-  kickY_m(0.0)
+  kickY_m(0.0),
+  designEnergy_m(0.0),
+  designEnergyChangeable_m(true),
+  kickFieldSet_m(false),
+  kickField_m(0.0)
 { }
 
 
@@ -62,58 +71,91 @@ void Corrector::accept(BeamlineVisitor &visitor) const {
     visitor.visitCorrector(*this);
 }
 
-bool Corrector::apply(const size_t &i, const double &t, double E[], double B[]) {
-  B[0] = kickField_m(0);
-  B[1] = kickField_m(1);
+bool Corrector::apply(const size_t &i, const double &t, Vector_t &E, Vector_t &B) {
+    Vector_t &R = RefPartBunch_m->R[i];
 
-  return false;
-}
+    if (R(2) >= 0.0 && R(2) < getElementLength()) {
+        if (!isInsideTransverse(R)) return true;
 
-bool Corrector::apply(const size_t &i, const double &t, Vector_t &E, Vector_t &B) {
-  B += kickField_m;
-  return false;
+        B += kickField_m;
+    }
+
+    return false;
 }
 
-bool Corrector::apply(const Vector_t &R, const Vector_t &centroid, const double &t, Vector_t &E, Vector_t &B) {
-  return false;
+bool Corrector::apply(const Vector_t &R,
+                      const Vector_t &P,
+                      const double &t,
+                      Vector_t &E,
+                      Vector_t &B) {
+    if (R(2) >= 0.0 && R(2) < getElementLength()) {
+        if (!isInsideTransverse(R)) return true;
+
+        B += kickField_m;
+    }
+
+    return false;
 }
 
-void Corrector::initialise(PartBunch *bunch, double &startField, double &endField, const double &scaleFactor) {
-    endField_m = endField = startField + getElementLength();
+void Corrector::initialise(PartBunch *bunch, double &startField, double &endField) {
+    endField = startField + getElementLength();
     RefPartBunch_m = bunch;
-    startField_m = startField;
 }
 
 void Corrector::finalise()
 { }
 
-void Corrector::goOnline(const double &kineticEnergy) {
-    if (kineticEnergy < 0.0) {
-        throw GeneralClassicException("Corrector::goOnline", "given kinetic energy is negative");
-    }
+void Corrector::goOnline(const double &) {
+    // if (kineticEnergy < 0.0) {
+    //     throw GeneralClassicException("Corrector::goOnline", "given kinetic energy is negative");
+    // }
 
 
     const double pathLength = getGeometry().getElementLength();
     const double minLength = Physics::c * RefPartBunch_m->getdT();
-    if (pathLength < minLength) throw GeneralClassicException("Corrector::goOnline", "length of corrector, L= " + std::to_string(pathLength) + ", shorter than distance covered during one time step, dS= " + std::to_string(minLength));
+    if (pathLength < minLength) {
+        throw GeneralClassicException("Corrector::goOnline",
+                                      "length of corrector, L= " + std::to_string(pathLength) +
+                                      ", shorter than distance covered during one time step, dS= " + std::to_string(minLength));
+    }
 
-    const double momentum = sqrt(std::pow(kineticEnergy * 1e6, 2.0) + 2.0 * kineticEnergy * 1e6 * RefPartBunch_m->getM());
-    const double magnitude = momentum / (Physics::c * pathLength);
-    kickField_m = magnitude * RefPartBunch_m->getQ() * Vector_t(kickY_m, -kickX_m, 0.0);
+    if (!kickFieldSet_m) {
+        const double momentum = sqrt(std::pow(designEnergy_m, 2.0) + 2.0 * designEnergy_m * RefPartBunch_m->getM());
+        const double magnitude = momentum / (Physics::c * pathLength);
+        kickField_m = magnitude * RefPartBunch_m->getQ() * Vector_t(kickY_m, -kickX_m, 0.0);
+    }
 
     online_m = true;
 }
 
+void Corrector::setDesignEnergy(double ekin, bool changeable) {
+    if (designEnergyChangeable_m) {
+        designEnergy_m = ekin;
+        designEnergyChangeable_m = changeable;
+    }
+    if (RefPartBunch_m) {
+        // designEnergy_m = ekin;
+        // designEnergyChangeable_m = changeable;
+
+        if (!kickFieldSet_m) {
+            const double pathLength = getGeometry().getElementLength();
+            const double momentum = sqrt(std::pow(designEnergy_m, 2.0) + 2.0 * designEnergy_m * RefPartBunch_m->getM());
+            const double magnitude = momentum / (Physics::c * pathLength);
+            kickField_m = magnitude * RefPartBunch_m->getQ() * Vector_t(kickY_m, -kickX_m, 0.0);
+        }
+    }
+}
+
 bool Corrector::bends() const {
     return false;
 }
 
 void Corrector::getDimensions(double &zBegin, double &zEnd) const
 {
-  zBegin = startField_m;
-  zEnd = startField_m + getElementLength();
+  zBegin = 0.0;
+  zEnd = getElementLength();
 }
 
 ElementBase::ElementType Corrector::getType() const {
     return CORRECTOR;
-}
\ No newline at end of file
+}
diff --git a/src/Classic/AbsBeamline/Corrector.h b/src/Classic/AbsBeamline/Corrector.h
index a84d43b1c3795f5f5b868cbb2d6b6520d1623eae..f0a9915f22d0688186532a71f4906a07e1089021 100644
--- a/src/Classic/AbsBeamline/Corrector.h
+++ b/src/Classic/AbsBeamline/Corrector.h
@@ -26,7 +26,6 @@
 #include "BeamlineGeometry/StraightGeometry.h"
 #include "Fields/BDipoleField.h"
 
-
 // Class Corrector
 // ------------------------------------------------------------------------
 /// Interface for general corrector.
@@ -77,13 +76,18 @@ public:
     /// Return the plane on which the corrector acts.
     virtual Plane getPlane() const = 0;
 
-    virtual bool apply(const size_t &i, const double &t, double E[], double B[]);
-
-    virtual bool apply(const size_t &i, const double &t, Vector_t &E, Vector_t &B);
+    virtual bool apply(const size_t &i,
+                       const double &t,
+                       Vector_t &E,
+                       Vector_t &B);
 
-    virtual bool apply(const Vector_t &R, const Vector_t &centroid, const double &t, Vector_t &E, Vector_t &B);
+    virtual bool apply(const Vector_t &R,
+                       const Vector_t &P,
+                       const double &t,
+                       Vector_t &E,
+                       Vector_t &B);
 
-    virtual void initialise(PartBunch *bunch, double &startField, double &endField, const double &scaleFactor);
+    virtual void initialise(PartBunch *bunch, double &startField, double &endField);
 
     virtual void goOnline(const double &kineticEnergy);
 
@@ -99,16 +103,20 @@ public:
 
     void setKickY(double k);
 
+    virtual void setDesignEnergy(double ekin, bool changeable = true);
+
     double getKickX() const;
 
     double getKickY() const;
 
+    void setKickField(const Vector_t &k0);
 
 private:
-    double startField_m;
-    double endField_m;
     double kickX_m;
     double kickY_m;
+    double designEnergy_m;
+    bool designEnergyChangeable_m;
+    bool kickFieldSet_m;
 
     Vector_t kickField_m;
 
@@ -118,11 +126,6 @@ protected:
     void operator=(const Corrector &);
 
     Plane plane_m;
-
-    double position_m;
-    bool   informed_m;
-
-
 };
 
 inline
@@ -145,4 +148,9 @@ double Corrector::getKickY() const {
     return kickY_m;
 }
 
-#endif // CLASSIC_Corrector_HH
\ No newline at end of file
+inline
+void Corrector::setKickField(const Vector_t &k0) {
+    kickField_m = k0;
+    kickFieldSet_m = true;
+}
+#endif // CLASSIC_Corrector_HH
diff --git a/src/Classic/AbsBeamline/Cyclotron.cpp b/src/Classic/AbsBeamline/Cyclotron.cpp
index fba191ac22ea875c8fec6c740b773bdd3e5d4fa9..b1fd830c1847596b39b48bbebc91643b9cfbb7e4 100644
--- a/src/Classic/AbsBeamline/Cyclotron.cpp
+++ b/src/Classic/AbsBeamline/Cyclotron.cpp
@@ -92,7 +92,7 @@ Cyclotron::~Cyclotron() {
 }
 
 
-void Cyclotron::applyTrimCoil(double r, double z, double slope, double tcr1, double tcr2, double magnitude, double *br, double *bz) { 
+void Cyclotron::applyTrimCoil(double r, double z, double slope, double tcr1, double tcr2, double magnitude, double *br, double *bz) {
   /// updated bz and br with trim coil contributions
   if(tcr1 != 0.0 && tcr2 != 0.0) {
     const double Amax1 = 1;
@@ -117,7 +117,7 @@ void Cyclotron::applyTrimCoil(double r, double z, double slope, double tcr1, dou
     double part4 = (Amax2 - Amin) * h2 * log(10) / slope / (1 + part2) / (1 + part2) * part2;
     double dr = magnitude / 2.78 * (part3 + part4);
     double btr = magnitude / 2.78 * (Amin + (Amax1 - Amin) / (1 + part1) + (Amax2 - Amin) / (1 + part2) - 1.0);
-    
+
     if(r < tcr2)       {
       *bz -= btr;
       *br -= dr * z;
@@ -360,21 +360,6 @@ void Cyclotron::setFMHighE(double e) { fmHighE_m = e;}
 double Cyclotron::getFMHighE() const { return fmHighE_m;}
 
 
-bool Cyclotron::apply(const size_t &id, const double &t, double E[], double B[]) {
-    Vector_t Ev(0, 0, 0), Bv(0, 0, 0);
-
-    if(apply(id, t, Ev, Bv)) return true;
-
-    E[0] = Ev(0);
-    E[1] = Ev(1);
-    E[2] = Ev(2);
-    B[0] = Bv(0);
-    B[1] = Bv(1);
-    B[2] = Bv(2);
-
-    return false;
-}
-
 bool Cyclotron::apply(const size_t &id, const double &t, Vector_t &E, Vector_t &B) {
 
   bool flagNeedUpdate = false;
@@ -390,7 +375,7 @@ bool Cyclotron::apply(const size_t &id, const double &t, Vector_t &E, Vector_t &
 
   } else{
 
-      flagNeedUpdate = apply(RefPartBunch_m->R[id], Vector_t(0.0), t, E, B);
+      flagNeedUpdate = apply(RefPartBunch_m->R[id], RefPartBunch_m->P[id], t, E, B);
       if(flagNeedUpdate){
           Inform gmsgALL("OPAL ", INFORM_ALL_NODES);
           gmsgALL << getName() << ": particle "<< id <<" out of the field map boundary!"<< endl;
@@ -405,7 +390,7 @@ bool Cyclotron::apply(const size_t &id, const double &t, Vector_t &E, Vector_t &
   return flagNeedUpdate;
 }
 
-bool Cyclotron::apply(const Vector_t &R, const Vector_t &centroid, const double &t, Vector_t &E, Vector_t &B) {
+bool Cyclotron::apply(const Vector_t &R, const Vector_t &P, const double &t, Vector_t &E, Vector_t &B) {
 
     const double rad = sqrt(R[0] * R[0] + R[1] * R[1]);
     const double xir = (rad - BP.rmin) / BP.delr;
@@ -531,9 +516,9 @@ bool Cyclotron::apply(const Vector_t &R, const Vector_t &centroid, const double
         bt = - btf;
 
 
-        /* Br Btheta -> Bx By */	
+        /* Br Btheta -> Bx By */
 
-	if (slptcV_m.size() != 0) {	 
+	if (slptcV_m.size() != 0) {
 	  for (unsigned int i=0; i<slptcV_m.size(); i++)
 	    applyTrimCoil(rad, R[2], slptcV_m[i], tcr1V_m[i], tcr2V_m[i], mbtcV_m[i], &br, &bz);
 	}
@@ -570,15 +555,15 @@ bool Cyclotron::apply(const Vector_t &R, const Vector_t &centroid, const double
                 if(!(*fi)->getFieldstrength(R, tmpE, tmpB)) {
 		  ++fcount;
                   double phase = 2.0 * pi * (1E-3 * (*rffi)) * t + *rfphii;
-		  
+
 		  double ebscale = *escali;
                   E += ebscale * cos(phase) * tmpE;
                   B -= ebscale * sin(phase) * tmpB;
-                  
+
 //                INFOMSG("Field " << fcount << " BANDRF E= " << tmpE << " R= " << R << " phase " << phase << endl);
                 }
             }
-    	} 
+	}
     } else if(myBFieldType_m == SYNCHRO) {
         //The RF field is suppose to be sampled on a cartesian grid
         vector<Fieldmap *>::const_iterator fi  = RFfields_m.begin();
@@ -626,29 +611,29 @@ bool Cyclotron::apply(const Vector_t &R, const Vector_t &centroid, const double
 		    }
 
                     double phase = 2.0 * pi * 1.0E-3 * frequency * t + (*rfphii);  // f in [MHz], t in [ns]
-		  
+
                     E += ebscale * cos(phase) * tmpE;
                     B -= ebscale * sin(phase) * tmpB;
-                  
+
 		    // Some phase output -DW
-		    
-		    if (tet >= 90.0 && waiting_for_gap == 1) { 
+
+		    if (tet >= 90.0 && waiting_for_gap == 1) {
 
                         double phase_print = 180.0 * phase / pi;
 			phase_print = fmod(phase_print, 360) - 360.0;
-			  
+
 			*gmsg << endl << "Gap 1 phase = " << phase_print << " Deg" << endl;
 			*gmsg << "Gap 1 E-Field = (" << E[0] << "/" << E[1] << "/" << E[2] << ")" << endl;
 			*gmsg << "Gap 1 B-Field = (" << B[0] << "/" << B[1] << "/" << B[2] << ")" << endl;
 			*gmsg << "RF Frequency = " << frequency << " MHz" << endl;
-			  
+
 			waiting_for_gap = 2;
-		    } 
-		    else if (tet >= 270.0 && waiting_for_gap == 2) { 
+		    }
+		    else if (tet >= 270.0 && waiting_for_gap == 2) {
 
 		        double phase_print = 180.0 * phase / pi;
 			phase_print = fmod(phase_print, 360) - 360.0;
-			  
+
 			*gmsg << endl << "Gap 2 phase = " << phase_print << " Deg" << endl;
 			*gmsg << "Gap 2 E-Field = (" << E[0] << "/" << E[1] << "/" << E[2] << ")" << endl;
 			*gmsg << "Gap 2 B-Field = (" << B[0] << "/" << B[1] << "/" << B[2] << ")" << endl;
@@ -909,7 +894,7 @@ void Cyclotron::getdiffs() {
         Bfield.g3[iend]     = Bfield.g3[istart];
 
     }
-    
+
     /* debug
 
     for(int i = 0; i< Bfield.nrad; i++){
@@ -1049,7 +1034,7 @@ void Cyclotron::initR(double rmin, double dr, int nrad) {
     BP.delr = dr;
 }
 
-void Cyclotron::initialise(PartBunch *bunch, double &startField, double &endField, const double &scaleFactor) {
+void Cyclotron::initialise(PartBunch *bunch, double &startField, double &endField) {
     RefPartBunch_m = bunch;
     online_m = true;
 }
@@ -1352,7 +1337,7 @@ void Cyclotron::getFieldFromFile_Carbon(const double &scaleFactor) {
 
     //Bfield.ntot = idx(Bfield.nrad - 1, Bfield.ntet) + 1;
     Bfield.ntot = Bfield.nrad * Bfield.ntetS;
-    
+
     *gmsg << "* Adding a guard cell along azimuth" << endl;
     *gmsg << "* Total stored grid point number ((ntet+1) * nrad) : " << Bfield.ntot << endl;
     Bfield.bfld.resize(Bfield.ntot);
@@ -1519,7 +1504,7 @@ void Cyclotron::getFieldFromFile_Synchrocyclotron(const double &scaleFactor) {
     int fcount = 0;
     FILE *rffcf = NULL;
     FILE *rfvcf = NULL;
-    
+
     *gmsg << endl;
     *gmsg << "* ------------------------------------------------------------" << endl;
     *gmsg << "*      READ IN 3D RF Fields and Frequency Coefficients        " << endl;
@@ -1534,7 +1519,7 @@ void Cyclotron::getFieldFromFile_Synchrocyclotron(const double &scaleFactor) {
         f->readMap();
 	// if (IPPL::Comm->getOutputLevel() != 0) f->getInfo(gmsg);
         RFfields_m.push_back(f);
-	
+
         // Read RF Frequency Coefficients from file
 	*gmsg << "RF Frequency Coefficient Filename: " << (*rffcfni) << endl;
 
@@ -1592,4 +1577,4 @@ void Cyclotron::getFieldFromFile_Synchrocyclotron(const double &scaleFactor) {
 void Cyclotron::getDimensions(double &zBegin, double &zEnd) const
 { }
 
-#undef CHECK_CYC_FSCANF_EOF
+#undef CHECK_CYC_FSCANF_EOF
\ No newline at end of file
diff --git a/src/Classic/AbsBeamline/Cyclotron.h b/src/Classic/AbsBeamline/Cyclotron.h
index d67b369f988444631d3929a48bb98ceafc9a2438..2c29099f524de5661108bc9e50f6b2a49b603488 100644
--- a/src/Classic/AbsBeamline/Cyclotron.h
+++ b/src/Classic/AbsBeamline/Cyclotron.h
@@ -213,13 +213,11 @@ public:
     void setSpiralFlag(bool spiral_flag);
     virtual bool getSpiralFlag() const;
 
-    virtual bool apply(const size_t &id, const double &t, double E[], double B[]);
-
     virtual bool apply(const size_t &id, const double &t, Vector_t &E, Vector_t &B);
 
-    virtual bool apply(const Vector_t &R, const Vector_t &centroid, const double &t, Vector_t &E, Vector_t &B);
+    virtual bool apply(const Vector_t &R, const Vector_t &P, const double &t, Vector_t &E, Vector_t &B);
 
-    virtual void initialise(PartBunch *bunch, double &startField, double &endField, const double &scaleFactor);
+    virtual void initialise(PartBunch *bunch, double &startField, double &endField);
 
     virtual void initialise(PartBunch *bunch, const int &fieldflag, const double &scaleFactor);
 
@@ -230,7 +228,7 @@ public:
     virtual double getRmax() const;
 
     virtual double getRmin() const;
-    
+
 protected:
     void   getdiffs();
 
@@ -247,7 +245,7 @@ protected:
     void   getFieldFromFile_Synchrocyclotron(const double &scaleFactor);
 
     inline int idx(int irad, int ktet) {return (ktet + Bfield.ntetS * irad);}
-    
+
 private:
 
     std::string fmapfn_m; /* stores the filename of the fieldmap */
@@ -305,13 +303,13 @@ private:
     std::vector<std::string> RFfilename_m;
     std::vector<std::string> RFFCoeff_fn_m;
     std::vector<std::string> RFVCoeff_fn_m;
-    
+
     // handling for store the particle out of region
     std::unique_ptr<LossDataSink> lossDs_m;
 
     // Necessary for quick and dirty phase output -DW
     int waiting_for_gap = 1;
-    
+
 protected:
     // object of Matrics including magnetic field map and its derivates
     BfieldData Bfield;
@@ -320,4 +318,4 @@ protected:
     BPositions BP;
 };
 
-#endif // CLASSIC_Cyclotron_HH
+#endif // CLASSIC_Cyclotron_HH
\ No newline at end of file
diff --git a/src/Classic/AbsBeamline/CyclotronValley.cpp b/src/Classic/AbsBeamline/CyclotronValley.cpp
index e622b37247b9b51c4c42e6a02574c349d4e0d90f..35c4837eba9ffcc809a3a535ac8fd0aa48dfa4fd 100644
--- a/src/Classic/AbsBeamline/CyclotronValley.cpp
+++ b/src/Classic/AbsBeamline/CyclotronValley.cpp
@@ -102,52 +102,29 @@ bool CyclotronValley::getFast() const {
     return fast_m;
 }
 
-bool CyclotronValley::apply(const size_t &i, const double &t, double E[], double B[]) {
-    Vector_t Ev(0, 0, 0), Bv(0, 0, 0);
-    Vector_t Rt(RefPartBunch_m->getX(i), RefPartBunch_m->getY(i), RefPartBunch_m->getZ(i));
-    if(apply(Rt, Vector_t(0.0), t, Ev, Bv)) return true;
-
-    E[0] = Ev(0);
-    E[1] = Ev(1);
-    E[2] = Ev(2);
-    B[0] = Bv(0);
-    B[1] = Bv(1);
-    B[2] = Bv(2);
-
-    return false;
-}
-
 bool CyclotronValley::apply(const size_t &i, const double &t, Vector_t &E, Vector_t &B) {
 
-
-    const Vector_t tmpR(RefPartBunch_m->getX(i) - dx_m, RefPartBunch_m->getY(i) - dy_m , RefPartBunch_m->getZ(i) - startField_m - ds_m);
-    Vector_t tmpE(0.0, 0.0, 0.0), tmpB(0.0, 0.0, 0.0);
-    if(!fieldmap_m->getFieldstrength(tmpR, tmpE, tmpB)) {
-        // E += scale_m * cos(phase) * tmpE;
-        //B -= scale_m * sin(phase) * tmpB;
-	B +=scale_m * tmpB;
-        return false;
-    }
-
-    return true;
+    const Vector_t tmpR = RefPartBunch_m->R[i];
+    return applyToReferenceParticle(tmpR, RefPartBunch_m->P[i], t, E, B);
 }
 
-bool CyclotronValley::apply(const Vector_t &R, const Vector_t &centroid, const double &t, Vector_t &E, Vector_t &B) {
+bool CyclotronValley::apply(const Vector_t &R, const Vector_t &P, const double &t, Vector_t &E, Vector_t &B) {
 
+    const Vector_t tmpR = R;
+    return applyToReferenceParticle(tmpR, P, t, E, B);
+}
 
-    const Vector_t tmpR(R(0) - dx_m, R(1) - dy_m, R(2) - startField_m - ds_m);
+bool CyclotronValley::applyToReferenceParticle(const Vector_t &tmpR, const Vector_t &P, const double &t, Vector_t &E, Vector_t &B) {
     Vector_t  tmpE(0.0, 0.0, 0.0), tmpB(0.0, 0.0, 0.0);
 
     if(!fieldmap_m->getFieldstrength(tmpR, tmpE, tmpB)) {
-        // E += scale_m * cos(phase) * tmpE;
-        //B -= scale_m * sin(phase) * tmpB;
 	B +=scale_m * tmpB;
         return false;
     }
     return true;
 }
 
-void CyclotronValley::initialise(PartBunch *bunch, double &startField, double &endField, const double &scaleFactor) {// called by ParallelTTracker::visitCyclotronValley --> OpalBeamline::visit
+void CyclotronValley::initialise(PartBunch *bunch, double &startField, double &endField) {// called by ParallelTTracker::visitCyclotronValley --> OpalBeamline::visit
     using Physics::two_pi;
     double zBegin = 0.0, zEnd = 0.0, rBegin = 0.0, rEnd = 0.0;
     Inform msg("CyclotronValley ");
diff --git a/src/Classic/AbsBeamline/CyclotronValley.h b/src/Classic/AbsBeamline/CyclotronValley.h
index 6c2eeaec07cea9762ffdeaec2a12e0636e00c514..a148e91ab55ed25e7749daa66c36fc78d34395e3 100644
--- a/src/Classic/AbsBeamline/CyclotronValley.h
+++ b/src/Classic/AbsBeamline/CyclotronValley.h
@@ -10,7 +10,7 @@
 // ------------------------------------------------------------------------
 //
 // Class: CyclotronValley
-//   Defines the abstract interface for an element modeling the valley of 
+//   Defines the abstract interface for an element modeling the valley of
 //   a cyclotron.
 //
 // ------------------------------------------------------------------------
@@ -37,7 +37,7 @@ class CyclotronValley: public Component {
 
 public:
 
-   
+
     /// Constructor with given name.
     explicit CyclotronValley(const std::string &name);
 
@@ -48,7 +48,7 @@ public:
     /// Apply visitor to CyclotronValley.
     virtual void accept(BeamlineVisitor &) const;
 
-   
+
     /// Set the name of the field map
     void setFieldMapFN(std::string fmapfn);
 
@@ -58,15 +58,16 @@ public:
 
     bool getFast() const;
     ElementBase::ElementType getType() const;
-    virtual bool apply(const size_t &i, const double &t, double E[], double B[]);
-   
+
     virtual bool apply(const size_t &i, const double &t, Vector_t &E, Vector_t &B);
 
-    virtual bool apply(const Vector_t &R, const Vector_t &centroid, const double &t, Vector_t &E, Vector_t &B);
+    virtual bool apply(const Vector_t &R, const Vector_t &P, const double &t, Vector_t &E, Vector_t &B);
 
-    virtual void initialise(PartBunch *bunch, double &startField, double &endField, const double &scaleFactor);
+    virtual bool applyToReferenceParticle(const Vector_t &R, const Vector_t &P, const double &t, Vector_t &E, Vector_t &B);
 
-    //virtual void initialise(PartBunch *bunch, const double &scaleFactor);
+    virtual void initialise(PartBunch *bunch, double &startField, double &endField);
+
+    //virtual void initialise(PartBunch *bunch);
 
     virtual void finalise();
 
@@ -82,15 +83,15 @@ private:
     std::string filename_m;             /**< The name of the inputfile*/
     Fieldmap *fieldmap_m;
     double scale_m;              /**< scale multiplier*/
-   
+
     double ElementEdge_m;
     double startField_m;         /**< starting point of field(m)*/
     double endField_m;
     bool fast_m;
-   
+
 
     // Not implemented.
     void operator=(const CyclotronValley &);
 };
 
-#endif // CLASSIC_CyclotronValley_HH
+#endif // CLASSIC_CyclotronValley_HH
\ No newline at end of file
diff --git a/src/Classic/AbsBeamline/Degrader.cpp b/src/Classic/AbsBeamline/Degrader.cpp
index 70c98d9927f5f386bad9ec0a703ed5aeb8da6f93..b3fb829089923d1d90675c4997b6b1065041ab98 100644
--- a/src/Classic/AbsBeamline/Degrader.cpp
+++ b/src/Classic/AbsBeamline/Degrader.cpp
@@ -37,8 +37,6 @@ using namespace std;
 Degrader::Degrader():
     Component(),
     filename_m(""),
-    position_m(0.0),
-    deg_width_m(0.0),
     PosX_m(0),
     PosY_m(0),
     PosZ_m(0),
@@ -46,15 +44,12 @@ Degrader::Degrader():
     MomentumY_m(0),
     MomentumZ_m(0),
     time_m(0),
-    id_m(0),
-    informed_m(false)
+    id_m(0)
 {}
 
 Degrader::Degrader(const Degrader &right):
     Component(right),
     filename_m(right.filename_m),
-    position_m(right.position_m),
-    deg_width_m(right.deg_width_m),
     PosX_m(right.PosX_m),
     PosY_m(right.PosY_m),
     PosZ_m(right.PosZ_m),
@@ -62,17 +57,12 @@ Degrader::Degrader(const Degrader &right):
     MomentumY_m(right.MomentumY_m),
     MomentumZ_m(right.MomentumZ_m),
     time_m(right.time_m),
-    id_m(right.id_m),
-    informed_m(right.informed_m),
-    zstart_m(right.zstart_m),
-    zend_m(right.zend_m)
+    id_m(right.id_m)
 {}
 
 Degrader::Degrader(const std::string &name):
     Component(name),
     filename_m(""),
-    position_m(0.0),
-    deg_width_m(0.0),
     PosX_m(0),
     PosY_m(0),
     PosZ_m(0),
@@ -80,10 +70,7 @@ Degrader::Degrader(const std::string &name):
     MomentumY_m(0),
     MomentumZ_m(0),
     time_m(0),
-    id_m(0),
-    informed_m(false),
-    zstart_m(0.0),
-    zend_m(0.0)
+    id_m(0)
 {}
 
 
@@ -104,53 +91,40 @@ inline bool Degrader::isInMaterial(double z ) {
      check if the particle is in the degarder material
 
   */
-    return ((z > position_m) && (z <= position_m + getZSize())); //getElementLength()));
-}
-
-bool Degrader::apply(const size_t &i, const double &t, double E[], double B[]) {
-    Vector_t Ev(0, 0, 0), Bv(0, 0, 0);
-    return apply(i, t, Ev, Bv);
+    return ((z > 0.0) && (z <= getElementLength()));
 }
 
 bool Degrader::apply(const size_t &i, const double &t, Vector_t &E, Vector_t &B) {
 
-    const Vector_t &R = RefPartBunch_m->R[i] - Vector_t(dx_m, dy_m, ds_m); // including the missaligment
+    const Vector_t &R = RefPartBunch_m->R[i];
     const Vector_t &P = RefPartBunch_m->P[i];
-    const double recpgamma = Physics::c * RefPartBunch_m->getdT() / sqrt(1.0  + dot(P, P));
-
-    bool pdead = false;
-    pdead = isInMaterial(R(2));
-
-    if(pdead) {
-      //if particle was allready marked as -1 (it means it should have gone into degrader but didn't)
-      //set the label to -2 (will not go into degrader and will be deleted when particles per core > 2)
-      if (RefPartBunch_m->Bin[i] < 0)
-	RefPartBunch_m->Bin[i] = -2;
-      else
-	RefPartBunch_m->Bin[i] = -1;
-
-      double frac = (R(2) - position_m) / P(2) * recpgamma;
-      PosX_m.push_back(R(0));
-      PosY_m.push_back(R(1));
-      PosZ_m.push_back(R(2));
-      MomentumX_m.push_back(P(0));
-      MomentumY_m.push_back(P(1));
-      MomentumZ_m.push_back(P(2));
-      time_m.push_back(t + frac * RefPartBunch_m->getdT());
-      id_m.push_back(i);
+    const double recpgamma = Physics::c * RefPartBunch_m->dt[i] / sqrt(1.0  + dot(P, P));
+
+    if(isInMaterial(R(2))) {
+        //if particle was allready marked as -1 (it means it should have gone into degrader but didn't)
+        //set the label to -2 (will not go into degrader and will be deleted when particles per core > 2)
+        if (RefPartBunch_m->Bin[i] < 0)
+            RefPartBunch_m->Bin[i] = -2;
+        else
+            RefPartBunch_m->Bin[i] = -1;
+
+        double frac = -R(2) / P(2) * recpgamma;
+        PosX_m.push_back(R(0));
+        PosY_m.push_back(R(1));
+        PosZ_m.push_back(R(2));
+        MomentumX_m.push_back(P(0));
+        MomentumY_m.push_back(P(1));
+        MomentumZ_m.push_back(P(2));
+        time_m.push_back(t + frac * RefPartBunch_m->dt[i]);
+        id_m.push_back(RefPartBunch_m->ID[i]);
     }
-    return false;
-}
 
-bool Degrader::apply(const Vector_t &R, const Vector_t &centroid, const double &t, Vector_t &E, Vector_t &B) {
     return false;
 }
 
-
-void Degrader::initialise(PartBunch *bunch, double &startField, double &endField, const double &scaleFactor) {
+void Degrader::initialise(PartBunch *bunch, double &startField, double &endField) {
     RefPartBunch_m = bunch;
-    position_m = startField;
-    endField = position_m + getElementLength();
+    endField = startField + getElementLength();
 
     if (filename_m == std::string(""))
         lossDs_m = std::unique_ptr<LossDataSink>(new LossDataSink(getName(), !Options::asciidump));
@@ -158,7 +132,7 @@ void Degrader::initialise(PartBunch *bunch, double &startField, double &endField
         lossDs_m = std::unique_ptr<LossDataSink>(new LossDataSink(filename_m.substr(0, filename_m.rfind(".")), !Options::asciidump));
 }
 
-void Degrader::initialise(PartBunch *bunch, const double &scaleFactor) {
+void Degrader::initialise(PartBunch *bunch) {
     RefPartBunch_m = bunch;
     if (filename_m == std::string(""))
         lossDs_m = std::unique_ptr<LossDataSink>(new LossDataSink(getName(), !Options::asciidump));
@@ -173,21 +147,8 @@ void Degrader::finalise()
 }
 
 void Degrader::goOnline(const double &) {
- Inform msg("Degrader::goOnline ");
-   if(RefPartBunch_m == NULL) {
-        if(!informed_m) {
-            std::string errormsg = Fieldmap::typeset_msg("BUNCH SIZE NOT SET", "warning");
-            msg << errormsg << "\n"
-                << endl;
-            if(Ippl::myNode() == 0) {
-                ofstream omsg("errormsg.txt", ios_base::app);
-                omsg << errormsg << endl;
-                omsg.close();
-            }
-            informed_m = true;
-        }
-        return;
-    }
+    Inform msg("Degrader::goOnline ");
+
     PosX_m.reserve((int)(1.1 * RefPartBunch_m->getLocalNum()));
     PosY_m.reserve((int)(1.1 * RefPartBunch_m->getLocalNum()));
     PosZ_m.reserve((int)(1.1 * RefPartBunch_m->getLocalNum()));
@@ -221,17 +182,9 @@ string Degrader::getOutputFN() {
         return filename_m.substr(0, filename_m.rfind("."));
 }
 
-double Degrader::getZStart() {
-    return zstart_m;
-}
-
-double Degrader::getZEnd() {
-    return zend_m;
-}
-
 void Degrader::getDimensions(double &zBegin, double &zEnd) const {
-    zBegin = position_m;
-    zEnd = position_m + getElementLength();
+    zBegin = 0.0;
+    zEnd = getElementLength();
 
 }
 
@@ -243,11 +196,3 @@ string Degrader::getDegraderShape() {
     return "DEGRADER";
 
 }
-
-void Degrader::setZSize(double z) {
-    deg_width_m = z;
-}
-
-double Degrader::getZSize() {
-    return deg_width_m;
-}
diff --git a/src/Classic/AbsBeamline/Degrader.h b/src/Classic/AbsBeamline/Degrader.h
index e0a2f7e354d09565ffa954bc8b5a87e3d2618499..7d77efb2de08179d347bb6a662c419fdefcc4282 100644
--- a/src/Classic/AbsBeamline/Degrader.h
+++ b/src/Classic/AbsBeamline/Degrader.h
@@ -60,15 +60,11 @@ public:
     /// Apply visitor to Degrader.
     virtual void accept(BeamlineVisitor &) const;
 
-    virtual bool apply(const size_t &i, const double &t, double E[], double B[]);
-
     virtual bool apply(const size_t &i, const double &t, Vector_t &E, Vector_t &B);
 
-    virtual bool apply(const Vector_t &R, const Vector_t &centroid, const double &t, Vector_t &E, Vector_t &B);
-
-    virtual void initialise(PartBunch *bunch, double &startField, double &endField, const double &scaleFactor);
+    virtual void initialise(PartBunch *bunch, double &startField, double &endField);
 
-    virtual void initialise(PartBunch *bunch, const double &scaleFactor);
+    virtual void initialise(PartBunch *bunch);
 
     virtual void finalise();
 
@@ -87,15 +83,6 @@ public:
     void setOutputFN(std::string fn);
     std::string getOutputFN();
 
-    void setZSize( double z) ;
-
-    void setZStart(double zstart) ;
-    void setZEnd(double zend) ;
-
-    double getZStart() ;
-    double getZEnd() ;
-    double getZSize();
-
     virtual bool isInMaterial(double z);
 
 private:
@@ -105,9 +92,6 @@ private:
 
     std::string filename_m;               /**< The name of the outputfile*/
 
-    double position_m;
-    double deg_width_m;
-
     std::vector<double> PosX_m;
     std::vector<double> PosY_m;
     std::vector<double> PosZ_m;
@@ -116,12 +100,8 @@ private:
     std::vector<double> MomentumZ_m;
     std::vector<double> time_m;
     std::vector<int> id_m;
-    bool informed_m;
-
-    double zstart_m;
-    double zend_m;
 
     std::unique_ptr<LossDataSink> lossDs_m;
 };
 
-#endif // CLASSIC_Degrader_HH
+#endif // CLASSIC_Degrader_HH
\ No newline at end of file
diff --git a/src/Classic/AbsBeamline/Diagnostic.cpp b/src/Classic/AbsBeamline/Diagnostic.cpp
index 625299cb39e00a51dee82798bbd38bea89116e9b..13bde0533ea2f1d8deed901a6acaa9b2944ed249 100644
--- a/src/Classic/AbsBeamline/Diagnostic.cpp
+++ b/src/Classic/AbsBeamline/Diagnostic.cpp
@@ -48,19 +48,7 @@ void Diagnostic::accept(BeamlineVisitor &visitor) const {
     visitor.visitDiagnostic(*this);
 }
 
-bool Diagnostic::apply(const size_t &i, const double &t, double E[], double B[]) {
-    return false;
-}
-
-bool Diagnostic::apply(const size_t &i, const double &t, Vector_t &E, Vector_t &B) {
-    return false;
-}
-
-bool Diagnostic::apply(const Vector_t &R, const Vector_t &centroid, const double &t, Vector_t &E, Vector_t &B) {
-    return false;
-}
-
-void Diagnostic::initialise(PartBunch *bunch, double &startField, double &endField, const double &scaleFactor) {
+void Diagnostic::initialise(PartBunch *bunch, double &startField, double &endField) {
     RefPartBunch_m = bunch;
 }
 
@@ -76,4 +64,4 @@ ElementBase::ElementType Diagnostic::getType() const {
 }
 
 void Diagnostic::getDimensions(double &zBegin, double &zEnd) const
-{ }
+{ }
\ No newline at end of file
diff --git a/src/Classic/AbsBeamline/Diagnostic.h b/src/Classic/AbsBeamline/Diagnostic.h
index 7d4a55197864e206a7035bb9161d4e7026bc4837..0c23c1f35db2a4111e6050df1ef393427fbf7072 100644
--- a/src/Classic/AbsBeamline/Diagnostic.h
+++ b/src/Classic/AbsBeamline/Diagnostic.h
@@ -43,13 +43,7 @@ public:
     /// Apply visitor to Diagnostic.
     virtual void accept(BeamlineVisitor &) const;
 
-    virtual bool apply(const size_t &i, const double &t, double E[], double B[]);
-
-    virtual bool apply(const size_t &i, const double &t, Vector_t &E, Vector_t &B);
-
-    virtual bool apply(const Vector_t &R, const Vector_t &centroid, const double &t, Vector_t &E, Vector_t &B);
-
-    virtual void initialise(PartBunch *bunch, double &startField, double &endField, const double &scaleFactor);
+    virtual void initialise(PartBunch *bunch, double &startField, double &endField);
 
     virtual void finalise();
 
@@ -65,4 +59,4 @@ private:
     void operator=(const Diagnostic &);
 };
 
-#endif // CLASSIC_Diagnostic_HH
+#endif // CLASSIC_Diagnostic_HH
\ No newline at end of file
diff --git a/src/Classic/AbsBeamline/Drift.cpp b/src/Classic/AbsBeamline/Drift.cpp
index 907e0ab88b1a63eb3bfd65f1d0b34a7087939d4a..34fd83fb1d6f2e536a8c0e1cfb50c71ed67ebc88 100644
--- a/src/Classic/AbsBeamline/Drift.cpp
+++ b/src/Classic/AbsBeamline/Drift.cpp
@@ -20,6 +20,7 @@
 
 #include "AbsBeamline/Drift.h"
 #include "AbsBeamline/BeamlineVisitor.h"
+#include "Algorithms/PartBunch.h"
 
 extern Inform *gmsg;
 
@@ -49,19 +50,7 @@ void Drift::accept(BeamlineVisitor &visitor) const {
     visitor.visitDrift(*this);
 }
 
-bool Drift::apply(const size_t &i, const double &t, double E[], double B[]) {
-    return false;
-}
-
-bool Drift::apply(const size_t &i, const double &t, Vector_t &E, Vector_t &B) {
-    return false;
-}
-
-bool Drift::apply(const Vector_t &R, const Vector_t &centroid, const double &t, Vector_t &E, Vector_t &B) {
-    return false;
-}
-
-void Drift::initialise(PartBunch *bunch, double &startField, double &endField, const double &scaleFactor) {
+void Drift::initialise(PartBunch *bunch, double &startField, double &endField) {
     endField = startField + getElementLength();
     RefPartBunch_m = bunch;
     startField_m = startField;
@@ -81,4 +70,4 @@ void Drift::getDimensions(double &zBegin, double &zEnd) const {
 
 ElementBase::ElementType Drift::getType() const {
     return DRIFT;
-}
+}
\ No newline at end of file
diff --git a/src/Classic/AbsBeamline/Drift.h b/src/Classic/AbsBeamline/Drift.h
index 625aabf007b102823df7008db36953e3b798fdcb..13de997c189b1eeb34f738ee9dc9d400fdcf6337 100644
--- a/src/Classic/AbsBeamline/Drift.h
+++ b/src/Classic/AbsBeamline/Drift.h
@@ -44,13 +44,7 @@ public:
     /// Apply visitor to Drift.
     virtual void accept(BeamlineVisitor &) const;
 
-    virtual bool apply(const size_t &i, const double &t, double E[], double B[]);
-
-    virtual bool apply(const size_t &i, const double &t, Vector_t &E, Vector_t &B);
-
-    virtual bool apply(const Vector_t &R, const Vector_t &centroid, const double &t, Vector_t &E, Vector_t &B);
-
-    virtual void initialise(PartBunch *bunch, double &startField, double &endField, const double &scaleFactor);
+    virtual void initialise(PartBunch *bunch, double &startField, double &endField);
 
     virtual void finalise();
 
@@ -68,4 +62,4 @@ private:
     void operator=(const Drift &);
 };
 
-#endif // CLASSIC_Drift_HH
+#endif // CLASSIC_Drift_HH
\ No newline at end of file
diff --git a/src/Classic/AbsBeamline/ElementBase.cpp b/src/Classic/AbsBeamline/ElementBase.cpp
index 53391adf75ff8aba7b676882ef3b0a22f7d6aaf0..0cb008def5948d92472c750ba442fe5c31d90e25 100644
--- a/src/Classic/AbsBeamline/ElementBase.cpp
+++ b/src/Classic/AbsBeamline/ElementBase.cpp
@@ -39,24 +39,35 @@ using namespace std;
 ElementBase::ElementBase():
     RCObject(),
     shareFlag(true),
+    csTrafoGlobal2Local_m(),
+    misalignment_m(),
+    elementEdge_m(0),
+    rotationZAxis_m(0.0),
     elementID(""),
     userAttribs(),
     wake_m(NULL),
     bgeometry_m(NULL),
     sphys_m(NULL),
-    elType_m(isOther)
+    elType_m(isOther),
+    positionIsFixed(false)
 {}
 
 
 ElementBase::ElementBase(const ElementBase &right):
     RCObject(),
     shareFlag(true),
+    csTrafoGlobal2Local_m(right.csTrafoGlobal2Local_m),
+    misalignment_m(right.misalignment_m),
+    aperture_m(right.aperture_m),
+    elementEdge_m(right.elementEdge_m),
+    rotationZAxis_m(right.rotationZAxis_m),
     elementID(right.elementID),
     userAttribs(right.userAttribs),
     wake_m(right.wake_m),
     bgeometry_m(right.bgeometry_m),
     sphys_m(right.sphys_m),
-    elType_m(right.elType_m)
+    elType_m(right.elType_m),
+    positionIsFixed(right.positionIsFixed)
 {
 
     if(sphys_m) {
@@ -70,12 +81,17 @@ ElementBase::ElementBase(const ElementBase &right):
 ElementBase::ElementBase(const std::string &name):
     RCObject(),
     shareFlag(true),
+    csTrafoGlobal2Local_m(),
+    misalignment_m(),
+    elementEdge_m(0),
+    rotationZAxis_m(0.0),
     elementID(name),
     userAttribs(),
     wake_m(NULL),
     bgeometry_m(NULL),
     sphys_m(NULL),
-    elType_m(isOther)
+    elType_m(isOther),
+    positionIsFixed(false)
 {}
 
 
@@ -161,8 +177,12 @@ std::string ElementBase::getTypeString(ElementBase::ElementType type) {
         return "Collimator";
     case CORRECTOR:
         return "Corrector";
+    case CORRECTORWRAPPER:
+        return "Correctorwrapper";
     case CYCLOTRON:
         return "Cyclotron";
+    case CYCLOTRONWRAPPER:
+        return "Cyclotronwrapper";
     case CYCLOTRONVALLEY:
         return "CyclotronValley";
     case DEGRADER:
@@ -181,6 +201,8 @@ std::string ElementBase::getTypeString(ElementBase::ElementType type) {
         return "Monitor";
     case MULTIPOLE:
         return "Multipole";
+    case MULTIPOLEWRAPPER:
+        return "Multipolewrapper";
     case OFFSET:
         return "Offset";
     case PARALLELPLATE:
@@ -191,6 +213,8 @@ std::string ElementBase::getTypeString(ElementBase::ElementType type) {
         return "Probe";
     case RBEND:
         return "RBend";
+    case RBENDWRAPPER:
+        return "RBendwrapper";
     case RFCAVITY:
         return "RFCavity";
     case RFQUADRUPOLE:
@@ -201,6 +225,8 @@ std::string ElementBase::getTypeString(ElementBase::ElementType type) {
         return "SBend3D";
     case SBEND:
         return "SBend";
+    case SBENDWRAPPER:
+        return "SBendwrapper";
     case SEPARATOR:
         return "Separator";
     case SEPTUM:
@@ -215,7 +241,7 @@ std::string ElementBase::getTypeString(ElementBase::ElementType type) {
         return "VariableRFCavity";
     case ANY:
     default:
-        return "";
+        return "'unknown' type";
     }
 }
 
@@ -304,4 +330,13 @@ void ElementBase::setBoundaryGeometry(BoundaryGeometry *geo) {
 
 void ElementBase::setSurfacePhysics(SurfacePhysicsHandler *sphys) {
     sphys_m = sphys;
+}
+
+void ElementBase::setCurrentSCoordinate(double s) {
+    if (actionRange_m.size() > 0 && actionRange_m.front().second < s) {
+        actionRange_m.pop();
+        if (actionRange_m.size() > 0) {
+            elementEdge_m = actionRange_m.front().first;
+        }
+    }
 }
\ No newline at end of file
diff --git a/src/Classic/AbsBeamline/ElementBase.h b/src/Classic/AbsBeamline/ElementBase.h
index d6ba4186f84d0cd3347c613d3a927e13e6d2ed12..640b20b9dc43aa49b7cf8ea17552390671090365 100644
--- a/src/Classic/AbsBeamline/ElementBase.h
+++ b/src/Classic/AbsBeamline/ElementBase.h
@@ -27,7 +27,12 @@
 #include "AbsBeamline/AttributeSet.h"
 #include "BeamlineGeometry/Geometry.h"
 #include "MemoryManagement/RCObject.h"
+#include "Algorithms/Vektor.h"
+#include "Algorithms/Quaternion.h"
+#include "Algorithms/CoordinateSystemTrafo.h"
+
 #include <string>
+#include <queue>
 
 class Beamline;
 class BeamlineVisitor;
@@ -38,6 +43,7 @@ class ElementImage;
 enum ElemType {
     isDrift,
     isSolenoid,
+    isSource,
     isRF,
     isDipole,
     isMultipole,
@@ -136,6 +142,11 @@ public:
     /// Set element name.
     virtual void setName(const std::string &name);
 
+    enum ApertureType {RECTANGULAR
+                     , ELLIPTICAL
+                     , CONIC_RECTANGULAR
+                     , CONIC_ELLIPTICAL
+    };
 
     enum ElementType {ALIGNWRAPPER
                     , BEAMBEAM
@@ -162,6 +173,7 @@ public:
                     , PATCH
                     , PROBE
                     , RBEND
+                    , RBEND3D
                     , RBENDWRAPPER
                     , RFCAVITY
                     , RFQUADRUPOLE
@@ -172,6 +184,7 @@ public:
                     , SEPARATOR
                     , SEPTUM
                     , SOLENOID
+                    , SOURCE
                     , STRIPPER
                     , TRAVELINGWAVE
                     , VARIABLERFCAVITY
@@ -403,12 +416,47 @@ public:
     /// set the element type as enumeration needed in the envelope tracker
     void setElType(ElemType elt);
 
+    void setCSTrafoGlobal2Local(const CoordinateSystemTrafo &ori);
+    CoordinateSystemTrafo getCSTrafoGlobal2Local() const;
+    void fixPosition();
+    bool isPositioned();
+
+    virtual CoordinateSystemTrafo getBeginToEnd() const;
+
+    void setAperture(const ApertureType& type, const std::vector<double> &args);
+    std::pair<ElementBase::ApertureType, std::vector<double> > getAperture() const;
+
+    virtual bool isInside(const Vector_t &r) const;
+
+    void setMisalignment(double x, double y, double s);
+    void setMisalignment(const CoordinateSystemTrafo &cst);
+
+    void getMisalignment(double &x, double &y, double &s) const;
+    CoordinateSystemTrafo getMisalignment() const;
+
+    void setActionRange(const std::queue<std::pair<double, double> > &range);
+    void setCurrentSCoordinate(double s);
+
+    /// Set rotation about z axis in bend frame.
+    void setRotationAboutZ(double rotation);
+    double getRotationAboutZ() const;
+
 protected:
+    bool isInsideTransverse(const Vector_t &r, double f = 1) const;
 
     // Sharable flag.
     // If this flag is true, the element is always shared.
     mutable bool shareFlag;
 
+    CoordinateSystemTrafo csTrafoGlobal2Local_m;
+    CoordinateSystemTrafo misalignment_m;
+
+    std::pair<ApertureType, std::vector<double> > aperture_m;
+
+    double elementEdge_m;
+
+    double rotationZAxis_m;
+
 private:
 
     // Not implemented.
@@ -427,79 +475,202 @@ private:
     SurfacePhysicsHandler *sphys_m;
 
     ElemType elType_m;
+
+    bool positionIsFixed;
+
+    std::queue<std::pair<double, double> > actionRange_m;
 };
 
 
 // Inline functions.
 // ------------------------------------------------------------------------
 
-inline double ElementBase::getArcLength() const
+inline
+double ElementBase::getArcLength() const
 { return getGeometry().getArcLength(); }
 
-inline double ElementBase::getElementLength() const
+inline
+double ElementBase::getElementLength() const
 { return getGeometry().getElementLength(); }
 
-inline void ElementBase::setElementLength(double length)
+inline
+void ElementBase::setElementLength(double length)
 { getGeometry().setElementLength(length); }
 
-inline double ElementBase::getOrigin() const
+inline
+double ElementBase::getOrigin() const
 { return getGeometry().getOrigin(); }
 
-inline double ElementBase::getEntrance() const
+inline
+double ElementBase::getEntrance() const
 { return getGeometry().getEntrance(); }
 
-inline double ElementBase::getExit() const
+inline
+double ElementBase::getExit() const
 { return getGeometry().getExit(); }
 
-inline Euclid3D ElementBase::getTransform(double fromS, double toS) const
+inline
+Euclid3D ElementBase::getTransform(double fromS, double toS) const
 { return getGeometry().getTransform(fromS, toS); }
 
-inline Euclid3D ElementBase::getTotalTransform() const
+inline
+Euclid3D ElementBase::getTotalTransform() const
 { return getGeometry().getTotalTransform(); }
 
-inline Euclid3D ElementBase::getTransform(double s) const
+inline
+Euclid3D ElementBase::getTransform(double s) const
 { return getGeometry().getTransform(s); }
 
-inline Euclid3D ElementBase::getEntranceFrame() const
+inline
+Euclid3D ElementBase::getEntranceFrame() const
 { return getGeometry().getEntranceFrame(); }
 
-inline Euclid3D ElementBase::getExitFrame() const
+inline
+Euclid3D ElementBase::getExitFrame() const
 { return getGeometry().getExitFrame(); }
 
-inline Euclid3D ElementBase::getEntrancePatch() const
+inline
+Euclid3D ElementBase::getEntrancePatch() const
 { return getGeometry().getEntrancePatch(); }
 
-inline Euclid3D ElementBase::getExitPatch() const
+inline
+Euclid3D ElementBase::getExitPatch() const
 { return getGeometry().getExitPatch(); }
 
-inline bool ElementBase::isSharable() const
+inline
+bool ElementBase::isSharable() const
 { return shareFlag; }
 
-inline WakeFunction *ElementBase::getWake() const
+inline
+WakeFunction *ElementBase::getWake() const
 { return wake_m; }
 
-inline bool ElementBase::hasWake() const
+inline
+bool ElementBase::hasWake() const
 { return wake_m != NULL; }
 
-inline BoundaryGeometry *ElementBase::getBoundaryGeometry() const
+inline
+BoundaryGeometry *ElementBase::getBoundaryGeometry() const
 { return bgeometry_m; }
 
-inline bool ElementBase::hasBoundaryGeometry() const
+inline
+bool ElementBase::hasBoundaryGeometry() const
 { return bgeometry_m != NULL; }
 
-inline SurfacePhysicsHandler *ElementBase::getSurfacePhysics() const
+inline
+SurfacePhysicsHandler *ElementBase::getSurfacePhysics() const
 { return sphys_m; }
 
-inline bool ElementBase::hasSurfacePhysics() const
+inline
+bool ElementBase::hasSurfacePhysics() const
 { return sphys_m != NULL; }
 
-inline ElemType ElementBase::getElType() const
+inline
+ElemType ElementBase::getElType() const
 { return elType_m;}
 
-inline void ElementBase::setElType(ElemType elt)
+inline
+void ElementBase::setElType(ElemType elt)
 { elType_m = elt;}
 
-inline std::string ElementBase::getTypeString() const
+inline
+void ElementBase::setCSTrafoGlobal2Local(const CoordinateSystemTrafo &trafo)
+{
+    if (positionIsFixed) return;
+
+    csTrafoGlobal2Local_m = trafo;
+}
+
+inline
+CoordinateSystemTrafo ElementBase::getCSTrafoGlobal2Local() const
+{ return csTrafoGlobal2Local_m; }
+
+inline
+CoordinateSystemTrafo ElementBase::getBeginToEnd() const
+{
+    CoordinateSystemTrafo ret(Vector_t(0, 0, getElementLength()),
+                              Quaternion(1, 0, 0, 0));
+
+    return ret;
+}
+
+inline
+void ElementBase::setAperture(const ApertureType& type, const std::vector<double> &args)
+{
+    aperture_m.first = type;
+    aperture_m.second = args;
+}
+
+inline
+std::pair<ElementBase::ApertureType, std::vector<double> > ElementBase::getAperture() const
+{
+    return aperture_m;
+}
+
+inline
+bool ElementBase::isInside(const Vector_t &r) const
+{
+    const double length = getElementLength();
+    return isInsideTransverse(r, r(2) / length * aperture_m.second[2]) && r(2) >= 0.0 && r(2) < length;
+}
+
+inline
+bool ElementBase::isInsideTransverse(const Vector_t &r, double f) const
+{
+    switch(aperture_m.first) {
+    case RECTANGULAR:
+        return (std::abs(r[0]) < aperture_m.second[0] && std::abs(r[1]) < aperture_m.second[1]);
+    case ELLIPTICAL:
+        return (std::pow(r[0] / aperture_m.second[0], 2) + std::pow(r[1] / aperture_m.second[1], 2) < 1.0);
+    case CONIC_RECTANGULAR:
+        return (std::abs(r[0]) < (1.0 - f) * aperture_m.second[0] && std::abs(r[1]) < (1.0 - f) * aperture_m.second[1]);
+    case CONIC_ELLIPTICAL:
+        return (std::pow(r[0] / ((1.0 - f) * aperture_m.second[0]), 2) + std::pow(r[1] / ((1.0 - f) * aperture_m.second[1]), 2) < 1.0);
+    default:
+        return false;
+    }
+}
+
+inline
+void ElementBase::setMisalignment(const CoordinateSystemTrafo &cst) {
+    misalignment_m = cst;
+}
+
+inline
+CoordinateSystemTrafo ElementBase::getMisalignment() const {
+    return misalignment_m;
+}
+
+inline
+void ElementBase::fixPosition() {
+    positionIsFixed = true;
+}
+
+inline
+bool ElementBase::isPositioned() {
+    return positionIsFixed;
+}
+
+inline
+void ElementBase::setActionRange(const std::queue<std::pair<double, double> > &range) {
+    actionRange_m = range;
+
+    if (actionRange_m.size() > 0)
+        elementEdge_m = actionRange_m.front().first;
+}
+
+inline
+void ElementBase::setRotationAboutZ(double rotation) {
+    rotationZAxis_m = rotation;
+}
+
+inline
+double ElementBase::getRotationAboutZ() const {
+    return rotationZAxis_m;
+}
+
+inline
+std::string ElementBase::getTypeString() const
 { return getTypeString(getType());}
 
 #endif // CLASSIC_ElementBase_HH
\ No newline at end of file
diff --git a/src/Classic/AbsBeamline/Lambertson.cpp b/src/Classic/AbsBeamline/Lambertson.cpp
index 64b30af79c2baecdfb120c0e0bb487af8ff63969..318e8d9c8cd0700300f4ce8116c841b9e6b229e7 100644
--- a/src/Classic/AbsBeamline/Lambertson.cpp
+++ b/src/Classic/AbsBeamline/Lambertson.cpp
@@ -48,19 +48,7 @@ void Lambertson::accept(BeamlineVisitor &visitor) const {
     visitor.visitLambertson(*this);
 }
 
-bool Lambertson::apply(const size_t &i, const double &t, double E[], double B[]) {
-    return false;
-}
-
-bool Lambertson::apply(const size_t &i, const double &t, Vector_t &E, Vector_t &B) {
-    return false;
-}
-
-bool Lambertson::apply(const Vector_t &R, const Vector_t &centroid, const double &t, Vector_t &E, Vector_t &B) {
-    return false;
-}
-
-void Lambertson::initialise(PartBunch *bunch, double &startField, double &endField, const double &scaleFactor) {
+void Lambertson::initialise(PartBunch *bunch, double &startField, double &endField) {
     RefPartBunch_m = bunch;
 }
 
@@ -77,4 +65,4 @@ void Lambertson::getDimensions(double &zBegin, double &zEnd) const {
 
 ElementBase::ElementType Lambertson::getType() const {
     return LAMBERTSON;
-}
+}
\ No newline at end of file
diff --git a/src/Classic/AbsBeamline/Lambertson.h b/src/Classic/AbsBeamline/Lambertson.h
index 12f98504ff73e15f54b6c6e2da126b567453ba93..1be3b1d7a258390dd5edd6c044e471f8316ece5a 100644
--- a/src/Classic/AbsBeamline/Lambertson.h
+++ b/src/Classic/AbsBeamline/Lambertson.h
@@ -44,13 +44,7 @@ public:
     /// Apply visitor to Lambertson.
     virtual void accept(BeamlineVisitor &) const;
 
-    virtual bool apply(const size_t &i, const double &t, double E[], double B[]);
-
-    virtual bool apply(const size_t &i, const double &t, Vector_t &E, Vector_t &B);
-
-    virtual bool apply(const Vector_t &R, const Vector_t &centroid, const double &t, Vector_t &E, Vector_t &B);
-
-    virtual void initialise(PartBunch *bunch, double &startField, double &endField, const double &scaleFactor);
+    virtual void initialise(PartBunch *bunch, double &startField, double &endField);
 
     virtual void finalise();
 
@@ -66,4 +60,4 @@ private:
     void operator=(const Lambertson &);
 };
 
-#endif // CLASSIC_Lambertson_HH
+#endif // CLASSIC_Lambertson_HH
\ No newline at end of file
diff --git a/src/Classic/AbsBeamline/Marker.cpp b/src/Classic/AbsBeamline/Marker.cpp
index 2bc13f8e251f817f0c2efc7eeaaf26c1051c1935..edc37d9c2da5747be9e8deaf7ad2d58d73fa13a0 100644
--- a/src/Classic/AbsBeamline/Marker.cpp
+++ b/src/Classic/AbsBeamline/Marker.cpp
@@ -49,19 +49,7 @@ void Marker::accept(BeamlineVisitor &visitor) const {
     visitor.visitMarker(*this);
 }
 
-bool Marker::apply(const size_t &i, const double &t, double E[], double B[]) {
-    return false;
-}
-
-bool Marker::apply(const size_t &i, const double &t, Vector_t &E, Vector_t &B) {
-    return false;
-}
-
-bool Marker::apply(const Vector_t &R, const Vector_t &centroid, const double &t, Vector_t &E, Vector_t &B) {
-    return false;
-}
-
-void Marker::initialise(PartBunch *bunch, double &startField, double &endField, const double &scaleFactor) {
+void Marker::initialise(PartBunch *bunch, double &startField, double &endField) {
     RefPartBunch_m = bunch;
 }
 
@@ -79,4 +67,4 @@ void Marker::getDimensions(double &zBegin, double &zEnd) const {
 
 ElementBase::ElementType Marker::getType() const {
     return MARKER;
-}
+}
\ No newline at end of file
diff --git a/src/Classic/AbsBeamline/Marker.h b/src/Classic/AbsBeamline/Marker.h
index 8a768cf01a34cdb54a94e7d68c740dc229fe1807..120fce0c5f4c791501e516458b8dbc5133c98f90 100644
--- a/src/Classic/AbsBeamline/Marker.h
+++ b/src/Classic/AbsBeamline/Marker.h
@@ -43,13 +43,7 @@ public:
     /// Apply visitor to Marker.
     virtual void accept(BeamlineVisitor &) const;
 
-    virtual bool apply(const size_t &i, const double &t, double E[], double B[]);
-
-    virtual bool apply(const size_t &i, const double &t, Vector_t &E, Vector_t &B);
-
-    virtual bool apply(const Vector_t &R, const Vector_t &centroid, const double &t, Vector_t &E, Vector_t &B);
-
-    virtual void initialise(PartBunch *bunch, double &startField, double &endField, const double &scaleFactor);
+    virtual void initialise(PartBunch *bunch, double &startField, double &endField);
 
     virtual void finalise();
 
@@ -65,4 +59,4 @@ private:
     void operator=(const Marker &);
 };
 
-#endif // CLASSIC_Marker_HH
+#endif // CLASSIC_Marker_HH
\ No newline at end of file
diff --git a/src/Classic/AbsBeamline/Monitor.cpp b/src/Classic/AbsBeamline/Monitor.cpp
index b26de89537790b2c41c94b90053ae5be191415a3..83a8722720335a57927553a8d58586c0cc01c1d0 100644
--- a/src/Classic/AbsBeamline/Monitor.cpp
+++ b/src/Classic/AbsBeamline/Monitor.cpp
@@ -24,24 +24,27 @@
 #include "Fields/Fieldmap.h"
 #include "Structure/LossDataSink.h"
 #include "Utilities/Options.h"
+#include "Utilities/Util.h"
+#include <boost/filesystem.hpp>
+#include "AbstractObjects/OpalData.h"
 
 #include <memory>
 
 #include <fstream>
 #include <memory>
 
+extern Inform *gmsg;
+
 using namespace std;
 
 // Class Monitor
 // ------------------------------------------------------------------------
-
 Monitor::Monitor():
     Component(),
     filename_m(""),
     plane_m(OFF),
     type_m(SPATIAL),
-    position_m(0.0),
-    informed_m(false)
+    numPassages_m(0)
 {}
 
 
@@ -50,8 +53,7 @@ Monitor::Monitor(const Monitor &right):
     filename_m(right.filename_m),
     plane_m(right.plane_m),
     type_m(right.type_m),
-    position_m(right.position_m),
-    informed_m(right.informed_m)
+    numPassages_m(0)
 {}
 
 
@@ -60,8 +62,7 @@ Monitor::Monitor(const std::string &name):
     filename_m(""),
     plane_m(OFF),
     type_m(SPATIAL),
-    position_m(0.0),
-    informed_m(false)
+    numPassages_m(0)
 {}
 
 
@@ -73,54 +74,100 @@ void Monitor::accept(BeamlineVisitor &visitor) const {
     visitor.visitMonitor(*this);
 }
 
-bool Monitor::apply(const size_t &i, const double &t, double E[], double B[]) {
-    Vector_t Ev(0, 0, 0), Bv(0, 0, 0);
-    return apply(i, t, Ev, Bv);
-}
-
 bool Monitor::apply(const size_t &i, const double &t, Vector_t &E, Vector_t &B) {
     const Vector_t &R = RefPartBunch_m->R[i];
     const Vector_t &P = RefPartBunch_m->P[i];
-    const double recpgamma = Physics::c * RefPartBunch_m->getdT() / sqrt(1.0  + dot(P, P));
-    if(online_m) {
-        if (type_m == SPATIAL) {
-            if (R(2) < position_m && R(2) + P(2) * recpgamma > position_m) {
-                double frac = (position_m - R(2)) / (P(2) * recpgamma);
-
-                lossDs_m->addParticle(Vector_t(R(0) + frac * P(0) * recpgamma, R(1) + frac * P(1) * recpgamma, position_m),
-                                      P, RefPartBunch_m->ID[i], t + frac * RefPartBunch_m->getdT(), 0);
-            }
-        } else {
-            const Vector_t rmean = RefPartBunch_m->get_rmean();
-            const Vector_t pmean = RefPartBunch_m->get_pmean();
-            double recpgammamean = Physics::c * RefPartBunch_m->getdT() / sqrt(1.0  + dot(pmean, pmean));
-
-            if (rmean(2) < position_m && rmean(2) + pmean(2) * recpgammamean > position_m) {
-                double frac = (position_m - rmean(2)) / (pmean(2) * recpgammamean);
-
-                lossDs_m->addParticle(R + frac * P * recpgamma, P, RefPartBunch_m->ID[i],
-                                      t + frac * RefPartBunch_m->getdT(), 0);
-            }
+    const double &dt = RefPartBunch_m->dt[i];
+    const double recpgamma = Physics::c * dt / Util::getGamma(P);
+    const double middle = 0.5 * getElementLength();
+    if (online_m && type_m == SPATIAL) {
+        if (R(2) < middle && R(2) + P(2) * recpgamma > middle) {
+            double frac = (middle - R(2)) / (P(2) * recpgamma);
+
+            lossDs_m->addParticle(R + frac * recpgamma * P,
+                                  P, RefPartBunch_m->ID[i], t + frac * dt, 0);
         }
     }
 
     return false;
 }
 
-bool Monitor::apply(const Vector_t &R, const Vector_t &centroid, const double &t, Vector_t &E, Vector_t &B) {
+bool Monitor::applyToReferenceParticle(const Vector_t &R,
+                                       const Vector_t &P,
+                                       const double &t,
+                                       Vector_t &,
+                                       Vector_t &) {
+    if (!OpalData::getInstance()->isInPrepState()) {
+        const double dt = RefPartBunch_m->getdT();
+        const double recpgamma = Physics::c * dt / Util::getGamma(P);
+        const double middle = 0.5 * getElementLength();
+
+        if (R(2) < middle && R(2) + P(2) * recpgamma > middle) {
+            double frac = (middle - R(2)) / (P(2) * recpgamma);
+            double time = t + frac * dt;
+            Vector_t dR = (0.5 + frac) * P * recpgamma;
+            double ds = euclidian_norm(dR);
+            lossDs_m->addReferenceParticle(csTrafoGlobal2Local_m.transformFrom(R + dR),
+                                           csTrafoGlobal2Local_m.rotateFrom(P),
+                                           time,
+                                           RefPartBunch_m->get_sPos() + ds,
+                                           RefPartBunch_m->getGlobalTrackStep());
+
+            if (type_m == TEMPORAL) {
+                const unsigned int localNum = RefPartBunch_m->getLocalNum();
+
+                for (unsigned int i = 0; i < localNum; ++ i) {
+                    const double recpgamma = Physics::c * dt / Util::getGamma(RefPartBunch_m->P[i]);
+                    lossDs_m->addParticle(RefPartBunch_m->R[i] + frac * RefPartBunch_m->P[i] * recpgamma,
+                                          RefPartBunch_m->P[i], RefPartBunch_m->ID[i],
+                                          time, 0);
+                }
+                Options::OPENMODE mode = Options::openMode;
+                if (numPassages_m > 0) {
+                    Options::openMode = Options::APPEND;
+                }
+                lossDs_m->save();
+                if (numPassages_m > 0) {
+                    Options::openMode = mode;
+                }
+            }
+
+            ++ numPassages_m;
+        }
+    }
     return false;
 }
 
-void Monitor::initialise(PartBunch *bunch, double &startField, double &endField, const double &scaleFactor) {
+void Monitor::initialise(PartBunch *bunch, double &startField, double &endField) {
     RefPartBunch_m = bunch;
-    position_m = startField;
-    startField -= 0.005;
-    endField = position_m + 0.005;
+    endField = startField + halfLength_s;
+    startField -= halfLength_s;
+
     if (filename_m == std::string(""))
-        lossDs_m = std::unique_ptr<LossDataSink>(new LossDataSink(getName(), !Options::asciidump));
+        filename_m = getName();
     else
-        lossDs_m = std::unique_ptr<LossDataSink>(new LossDataSink(filename_m.substr(0, filename_m.rfind(".")), !Options::asciidump));
+        filename_m = filename_m.substr(0, filename_m.rfind("."));
+
+    const size_t totalNum = bunch->getTotalNum();
+    double currentPosition = endField;
+    if (totalNum > 0) {
+        currentPosition = bunch->get_sPos();
+    }
+
+    if (Options::openMode == Options::WRITE || currentPosition < startField) {
+        namespace fs = boost::filesystem;
+
+        fs::path lossFileName = fs::path(filename_m + ".h5");
+        if (fs::exists(lossFileName)) {
+            Ippl::Comm->barrier();
+            if (Ippl::myNode() == 0)
+                fs::remove(lossFileName);
 
+            Ippl::Comm->barrier();
+        }
+    }
+
+    lossDs_m = std::unique_ptr<LossDataSink>(new LossDataSink(filename_m, !Options::asciidump, getType()));
 }
 
 void Monitor::finalise() {
@@ -128,34 +175,18 @@ void Monitor::finalise() {
 }
 
 void Monitor::goOnline(const double &) {
-    if(RefPartBunch_m == NULL) {
-        if(!informed_m) {
-            Inform msg("Monitor ");
-            std::string errormsg;
-            errormsg = Fieldmap::typeset_msg("BUNCH SIZE NOT SET", "warning");
-            msg << errormsg << "\n"
-                << endl;
-            if(Ippl::myNode() == 0) {
-                ofstream omsg("errormsg.txt", ios_base::app);
-                omsg << errormsg << endl;
-                omsg.close();
-            }
-            informed_m = true;
-        }
-        return;
-    }
-
     if(Monitor::h5pfiles_s.find(filename_m) == Monitor::h5pfiles_s.end()) {
         Monitor::h5pfiles_s.insert(pair<string, unsigned int>(filename_m, 1));
-        step_m = 0;
     } else {
-        step_m = (*Monitor::h5pfiles_s.find(filename_m)).second ++;
+        (*Monitor::h5pfiles_s.find(filename_m)).second ++;
     }
     online_m = true;
 }
 
 void Monitor::goOffline() {
-    lossDs_m->save();
+    if (type_m != TEMPORAL) {
+        lossDs_m->save(numPassages_m);
+    }
 }
 
 bool Monitor::bends() const {
@@ -167,8 +198,8 @@ void Monitor::setOutputFN(std::string fn) {
 }
 
 void Monitor::getDimensions(double &zBegin, double &zEnd) const {
-    zBegin = position_m - 0.005;
-    zEnd = position_m + 0.005;
+    zBegin = -halfLength_s;
+    zEnd = halfLength_s;
 }
 
 
@@ -176,137 +207,5 @@ ElementBase::ElementType Monitor::getType() const {
     return MONITOR;
 }
 
-void Monitor::moveBy(const double &dz) {
-    position_m += dz;
-}
-
 map<string, unsigned int> Monitor::h5pfiles_s = map<string, unsigned int>();
-
-
-
-
-    /*
-    if (!Options::enableHDF5) return;
-
-	reduce(online_m, online_m, OpOr());
-
-    if(online_m) {
-        online_m = false;
-        if(filename_m == "") return;
-
-        unsigned long nLoc = PosX_m.size();
-        unsigned long i = 0;
-        h5_file_t *H5file;
-        h5_int64_t rc;
-        if(step_m == 0) {
-#ifdef PARALLEL_IO
-	    h5_prop_t props = H5CreateFileProp ();
-	    MPI_Comm = Ippl::getComm();
-	    H5SetPropFileMPIOCollective (props, &comm);
-            H5file = H5OpenFile(filename_m.c_str(), H5_O_WRONLY, props);
-#else
-            H5file = H5OpenFile(filename_m.c_str(), H5_O_WRONLY, H5_PROP_DEFAULT);
-#endif
-            rc = H5WriteFileAttribString(H5file, "timeUnit", "s");
-            if(rc != H5_SUCCESS)
-                ERRORMSG("H5 rc= " << rc << " in " << __FILE__ << " @ line " << __LINE__ << endl);
-            rc = H5WriteFileAttribString(H5file, "xUnit", "m");
-            if(rc != H5_SUCCESS)
-                ERRORMSG("H5 rc= " << rc << " in " << __FILE__ << " @ line " << __LINE__ << endl);
-            rc = H5WriteFileAttribString(H5file, "yUnit", "m");
-            if(rc != H5_SUCCESS)
-                ERRORMSG("H5 rc= " << rc << " in " << __FILE__ << " @ line " << __LINE__ << endl);
-            rc = H5WriteFileAttribString(H5file, "pxUnit", "#beta#gamma");
-            if(rc != H5_SUCCESS)
-                ERRORMSG("H5 rc= " << rc << " in " << __FILE__ << " @ line " << __LINE__ << endl);
-            rc = H5WriteFileAttribString(H5file, "pyUnit", "#beta#gamma");
-            if(rc != H5_SUCCESS)
-                ERRORMSG("H5 rc= " << rc << " in " << __FILE__ << " @ line " << __LINE__ << endl);
-            rc = H5WriteFileAttribString(H5file, "pzUnit", "#beta#gamma");
-            if(rc != H5_SUCCESS)
-                ERRORMSG("H5 rc= " << rc << " in " << __FILE__ << " @ line " << __LINE__ << endl);
-            rc = H5WriteFileAttribString(H5file, "SPOSUnit", "m");
-            if(rc != H5_SUCCESS)
-                ERRORMSG("H5 rc= " << rc << " in " << __FILE__ << " @ line " << __LINE__ << endl);
-        } else {
-#ifdef PARALLEL_IO
-            H5file = H5OpenFile(filename_m.c_str(), H5_O_APPEND, Ippl::getComm());
-#else
-            H5file = H5OpenFile(filename_m.c_str(), H5_O_APPEND, 0);
-#endif
-        }
-
-        rc = H5SetStep(H5file, step_m);
-        if(rc != H5_SUCCESS)
-            ERRORMSG("H5 rc= " << rc << " in " << __FILE__ << " @ line " << __LINE__ << endl);
-        rc = H5WriteStepAttribFloat64(H5file, "SPOS", &position_m, 1);
-        if(rc != H5_SUCCESS)
-            ERRORMSG("H5 rc= " << rc << " in " << __FILE__ << " @ line " << __LINE__ << endl);
-        rc = H5PartSetNumParticles(H5file, PosX_m.size());
-        if(rc != H5_SUCCESS)
-            ERRORMSG("H5 rc= " << rc << " in " << __FILE__ << " @ line " << __LINE__ << endl);
-
-        std::unique_ptr<char> varray(new char[nLoc * sizeof(double)]);
-        double *fvalues = reinterpret_cast<double*>(varray.get());
-        h5_int64_t *ids = reinterpret_cast<h5_int64_t*>(varray.get());
-
-	  FixMe: if I write with nLoc==0 -> rc == -2
-
-
-
-	if (nLoc > 0) {
-	  for(i = 0; i < nLoc; ++i) {
-            fvalues[i] = PosX_m.front();
-            PosX_m.pop_front();
-	  }
-	  rc = H5PartWriteDataFloat64(H5file, "x", fvalues);
-	  if(rc != H5_SUCCESS)
-	    ERRORMSG("H5 rc= " << rc << " in " << __FILE__ << " @ line " << __LINE__ << " nloc= " << nLoc << " fn= " << filename_m << endl);
-	  for(i = 0; i < nLoc; ++i) {
-            fvalues[i] = PosY_m.front();
-            PosY_m.pop_front();
-	  }
-	  rc = H5PartWriteDataFloat64(H5file, "y", fvalues);
-	  if(rc != H5_SUCCESS)
-            ERRORMSG("H5 rc= " << rc << " in " << __FILE__ << " @ line " << __LINE__ << endl);
-	  for(i = 0; i < nLoc; ++i) {
-            fvalues[i] = MomentumX_m.front();
-            MomentumX_m.pop_front();
-	  }
-	  rc = H5PartWriteDataFloat64(H5file, "px", fvalues);
-	  if(rc != H5_SUCCESS)
-            ERRORMSG("H5 rc= " << rc << " in " << __FILE__ << " @ line " << __LINE__ << endl);
-	  for(i = 0; i < nLoc; ++i) {
-            fvalues[i] = MomentumY_m.front();
-            MomentumY_m.pop_front();
-	  }
-	  rc = H5PartWriteDataFloat64(H5file, "py", fvalues);
-	  if(rc != H5_SUCCESS)
-            ERRORMSG("H5 rc= " << rc << " in " << __FILE__ << " @ line " << __LINE__ << endl);
-	  for(i = 0; i < nLoc; ++i) {
-            fvalues[i] = MomentumZ_m.front();
-            MomentumZ_m.pop_front();
-	  }
-	  rc = H5PartWriteDataFloat64(H5file, "pz", fvalues);
-	  if(rc != H5_SUCCESS)
-            ERRORMSG("H5 rc= " << rc << " in " << __FILE__ << " @ line " << __LINE__ << endl);
-	  for(i = 0; i < nLoc; ++i) {
-            fvalues[i] = time_m.front();
-            time_m.pop_front();
-	  }
-	  rc = H5PartWriteDataFloat64(H5file, "time", fvalues);
-	  if(rc != H5_SUCCESS)
-            ERRORMSG("H5 rc= " << rc << " in " << __FILE__ << " @ line " << __LINE__ << endl);
-	  for(i = 0; i < nLoc; ++i) {
-            ids[i] = id_m.front();
-            id_m.pop_front();
-	  }
-	  rc = H5PartWriteDataInt64(H5file, "id", ids);
-	  if(rc != H5_SUCCESS)
-            ERRORMSG("H5 rc= " << rc << " in " << __FILE__ << " @ line " << __LINE__ << endl);
-	}
-        rc = H5CloseFile(H5file);
-        if(rc != H5_SUCCESS)
-	  ERRORMSG("H5 rc= " << rc << " in " << __FILE__ << " @ line " << __LINE__ << endl);
-    }
-    */
+const double Monitor::halfLength_s = 0.005;
\ No newline at end of file
diff --git a/src/Classic/AbsBeamline/Monitor.h b/src/Classic/AbsBeamline/Monitor.h
index cc2cf70cc129595e74386cb451bff1170c7348d5..6f68843c07d48e55fa35d0023213091b35a8dc3f 100644
--- a/src/Classic/AbsBeamline/Monitor.h
+++ b/src/Classic/AbsBeamline/Monitor.h
@@ -76,13 +76,15 @@ public:
     /// Get plane on which monitor observes.
     virtual Plane getPlane() const = 0;
 
-    virtual bool apply(const size_t &i, const double &t, double E[], double B[]);
-
     virtual bool apply(const size_t &i, const double &t, Vector_t &E, Vector_t &B);
 
-    virtual bool apply(const Vector_t &R, const Vector_t &centroid, const double &t, Vector_t &E, Vector_t &B);
+    virtual bool applyToReferenceParticle(const Vector_t &R,
+                                          const Vector_t &P,
+                                          const double &t,
+                                          Vector_t &E,
+                                          Vector_t &B);
 
-    virtual void initialise(PartBunch *bunch, double &startField, double &endField, const double &scaleFactor);
+    virtual void initialise(PartBunch *bunch, double &startField, double &endField);
 
     virtual void finalise();
 
@@ -99,27 +101,25 @@ public:
     void setOutputFN(std::string fn);
 
     void setType(Type type);
-
-    void moveBy(const double & dz);
 private:
 
     // Not implemented.
     void operator=(const Monitor &);
     std::string filename_m;               /**< The name of the outputfile*/
     Plane plane_m;
-    double position_m;
     Type type_m;
-
-    bool informed_m;
-    unsigned int step_m;
+    unsigned int numPassages_m;
 
     static std::map<std::string, unsigned int> h5pfiles_s;
 
     std::unique_ptr<LossDataSink> lossDs_m;
+
+    static const double halfLength_s;
 };
 
 inline
 void Monitor::setType(Monitor::Type type) {
     type_m = type;
 }
-#endif // CLASSIC_Monitor_HH
+
+#endif // CLASSIC_Monitor_HH
\ No newline at end of file
diff --git a/src/Classic/AbsBeamline/Multipole.cpp b/src/Classic/AbsBeamline/Multipole.cpp
index 85fe880f6ef96a817ccf689609b99a2e942a03ba..3d7c32141efd48b8255ecb7ed88fdb7e28e3dcd6 100644
--- a/src/Classic/AbsBeamline/Multipole.cpp
+++ b/src/Classic/AbsBeamline/Multipole.cpp
@@ -35,16 +35,18 @@ namespace{
         DECAPOLE
     };
 }
+
 // Class Multipole
 // ------------------------------------------------------------------------
 
 Multipole::Multipole():
     Component(),
     NormalComponents(1, 0.0),
+    NormalComponentErrors(1, 0.0),
     SkewComponents(1, 0.0),
+    SkewComponentErrors(1, 0.0),
     max_SkewComponent_m(1),
-    max_NormalComponent_m(1),
-    myFieldmap_m(NULL) {
+    max_NormalComponent_m(1) {
     setElType(isMultipole);
 }
 
@@ -52,10 +54,11 @@ Multipole::Multipole():
 Multipole::Multipole(const Multipole &right):
     Component(right),
     NormalComponents(right.NormalComponents),
+    NormalComponentErrors(right.NormalComponentErrors),
     SkewComponents(right.SkewComponents),
+    SkewComponentErrors(right.SkewComponentErrors),
     max_SkewComponent_m(right.max_SkewComponent_m),
-    max_NormalComponent_m(right.max_NormalComponent_m),
-    myFieldmap_m(right.myFieldmap_m) {
+    max_NormalComponent_m(right.max_NormalComponent_m) {
     setElType(isMultipole);
 }
 
@@ -63,10 +66,11 @@ Multipole::Multipole(const Multipole &right):
 Multipole::Multipole(const std::string &name):
     Component(name),
     NormalComponents(1, 0.0),
+    NormalComponentErrors(1, 0.0),
     SkewComponents(1, 0.0),
+    SkewComponentErrors(1, 0.0),
     max_SkewComponent_m(1),
-    max_NormalComponent_m(1),
-    myFieldmap_m(NULL) {
+    max_NormalComponent_m(1) {
     setElType(isMultipole);
 }
 
@@ -81,87 +85,82 @@ void Multipole::accept(BeamlineVisitor &visitor) const {
 
 
 double Multipole::getNormalComponent(int n) const {
-    return getField().getNormalComponent(n);
+    if (n < max_NormalComponent_m) {
+        return NormalComponents[n];
+    }
+    return 0.0;
 }
 
 
 double Multipole::getSkewComponent(int n) const {
-    return getField().getSkewComponent(n);
+    if (n < max_SkewComponent_m) {
+        return SkewComponents[n];
+    }
+    return 0.0;
 }
 
 
-void Multipole::setNormalComponent(int n, double v) {
+void Multipole::setNormalComponent(int n, double v, double vError) {
     //   getField().setNormalComponent(n, v);
     PAssert(n >= 1);
 
     if(n >  max_NormalComponent_m) {
         max_NormalComponent_m = n;
         NormalComponents.resize(max_NormalComponent_m, 0.0);
+        NormalComponentErrors.resize(max_NormalComponent_m, 0.0);
     }
     switch(n-1) {
+    case DIPOLE:
+        NormalComponents[n - 1] = (v + vError) / 2;
+        NormalComponentErrors[n - 1] = NormalComponents[n - 1];
+        break;
     case SEXTUPOLE:
-        NormalComponents[n - 1] = v / 2;
+        NormalComponents[n - 1] = (v + vError) / 2;
+        NormalComponentErrors[n - 1] = vError / 2;
         break;
     case OCTUPOLE:
     case DECAPOLE:
-        NormalComponents[n - 1] = v / 24;
+        NormalComponents[n - 1] = (v + vError) / 24;
+        NormalComponentErrors[n - 1] = vError / 24;
         break;
     default:
-        NormalComponents[n - 1] = v;
+        NormalComponents[n - 1] = (v + vError);
+        NormalComponentErrors[n - 1] = vError;
     }
 }
 
-void Multipole::setSkewComponent(int n, double v) {
+void Multipole::setSkewComponent(int n, double v, double vError) {
     //   getField().setSkewComponent(n, v);
     PAssert(n >= 1);
 
-    if(n > max_SkewComponent_m) {
+    if(n  > max_SkewComponent_m) {
         max_SkewComponent_m = n;
         SkewComponents.resize(max_SkewComponent_m, 0.0);
+        SkewComponentErrors.resize(max_SkewComponent_m, 0.0);
     }
     switch(n-1) {
+    case DIPOLE:
+        SkewComponents[n - 1] = (v + vError) / 2;
+        SkewComponentErrors[n - 1] = SkewComponents[n - 1];
+        break;
     case SEXTUPOLE:
-        SkewComponents[n - 1] = v / 2;
+        SkewComponents[n - 1] = (v + vError) / 2;
+        SkewComponentErrors[n - 1] = vError / 2;
         break;
     case OCTUPOLE:
-        SkewComponents[n - 1] = v / 6;
+        SkewComponents[n - 1] = (v + vError) / 6;
+        SkewComponentErrors[n - 1] = vError / 6;
         break;
     case DECAPOLE:
-        SkewComponents[n - 1] = v / 24;
+        SkewComponents[n - 1] = (v + vError) / 24;
+        SkewComponentErrors[n - 1] = vError / 24;
         break;
     default:
-        SkewComponents[n - 1] = v;
+        SkewComponents[n - 1] = (v + vError);
+        SkewComponentErrors[n - 1] = vError;
     }
 }
 
-double Multipole::EngeFunc(double z) {
-  const double a1 = 0.296417;
-  const double a2 = 4.533;
-  const double a3 = -2.27;
-  const double a4 = 1.06;
-  const double a5 = -0.03;
-  const double a6 = 0.02;					\
-  const double DD = 0.99;
-
-  const double y = z - 1.0;
-  return 1.0/(1 + std::exp(a1 + a2*(y/DD) + a3*std::pow(y/DD,2) + a4*std::pow(y/DD,3) + a5*std::pow(y/DD,4) + a6*std::pow(y/DD,5)));
-}
-
-double Multipole::EngeFact(double z) {
-  // Normalize
-  const double lFringe = std::abs(endField_m-startField_m);
-  const double zn = (z - startField_m) / lFringe;
-
-  const double scale = 1.0; // 1.4289638937448055; // to make integrated field strenght like the hard edge approximation
-
-  if(zn > 0.5) {
-    return scale*EngeFunc((zn-0.5)*10 - 3.) ;
-  }
-  else
-    return scale*EngeFunc((0.5-zn)*10 - 3.) ;
-}
-
-
 //ff
 // radial focussing term
 void Multipole::addKR(int i, double t, Vector_t &K) {
@@ -208,143 +207,143 @@ void Multipole::addKT(int i, double t, Vector_t &K) {
 
     double G = temp_n / l;
     double cf = -Physics::q_e * b * Physics::c * G / (g * Physics::EMASS);
-    double dx = RefPartBunch_m->getX0(i) - dx_m;
-    double dy = RefPartBunch_m->getY0(i) - dy_m;
+    double dx = RefPartBunch_m->getX0(i);
+    double dy = RefPartBunch_m->getY0(i);
 
     K += Vector_t(cf * dx, -cf * dy, 0.0);
 }
 
-void Multipole::computeField(Vector_t R, const double &t, Vector_t &E, Vector_t &B) {
-
-    if(R(2) > startField_m && R(2) <= endField_m) {
-
-        {
-            std::vector<Vector_t> Rn(max_NormalComponent_m + 1);
-            std::vector<double> fact(max_NormalComponent_m + 1);
-            Rn[0] = Vector_t(1.0);
-            fact[0] = 1;
-            for (int i = 0; i < max_NormalComponent_m; ++ i) {
-                switch(i) {
-                case DIPOLE:
-                    B(1) += NormalComponents[i];
-                    break;
-
-                case QUADRUPOLE:
-                    B(0) += NormalComponents[i] * R(1);
-                    B(1) += NormalComponents[i] * R(0);
-                    break;
-
-                case SEXTUPOLE:
-                    B(0) += 2 * NormalComponents[i] * R(0) * R(1);
-                    B(1) += NormalComponents[i] * (Rn[2](0) - Rn[2](1));
-                    break;
-
-                case OCTUPOLE:
-                    B(0) += NormalComponents[i] * (3 * Rn[2](0) * Rn[1](1) - Rn[3](1));
-                    B(1) += NormalComponents[i] * (Rn[3](0) - 3 * Rn[1](0) * Rn[2](1));
-                    break;
-
-                case DECAPOLE:
-                    B(0) += 4 * NormalComponents[i] * (Rn[3](0) * Rn[1](1) - Rn[1](0) * Rn[3](1));
-                    B(1) += NormalComponents[i] * (Rn[4](0) - 6 * Rn[2](0) * Rn[2](1) + Rn[4](1));
-                    break;
-
-                default:
-                    {
-                        double powMinusOne = 1;
-                        double Bx = 0.0, By = 0.0;
-                        for (int j = 1; j <= (i + 1) / 2; ++ j) {
-                            Bx += powMinusOne * NormalComponents[i] * (Rn[i - 2 * j + 1](0) * fact[i - 2 * j + 1] *
-                                                                       Rn[2 * j - 1](1) * fact[2 * j - 1]);
-                            By += powMinusOne * NormalComponents[i] * (Rn[i - 2 * j + 2](0) * fact[i - 2 * j + 2] *
-                                                                       Rn[2 * j - 2](1) * fact[2 * j - 2]);
-                            powMinusOne *= -1;
-                        }
-
-                        if ((i + 1) / 2 == i / 2) {
-                            int j = (i + 2) / 2;
-                            By += powMinusOne * NormalComponents[i] * (Rn[i - 2 * j + 2](0) * fact[i - 2 * j + 2] *
-                                                                       Rn[2 * j - 2](1) * fact[2 * j - 2]);
-                        }
-                        B(0) += Bx;
-                        B(1) += By;
+void Multipole::computeField(Vector_t R, Vector_t &E, Vector_t &B) {
+    {
+        std::vector<Vector_t> Rn(max_NormalComponent_m + 1);
+        std::vector<double> fact(max_NormalComponent_m + 1);
+        Rn[0] = Vector_t(1.0);
+        fact[0] = 1;
+        for (int i = 0; i < max_NormalComponent_m; ++ i) {
+            switch(i) {
+            case DIPOLE:
+                B(1) += NormalComponents[i];
+                break;
+
+            case QUADRUPOLE:
+                B(0) += NormalComponents[i] * R(1);
+                B(1) += NormalComponents[i] * R(0);
+                break;
+
+            case SEXTUPOLE:
+                B(0) += 2 * NormalComponents[i] * R(0) * R(1);
+                B(1) += NormalComponents[i] * (Rn[2](0) - Rn[2](1));
+                break;
+
+            case OCTUPOLE:
+                B(0) += NormalComponents[i] * (3 * Rn[2](0) * Rn[1](1) - Rn[3](1));
+                B(1) += NormalComponents[i] * (Rn[3](0) - 3 * Rn[1](0) * Rn[2](1));
+                break;
+
+            case DECAPOLE:
+                B(0) += 4 * NormalComponents[i] * (Rn[3](0) * Rn[1](1) - Rn[1](0) * Rn[3](1));
+                B(1) += NormalComponents[i] * (Rn[4](0) - 6 * Rn[2](0) * Rn[2](1) + Rn[4](1));
+                break;
+
+            default:
+                {
+                    double powMinusOne = 1;
+                    double Bx = 0.0, By = 0.0;
+                    for (int j = 1; j <= (i + 1) / 2; ++ j) {
+                        Bx += powMinusOne * NormalComponents[i] * (Rn[i - 2 * j + 1](0) * fact[i - 2 * j + 1] *
+                                                                   Rn[2 * j - 1](1) * fact[2 * j - 1]);
+                        By += powMinusOne * NormalComponents[i] * (Rn[i - 2 * j + 2](0) * fact[i - 2 * j + 2] *
+                                                                   Rn[2 * j - 2](1) * fact[2 * j - 2]);
+                        powMinusOne *= -1;
                     }
-                }
 
-                Rn[i + 1](0) = Rn[i](0) * R(0);
-                Rn[i + 1](1) = Rn[i](1) * R(1);
-                fact[i + 1] = fact[i] / (i + 1);
+                    if ((i + 1) / 2 == i / 2) {
+                        int j = (i + 2) / 2;
+                        By += powMinusOne * NormalComponents[i] * (Rn[i - 2 * j + 2](0) * fact[i - 2 * j + 2] *
+                                                                   Rn[2 * j - 2](1) * fact[2 * j - 2]);
+                    }
+                    B(0) += Bx;
+                    B(1) += By;
+                }
             }
+
+            Rn[i + 1](0) = Rn[i](0) * R(0);
+            Rn[i + 1](1) = Rn[i](1) * R(1);
+            fact[i + 1] = fact[i] / (i + 1);
         }
+    }
 
-        {
-
-            std::vector<Vector_t> Rn(max_SkewComponent_m + 1);
-            std::vector<double> fact(max_SkewComponent_m + 1);
-            Rn[0] = Vector_t(1.0);
-            fact[0] = 1;
-            for (int i = 0; i < max_SkewComponent_m; ++ i) {
-                switch(i) {
-                case DIPOLE:
-                    B(0) -= SkewComponents[i];
-                    break;
-
-                case QUADRUPOLE:
-                    B(0) -= SkewComponents[i] * R(0);
-                    B(1) += SkewComponents[i] * R(1);
-                    break;
-
-                case SEXTUPOLE:
-                    B(0) -= SkewComponents[i] * (Rn[2](0) - Rn[2](1));
-                    B(1) += 2 * SkewComponents[i] * R(0) * R(1);
-                    break;
-
-                case OCTUPOLE:
-                    B(0) -= SkewComponents[i] * (Rn[3](0) - 3 * Rn[1](0) * Rn[2](1));
-                    B(1) += SkewComponents[i] * (3 * Rn[2](0) * Rn[1](1) - Rn[3](1));
-                    break;
-
-                case DECAPOLE:
-                    B(0) -= SkewComponents[i] * (Rn[4](0) - 6 * Rn[2](0) * Rn[2](1) + Rn[4](1));
-                    B(1) += 4 * SkewComponents[i] * (Rn[3](0) * Rn[1](1) - Rn[1](0) * Rn[3](1));
-                    break;
-
-                default:
-                    {
-                        double powMinusOne = 1;
-                        double Bx = 0, By = 0;
-                        for (int j = 1; j <= (i + 1) / 2; ++ j) {
-                            Bx -= powMinusOne * SkewComponents[i] * (Rn[i - 2 * j + 2](0) * fact[i - 2 * j + 2] *
-                                                                     Rn[2 * j - 2](1) * fact[2 * j - 2]);
-                            By += powMinusOne * SkewComponents[i] * (Rn[i - 2 * j + 1](0) * fact[i - 2 * j + 1] *
-                                                                     Rn[2 * j - 1](1) * fact[2 * j - 1]);
-                            powMinusOne *= -1;
-                        }
-
-                        if ((i + 1) / 2 == i / 2) {
-                            int j = (i + 2) / 2;
-                            Bx -= powMinusOne * SkewComponents[i] * (Rn[i - 2 * j + 2](0) * fact[i - 2 * j + 2] *
-                                                                     Rn[2 * j - 2](1) * fact[2 * j - 2]);
-                        }
-
-                        B(0) += Bx;
-                        B(1) += By;
+    {
+
+        std::vector<Vector_t> Rn(max_SkewComponent_m + 1);
+        std::vector<double> fact(max_SkewComponent_m + 1);
+        Rn[0] = Vector_t(1.0);
+        fact[0] = 1;
+        for (int i = 0; i < max_SkewComponent_m; ++ i) {
+            switch(i) {
+            case DIPOLE:
+                B(0) -= SkewComponents[i];
+                break;
+
+            case QUADRUPOLE:
+                B(0) -= SkewComponents[i] * R(0);
+                B(1) += SkewComponents[i] * R(1);
+                break;
+
+            case SEXTUPOLE:
+                B(0) -= SkewComponents[i] * (Rn[2](0) - Rn[2](1));
+                B(1) += 2 * SkewComponents[i] * R(0) * R(1);
+                break;
+
+            case OCTUPOLE:
+                B(0) -= SkewComponents[i] * (Rn[3](0) - 3 * Rn[1](0) * Rn[2](1));
+                B(1) += SkewComponents[i] * (3 * Rn[2](0) * Rn[1](1) - Rn[3](1));
+                break;
+
+            case DECAPOLE:
+                B(0) -= SkewComponents[i] * (Rn[4](0) - 6 * Rn[2](0) * Rn[2](1) + Rn[4](1));
+                B(1) += 4 * SkewComponents[i] * (Rn[3](0) * Rn[1](1) - Rn[1](0) * Rn[3](1));
+                break;
+
+            default:
+                {
+                    double powMinusOne = 1;
+                    double Bx = 0, By = 0;
+                    for (int j = 1; j <= (i + 1) / 2; ++ j) {
+                        Bx -= powMinusOne * SkewComponents[i] * (Rn[i - 2 * j + 2](0) * fact[i - 2 * j + 2] *
+                                                                 Rn[2 * j - 2](1) * fact[2 * j - 2]);
+                        By += powMinusOne * SkewComponents[i] * (Rn[i - 2 * j + 1](0) * fact[i - 2 * j + 1] *
+                                                                 Rn[2 * j - 1](1) * fact[2 * j - 1]);
+                        powMinusOne *= -1;
                     }
-                }
 
-                Rn[i + 1](0) = Rn[i](0) * R(0);
-                Rn[i + 1](1) = Rn[i](1) * R(1);
-                fact[i + 1] = fact[i] / (i + 1);
+                    if ((i + 1) / 2 == i / 2) {
+                        int j = (i + 2) / 2;
+                        Bx -= powMinusOne * SkewComponents[i] * (Rn[i - 2 * j + 2](0) * fact[i - 2 * j + 2] *
+                                                                 Rn[2 * j - 2](1) * fact[2 * j - 2]);
+                    }
+
+                    B(0) += Bx;
+                    B(1) += By;
+                }
             }
+
+            Rn[i + 1](0) = Rn[i](0) * R(0);
+            Rn[i + 1](1) = Rn[i](1) * R(1);
+            fact[i + 1] = fact[i] / (i + 1);
         }
     }
-
 }
 
-bool Multipole::apply(const size_t &i, const double &t, double E[], double B[]) {
+
+bool Multipole::apply(const size_t &i, const double &, Vector_t &E, Vector_t &B) {
+    const Vector_t &R = RefPartBunch_m->R[i];
+    if(R(2) < 0.0 || R(2) > getElementLength()) return false;
+    if (!isInsideTransverse(R)) return true;
+
     Vector_t Ef(0.0), Bf(0.0);
-    Vector_t R(RefPartBunch_m->getX(i) - dx_m, RefPartBunch_m->getY(i) - dy_m, RefPartBunch_m->getZ(i) - ds_m);
-    computeField(R, t, Ef, Bf);
+    computeField(R, Ef, Bf);
+
     for (unsigned int d = 0; d < 3; ++ d) {
         E[d] += Ef(d);
         B[d] += Bf(d);
@@ -352,24 +351,42 @@ bool Multipole::apply(const size_t &i, const double &t, double E[], double B[])
 
     return false;
 }
-bool Multipole::apply(const size_t &i, const double &t, Vector_t &E, Vector_t &B) {
-    Vector_t R(RefPartBunch_m->getX(i) - dx_m, RefPartBunch_m->getY(i) - dy_m, RefPartBunch_m->getZ(i) - ds_m);
-    computeField(R, t, E, B);
+
+bool Multipole::apply(const Vector_t &R, const Vector_t &, const double &, Vector_t &E, Vector_t &B) {
+    if(R(2) < 0.0 || R(2) > getElementLength()) return false;
+    if (!isInsideTransverse(R)) return true;
+
+    computeField(R, E, B);
 
     return false;
 }
 
-bool Multipole::apply(const Vector_t &R0, const Vector_t &, const double &t, Vector_t &E, Vector_t &B) {
-    Vector_t R = R0 - Vector_t(dx_m, dy_m, ds_m);
-    computeField(R, t, E, B);
+bool Multipole::applyToReferenceParticle(const Vector_t &R, const Vector_t &, const double &, Vector_t &E, Vector_t &B) {
+    if(R(2) < 0.0 || R(2) > getElementLength()) return false;
+    if (!isInsideTransverse(R)) return true;
+
+    for (int i = 0; i < max_NormalComponent_m; ++ i) {
+        NormalComponents[i] -= NormalComponentErrors[i];
+    }
+    for (int i = 0; i < max_SkewComponent_m; ++ i) {
+        SkewComponents[i] -= SkewComponentErrors[i];
+    }
+
+    computeField(R, E, B);
+
+    for (int i = 0; i < max_NormalComponent_m; ++ i) {
+        NormalComponents[i] += NormalComponentErrors[i];
+    }
+    for (int i = 0; i < max_SkewComponent_m; ++ i) {
+        SkewComponents[i] += SkewComponentErrors[i];
+    }
 
     return false;
 }
-void Multipole::initialise(PartBunch *bunch, double &startField, double &endField, const double&) {
+
+void Multipole::initialise(PartBunch *bunch, double &startField, double &endField) {
     RefPartBunch_m = bunch;
     endField = startField + getElementLength();
-    startField_m = startField;
-    endField_m = endField;
     online_m = true;
 }
 
@@ -384,11 +401,26 @@ bool Multipole::bends() const {
 
 
 void Multipole::getDimensions(double &zBegin, double &zEnd) const {
-    zBegin = startField_m;
-    zEnd = endField_m;
+    zBegin = 0.0;
+    zEnd = getElementLength();
 }
 
 
 ElementBase::ElementType Multipole::getType() const {
     return MULTIPOLE;
+}
+
+
+bool Multipole::isInside(const Vector_t &r) const {
+    if (r(2) >= 0.0 && r(2) < getElementLength()) {
+        return isInsideTransverse(r);
+    }
+
+    return false;
+}
+
+bool Multipole::isFocusing(unsigned int component) const {
+    if (component >= NormalComponents.size()) throw GeneralClassicException("Multipole::isFocusing", "component to big");
+
+    return NormalComponents[component] * std::pow(-1, component + 1) * RefPartBunch_m->getChargePerParticle() > 0.0;
 }
\ No newline at end of file
diff --git a/src/Classic/AbsBeamline/Multipole.h b/src/Classic/AbsBeamline/Multipole.h
index 35a8ef791a0d62d8eb9c1c2cc73a4343d44a3736..037fe2f0ae5c8108497e322d1cb5f9afbe1f1cab 100644
--- a/src/Classic/AbsBeamline/Multipole.h
+++ b/src/Classic/AbsBeamline/Multipole.h
@@ -21,6 +21,7 @@
 #include "AbsBeamline/Component.h"
 #include "BeamlineGeometry/StraightGeometry.h"
 #include "Fields/BMultipoleField.h"
+#include "Utilities/GeneralClassicException.h"
 
 class PartBunch;
 class Fieldmap;
@@ -78,11 +79,26 @@ public:
     //  If [b]n[/b] is larger than the maximum order, the component is created.
     void setNormalComponent(int, double);
 
+    /// Set normal component.
+    //  Set the normal component of order [b]n[/b] in T/m**(n-1).
+    //  If [b]n[/b] is larger than the maximum order, the component is created.
+    void setNormalComponent(int, double, double);
+
     /// Set skew component.
     //  Set the skew component of order [b]n[/b] in T/m**(n-1).
     //  If [b]n[/b] is larger than the maximum order, the component is created.
     void setSkewComponent(int, double);
 
+    /// Set skew component.
+    //  Set the skew component of order [b]n[/b] in T/m**(n-1).
+    //  If [b]n[/b] is larger than the maximum order, the component is created.
+    void setSkewComponent(int, double, double);
+
+    size_t getMaxNormalComponentIndex() const;
+    size_t getMaxSkewComponentIndex() const;
+
+    bool isFocusing(unsigned int component) const;
+
     /// Get geometry.
     virtual StraightGeometry &getGeometry() = 0;
 
@@ -93,13 +109,13 @@ public:
 
     virtual void addKT(int i, double t, Vector_t &K);
 
-    virtual bool apply(const size_t &i, const double &t, double E[], double B[]);
-
     virtual bool apply(const size_t &i, const double &t, Vector_t &E, Vector_t &B);
 
-    virtual bool apply(const Vector_t &R, const Vector_t &centroid, const double &t, Vector_t &E, Vector_t &B);
+    virtual bool apply(const Vector_t &R, const Vector_t &P, const double &t, Vector_t &E, Vector_t &B);
+
+    virtual bool applyToReferenceParticle(const Vector_t &R, const Vector_t &P, const double &t, Vector_t &E, Vector_t &B);
 
-    virtual void initialise(PartBunch *bunch, double &startField, double &endField, const double &scaleFactor);
+    virtual void initialise(PartBunch *bunch, double &startField, double &endField);
 
     virtual void finalise();
 
@@ -109,20 +125,38 @@ public:
 
     virtual void getDimensions(double &zBegin, double &zEnd) const;
 
-    double EngeFact(double z);
-    double EngeFunc(double z);
+    virtual bool isInside(const Vector_t &r) const;
 private:
-    void computeField(Vector_t R, const double &t, Vector_t &E, Vector_t &B);
+    void computeField(Vector_t R, Vector_t &E, Vector_t &B);
 
     // Not implemented.
     void operator=(const Multipole &);
     std::vector<double> NormalComponents;
+    std::vector<double> NormalComponentErrors;
     std::vector<double> SkewComponents;
-    double startField_m;
-    double endField_m;
+    std::vector<double> SkewComponentErrors;
     int max_SkewComponent_m;
     int max_NormalComponent_m;
-    Fieldmap *myFieldmap_m;
 };
 
+inline
+void Multipole::setNormalComponent(int n, double v) {
+    setNormalComponent(n, v, 0.0);
+}
+
+inline
+void Multipole::setSkewComponent(int n, double v) {
+    setSkewComponent(n, v, 0.0);
+}
+
+inline
+size_t Multipole::getMaxNormalComponentIndex() const {
+    return NormalComponents.size();
+}
+
+inline
+size_t Multipole::getMaxSkewComponentIndex() const {
+    return SkewComponents.size();
+}
+
 #endif // CLASSIC_Multipole_HH
\ No newline at end of file
diff --git a/src/Classic/AbsBeamline/Offset.cpp b/src/Classic/AbsBeamline/Offset.cpp
index 5be020e70052bd57035780afbf84fcb7e4130b52..1c4c4b870411c7d25436cb56674b3f2673363261 100644
--- a/src/Classic/AbsBeamline/Offset.cpp
+++ b/src/Classic/AbsBeamline/Offset.cpp
@@ -95,23 +95,7 @@ const EMField &Offset::getField() const {
                         "No field defined for Offset");
 }
 
-bool Offset::apply(const size_t &i, const double &t,
-                    Vector_t &E, Vector_t &B) {
-    return false;
-}
-
-bool Offset::apply(const size_t &i, const double &t,
-                             double E[], double B[]) {
-    return false;
-}
-
-bool Offset::apply(const Vector_t &R, const Vector_t &centroid,
-                   const double &t, Vector_t &E, Vector_t &B) {
-    return false;
-}
-
-void Offset::initialise(PartBunch *bunch, double &startField, double &endField,
-                const double &scaleFactor) {
+void Offset::initialise(PartBunch *bunch, double &startField, double &endField) {
     RefPartBunch_m = bunch;
 }
 
@@ -313,4 +297,4 @@ Offset Offset::globalCartesianOffset(std::string name,
     off.setEndDirection(end_direction);
     off.setIsLocal(false);
     return off;
-}
+}
\ No newline at end of file
diff --git a/src/Classic/AbsBeamline/Offset.h b/src/Classic/AbsBeamline/Offset.h
index e334c38736c2092df9e935de714a71a71fa6b4ef..b7958c71585c29c371178953a28afcfb305f52a3 100644
--- a/src/Classic/AbsBeamline/Offset.h
+++ b/src/Classic/AbsBeamline/Offset.h
@@ -147,36 +147,13 @@ class Offset : public Component {
     /** Just calls the copy constructor on *this */
     ElementBase* clone() const;
 
-    /** Return false
-     *
-     *  No bound checking is performed and no field value is calculated as this
-     *  element does not have an associated field or beam pipe aperture.
-     */
-    bool apply(const size_t &i, const double &t, double E[], double B[]);
-
-    /** Return false
-     *
-     *  No bound checking is performed and no field value is calculated as this
-     *  element does not have an associated field or beam pipe aperture.
-     */
-    bool apply(const size_t &i, const double &t,
-                       Vector_t &E, Vector_t &B);
-
-    /** Return false
-     *
-     *  No bound checking is performed and no field value is calculated as this
-     *  element does not have an associated field or beam pipe aperture.
-     */
-    bool apply(const Vector_t &R, const Vector_t &centroid,
-                       const double &t, Vector_t &E, Vector_t &B);
-
     /** Returns true if either input angle or output angle are greater than
      *  float_tolerance
      */
     bool bends() const;
 
     void initialise(PartBunch *bunch, double &startField,
-                            double &endField, const double &scaleFactor);
+                            double &endField);
     void finalise();
     void getDimensions(double &zBegin, double &zEnd) const {}
 
@@ -240,4 +217,4 @@ bool operator!=(const Offset& off1, const Offset& off2);
 /** Print Offset off1 to the ostream */
 std::ostream& operator<<(std::ostream& out, const Offset& off1);
 
-#endif  // CLASSIC_ABSBEAMLINE_Offset_HH
+#endif  // CLASSIC_ABSBEAMLINE_Offset_HH
\ No newline at end of file
diff --git a/src/Classic/AbsBeamline/ParallelPlate.cpp b/src/Classic/AbsBeamline/ParallelPlate.cpp
index 91a8430d53cc3a46ed3fa82334837e7ce9d7b32d..075b456dd400e822d019cf998abf3ec182d99729 100644
--- a/src/Classic/AbsBeamline/ParallelPlate.cpp
+++ b/src/Classic/AbsBeamline/ParallelPlate.cpp
@@ -22,7 +22,6 @@
 #include "AbsBeamline/ParallelPlate.h"
 #include "AbsBeamline/BeamlineVisitor.h"
 #include "Algorithms/PartBunch.h"
-#include "Fields/Fieldmap.h"
 #include "Physics/Physics.h"
 
 #include <iostream>
@@ -40,9 +39,6 @@ ParallelPlate::ParallelPlate():
     phase_m(0.0),
     frequency_m(0.0),
     length_m(0.0),
-    startField_m(0.0),
-    endField_m(0.0),
-    ElementEdge_m(0.0),
     ptime_m(0.0) {
     setElType(isRF);
 }
@@ -55,9 +51,6 @@ ParallelPlate::ParallelPlate(const ParallelPlate &right):
     phase_m(right.phase_m),
     frequency_m(right.frequency_m),
     length_m(right.length_m),
-    startField_m(right.startField_m),
-    endField_m(right.endField_m),
-    ElementEdge_m(right.ElementEdge_m),
     ptime_m(0.0) {
     setElType(isRF);
 }
@@ -70,9 +63,6 @@ ParallelPlate::ParallelPlate(const std::string &name):
     phase_m(0.0),
     frequency_m(0.0),
     length_m(0.0),
-    startField_m(0.0),
-    endField_m(0.0),
-    ElementEdge_m(0.0),
     ptime_m(0.0) {
     setElType(isRF);
 }
@@ -117,85 +107,50 @@ double ParallelPlate::getPhase() const {
     return phase_m;
 }
 
-void ParallelPlate::setElementLength(double length) {
-    length_m = length;
-}
-
-double ParallelPlate::getElementLength() const {
-    return length_m;
-}
+// void ParallelPlate::setElementLength(double length) {
+//     length_m = length;
+// }
 
+// double ParallelPlate::getElementLength() const {
+//     return length_m;
+// }
 
-bool ParallelPlate::apply(const size_t &i, const double &t, double E[], double B[]) {
-    Vector_t Ev(0, 0, 0), Bv(0, 0, 0);
-    Vector_t Rt(RefPartBunch_m->getX(i), RefPartBunch_m->getY(i), RefPartBunch_m->getZ(i));
-    if(apply(Rt, Vector_t(0.0), t, Ev, Bv)) return true;
 
-    E[0] = Ev(0);
-    E[1] = Ev(1);
-    E[2] = Ev(2);
-    B[0] = Bv(0);
-    B[1] = Bv(1);
-    B[2] = Bv(2);
-
-    return false;
+bool ParallelPlate::apply(const size_t &i, const double &t, Vector_t &E, Vector_t &B) {
+    return applyToReferenceParticle(RefPartBunch_m->R[i], RefPartBunch_m->P[i], t, E, B);
 }
 
+bool ParallelPlate::apply(const Vector_t &R, const Vector_t &P, const double &t, Vector_t &E, Vector_t &B) {
+    return applyToReferenceParticle(R, P, t, E, B);
+}
 
-bool ParallelPlate::apply(const size_t &i, const double &t, Vector_t &E, Vector_t &B) {
+bool ParallelPlate::applyToReferenceParticle(const Vector_t &R, const Vector_t &P, const double &t, Vector_t &E, Vector_t &B) {
     const double phase = frequency_m * t + phase_m;
     Vector_t tmpE(0.0, 0.0, -1.0), tmpB(0.0, 0.0, 0.0);
-    if (ptime_m!=t) {
-        ptime_m=t;
-        //cout<<"time: "<<ptime_m<<" phase: "<<phase<<" E: "<<scale_m/length_m * sin(phase) * tmpE<<endl;
-
-    }
-    const Vector_t tmpR(RefPartBunch_m->getX(i) - dx_m, RefPartBunch_m->getY(i) - dy_m , RefPartBunch_m->getZ(i) - startField_m - ds_m);
+    ptime_m = t;
 
     //Here we don't check if the particle is outof bounds, just leave the matter to the particle Boundary collision model in BoundaryGeometry
-    if( (tmpR(2)>=startField_m-0.00001)
-        && (tmpR(2)<=endField_m+0.00001) ) {
-        E += scale_m/length_m * sin(phase) * tmpE; //Here scale_m should be Voltage between the parallel plates(V).
+    if ((R(2) >= 0.0)
+        && (R(2) < length_m)) {
+        E += scale_m / length_m * sin(phase) * tmpE; //Here scale_m should be Voltage between the parallel plates(V).
         B = tmpB;       //B field is always zero for our parallel plate elements used for benchmarking.
         return false;
     }
     return true;
 }
 
-bool ParallelPlate::apply(const Vector_t &R, const Vector_t &centroid, const double &t, Vector_t &E, Vector_t &B) {
-    const double phase = frequency_m * t + phase_m;
-    Vector_t  tmpE(0.0, 0.0, -1.0), tmpB(0.0, 0.0, 0.0);
-    if (ptime_m!=t) {
-        ptime_m=t;
-        //cout<<"time: "<<ptime_m<<" phase: "<<phase<<" E: "<<scale_m/length_m * sin(phase) * tmpE<<endl;
+void ParallelPlate::initialise(PartBunch *bunch, double &startField, double &endField) {
 
-    }
-    const Vector_t tmpR(R(0) - dx_m, R(1) - dy_m, R(2) - startField_m - ds_m);// Fixme: check this.
-
-
-    //if(!fieldmap_m->getFieldstrength(tmpR, tmpE, tmpB)) {
-    if( (tmpR(2)>=startField_m-0.00001)
-        && (tmpR(2)<=endField_m+0.00001) ) {
-        E += scale_m/length_m * sin(phase) * tmpE;
-        B = tmpB;
-        return false;
-    }
-    return true;
-}
-
-void ParallelPlate::initialise(PartBunch *bunch, double &startField, double &endField, const double &scaleFactor) {
-
-    Inform msg("PARALLELPLATE");
-    std::stringstream errormsg;
+    length_m = getElementLength();
     RefPartBunch_m = bunch;
-    startField_m = ElementEdge_m = startField;
-    //cout<<"Lenth_m in initialise: "<<length_m<<endl;
-    endField_m = endField = ElementEdge_m + length_m;//fixme:Has length_m already been initialised before?
+    startField = 0.0;
+
+    endField = length_m;
 
 }
 
 // In current version ,not implemented yet.
-void ParallelPlate::initialise(PartBunch *bunch, const double &scaleFactor) {
+void ParallelPlate::initialise(PartBunch *bunch) {
     using Physics::pi;
 
     Inform msg("ParallelPlate initialization for cyclotron tracker ");
@@ -216,8 +171,8 @@ bool ParallelPlate::bends() const {
 }
 
 void ParallelPlate::getDimensions(double &zBegin, double &zEnd) const {
-    zBegin = startField_m;
-    zEnd = endField_m;
+    zBegin = 0.0;
+    zEnd = length_m;
 }
 
 
diff --git a/src/Classic/AbsBeamline/ParallelPlate.h b/src/Classic/AbsBeamline/ParallelPlate.h
index baddf7590609c85e87da447788dcca12cf3fc287..a8bdaeeba91cf15a548d0f2a1c075c41a603f422 100644
--- a/src/Classic/AbsBeamline/ParallelPlate.h
+++ b/src/Classic/AbsBeamline/ParallelPlate.h
@@ -25,7 +25,6 @@
 #include "AbsBeamline/Component.h"
 
 class PartBunch;
-class Fieldmap;
 
 // Class ParallelPlate
 // ------------------------------------------------------------------------
@@ -65,18 +64,18 @@ public:
     void setPhase(double phase);
     double getPhase() const ;
 
-    void setElementLength(double length);
-    double getElementLength() const;
-
-    virtual bool apply(const size_t &i, const double &t, double E[], double B[]);
+    // void setElementLength(double length);
+    // double getElementLength() const;
 
     virtual bool apply(const size_t &i, const double &t, Vector_t &E, Vector_t &B);
 
-    virtual bool apply(const Vector_t &R, const Vector_t &centroid, const double &t, Vector_t &E, Vector_t &B);
+    virtual bool apply(const Vector_t &R, const Vector_t &P, const double &t, Vector_t &E, Vector_t &B);
+
+    virtual bool applyToReferenceParticle(const Vector_t &R, const Vector_t &P, const double &t, Vector_t &E, Vector_t &B);
 
-    virtual void initialise(PartBunch *bunch, double &startField, double &endField, const double &scaleFactor);
+    virtual void initialise(PartBunch *bunch, double &startField, double &endField);
 
-    virtual void initialise(PartBunch *bunch, const double &scaleFactor);
+    virtual void initialise(PartBunch *bunch);
 
     virtual void finalise();
 
@@ -90,9 +89,6 @@ private:
     double phase_m;              /**< phase shift of time varying field(degrees)*/
     double frequency_m;          /**< Read in frequency of time varying field(MHz)*/
     double length_m;             /**< Read in distance/length of Parallel Plate*/
-    double startField_m;
-    double endField_m;
-    double ElementEdge_m;
     double ptime_m;
 
     // Not implemented.
diff --git a/src/Classic/AbsBeamline/Patch.cpp b/src/Classic/AbsBeamline/Patch.cpp
index 945f3f5f819210bddb42fa9cf02396aebbb41094..2a27d6245dba893dbbdafb937ee56c73228cba3e 100644
--- a/src/Classic/AbsBeamline/Patch.cpp
+++ b/src/Classic/AbsBeamline/Patch.cpp
@@ -48,19 +48,7 @@ void Patch::accept(BeamlineVisitor &visitor) const {
     visitor.visitPatch(*this);
 }
 
-bool Patch::apply(const size_t &i, const double &t, double E[], double B[]) {
-    return false;
-}
-
-bool Patch::apply(const size_t &i, const double &t, Vector_t &E, Vector_t &B) {
-    return false;
-}
-
-bool Patch::apply(const Vector_t &R, const Vector_t &centroid, const double &t, Vector_t &E, Vector_t &B) {
-    return false;
-}
-
-void Patch::initialise(PartBunch *bunch, double &startField, double &endField, const double &scaleFactor) {
+void Patch::initialise(PartBunch *bunch, double &startField, double &endField) {
     RefPartBunch_m = bunch;
 }
 
@@ -78,5 +66,4 @@ void Patch::getDimensions(double &zBegin, double &zEnd) const {
 
 ElementBase::ElementType Patch::getType() const {
     return PATCH;
-}
-
+}
\ No newline at end of file
diff --git a/src/Classic/AbsBeamline/Patch.h b/src/Classic/AbsBeamline/Patch.h
index e3e22c04340aa18561e50e48c2b3b577571e718f..61ea410c1ddd92f4fc68e351f2988baa22c0b64d 100644
--- a/src/Classic/AbsBeamline/Patch.h
+++ b/src/Classic/AbsBeamline/Patch.h
@@ -48,13 +48,7 @@ public:
     /// Get patch transform.
     virtual const Euclid3D &getPatch() const = 0;
 
-    virtual bool apply(const size_t &i, const double &t, double E[], double B[]);
-
-    virtual bool apply(const size_t &i, const double &t, Vector_t &E, Vector_t &B);
-
-    virtual bool apply(const Vector_t &R, const Vector_t &centroid, const double &t, Vector_t &E, Vector_t &B);
-
-    virtual void initialise(PartBunch *bunch, double &startField, double &endField, const double &scaleFactor);
+    virtual void initialise(PartBunch *bunch, double &startField, double &endField);
 
     virtual void finalise();
 
@@ -70,4 +64,4 @@ private:
     void operator=(const Patch &);
 };
 
-#endif // CLASSIC_Patch_HH
+#endif // CLASSIC_Patch_HH
\ No newline at end of file
diff --git a/src/Classic/AbsBeamline/Probe.cpp b/src/Classic/AbsBeamline/Probe.cpp
index 3623994550945b055ea5d7300e4b17eebace922e..fd7741fbaac60b66b3b4c685471c1c40e0375303 100644
--- a/src/Classic/AbsBeamline/Probe.cpp
+++ b/src/Classic/AbsBeamline/Probe.cpp
@@ -94,26 +94,13 @@ void Probe::accept(BeamlineVisitor &visitor) const {
     visitor.visitProbe(*this);
 }
 
-bool Probe::apply(const size_t &i, const double &t, double E[], double B[]) {
-    Vector_t Ev(0, 0, 0), Bv(0, 0, 0);
-    return apply(i, t, Ev, Bv);
-}
-
-bool Probe::apply(const size_t &i, const double &t, Vector_t &E, Vector_t &B) {
-    return false;
-}
-
-bool Probe::apply(const Vector_t &R, const Vector_t &centroid, const double &t, Vector_t &E, Vector_t &B) {
-    return false;
-}
-
-void Probe::initialise(PartBunch *bunch, double &startField, double &endField, const double &scaleFactor) {
+void Probe::initialise(PartBunch *bunch, double &startField, double &endField) {
     position_m = startField;
     startField -= 0.005;
     endField = position_m + 0.005;
 }
 
-void Probe::initialise(PartBunch *bunch, const double &scaleFactor) {
+void Probe::initialise(PartBunch *bunch) {
     *gmsg << "* Initialize probe" << endl;
     if (filename_m == std::string(""))
         lossDs_m = std::unique_ptr<LossDataSink>(new LossDataSink(getName(), !Options::asciidump));
@@ -309,4 +296,4 @@ void Probe::getDimensions(double &zBegin, double &zEnd) const {
 
 ElementBase::ElementType Probe::getType() const {
     return PROBE;
-}
+}
\ No newline at end of file
diff --git a/src/Classic/AbsBeamline/Probe.h b/src/Classic/AbsBeamline/Probe.h
index 01cb0284fe6b27c7f983a495340d3ff0e5a3b2a5..69054af5e610b8a813a52a898caa4c4f1d30a6ae 100644
--- a/src/Classic/AbsBeamline/Probe.h
+++ b/src/Classic/AbsBeamline/Probe.h
@@ -45,14 +45,8 @@ public:
     /// Apply visitor to Probe.
     virtual void accept(BeamlineVisitor &) const;
 
-    virtual bool apply(const size_t &i, const double &t, double E[], double B[]);
-
-    virtual bool apply(const size_t &i, const double &t, Vector_t &E, Vector_t &B);
-
-    virtual bool apply(const Vector_t &R, const Vector_t &centroid, const double &t, Vector_t &E, Vector_t &B);
-
-    virtual void initialise(PartBunch *bunch, double &startField, double &endField, const double &scaleFactor);
-    virtual void initialise(PartBunch *bunch, const double &scaleFactor);
+    virtual void initialise(PartBunch *bunch, double &startField, double &endField);
+    virtual void initialise(PartBunch *bunch);
 
     virtual void finalise();
 
diff --git a/src/Classic/AbsBeamline/RBend.cpp b/src/Classic/AbsBeamline/RBend.cpp
index 1f366524212d96dc9a0d5839111b95217889db0e..ce61add4fc13d78598b20440018ac3b77a95329a 100644
--- a/src/Classic/AbsBeamline/RBend.cpp
+++ b/src/Classic/AbsBeamline/RBend.cpp
@@ -87,8 +87,8 @@ void RBend::addKR(int i, double t, Vector_t &K) {
     Vector_t tmpB(0.0, 0.0, 0.0);
     Vector_t tmpE_diff(0.0, 0.0, 0.0);
     Vector_t tmpB_diff(0.0, 0.0, 0.0);
-    double pz = RefPartBunch_m->getZ(i) - getStartField() - ds_m;
-    const Vector_t tmpA(RefPartBunch_m->getX(i) - dx_m, RefPartBunch_m->getY(i) - dy_m, pz);
+    double pz = RefPartBunch_m->getZ(i) - getStartField();
+    const Vector_t tmpA(RefPartBunch_m->getX(i), RefPartBunch_m->getY(i), pz);
 
     DiffDirection zdir(DZ);
     getFieldmap()->getFieldstrength(tmpA, tmpE, tmpB);
@@ -107,8 +107,8 @@ void RBend::addKT(int i, double t, Vector_t &K) {
 
     Vector_t tmpE(0.0, 0.0, 0.0);
     Vector_t tmpB(0.0, 0.0, 0.0);
-    double pz = RefPartBunch_m->getZ(i) - getStartField() - ds_m;
-    const Vector_t tmpA(RefPartBunch_m->getX(i) - dx_m, RefPartBunch_m->getY(i) - dy_m, pz);
+    double pz = RefPartBunch_m->getZ(i) - getStartField();
+    const Vector_t tmpA(RefPartBunch_m->getX(i), RefPartBunch_m->getY(i), pz);
     getFieldmap()->getFieldstrength(tmpA, tmpE, tmpB);
 
     double b = RefPartBunch_m->getBeta(i);
@@ -135,44 +135,25 @@ ElementBase::ElementType RBend::getType() const {
     return RBEND;
 }
 
-void RBend::SetBendAngle(double angle) {
-    getAngle() = angle;
-    getExitAngle() = std::abs(angle) - getEntranceAngle();
+void RBend::setBendAngle(double angle) {
+    Bend::setBendAngle(angle);
+    setExitAngle(angle - getEntranceAngle());
 }
 
-void RBend::SetEntranceAngle(double entranceAngle) {
-    getEntranceAngle() = entranceAngle;
-    getExitAngle() = std::abs(getAngle()) - entranceAngle;
+void RBend::setEntranceAngle(double entranceAngle) {
+    Bend::setEntranceAngle(entranceAngle);
+    setExitAngle(getBendAngle() - entranceAngle);
 }
 
-bool RBend::FindChordLength(Inform &msg,
-                            double &chordLength,
-                            bool &chordLengthFromMap) {
+bool RBend::findChordLength(Inform &msg,
+                            double &chordLength) {
 
     /*
      * Find bend chord length. If this was not set by the user using the
      * L (length) attribute, infer it from the field map.
      */
-    chordLength = 2 * getLength() * sin(0.5 * std::abs(getAngle())) /
-        (sin(getEntranceAngle()) + sin(std::abs(getAngle()) - getEntranceAngle()));
-    if(chordLength > 0.0) {
-        chordLengthFromMap = false;
-        return true;
-    } else {
-
-        if(chordLength == 0.0) {
-            double length = getMapLength();
-            chordLength = 2 * length * sin(0.5 * getAngle()) /
-                (sin(getEntranceAngle()) + sin(getAngle() - getEntranceAngle()));
-        }
-        chordLengthFromMap = true;
-
-        if(chordLength <= 0.0) {
-            ERRORMSG(level2 << "Magnet length inferred from field map is less than or equal"
-                     << " to zero. Check your bend magnet input." << endl);
-            return false;
-        } else
-            return true;
+    chordLength = std::abs(2 * getLength() * sin(0.5 * getBendAngle()) /
+                           (sin(getEntranceAngle()) + sin(getBendAngle() - getEntranceAngle())));
 
-    }
-}
\ No newline at end of file
+    return true;
+}
diff --git a/src/Classic/AbsBeamline/RBend.h b/src/Classic/AbsBeamline/RBend.h
index 3e47ebee54821cda19e7c7e7ed97c27a109ccbde..dc91e71d3f2c177ab96af412c7ec08c86c1baaab 100644
--- a/src/Classic/AbsBeamline/RBend.h
+++ b/src/Classic/AbsBeamline/RBend.h
@@ -172,17 +172,16 @@ public:
      */
 
     virtual ElementBase::ElementType getType() const;
-    virtual void SetBendAngle(double angle);
-    virtual void SetEntranceAngle(double entranceAngle);
+    virtual void setBendAngle(double angle);
+    virtual void setEntranceAngle(double entranceAngle);
 
 private:
 
     // Not implemented.
     void operator=(const RBend &);
 
-    virtual bool FindChordLength(Inform &msg,
-                                 double &chordLength,
-                                 bool &chordLengthFromMap);
+    virtual bool findChordLength(Inform &msg,
+                                 double &chordLength);
 };
 
 #endif // CLASSIC_RBend_HH
\ No newline at end of file
diff --git a/src/Classic/AbsBeamline/RFCavity.cpp b/src/Classic/AbsBeamline/RFCavity.cpp
index 26e4bc0ad8331c36f07c0ed49dd304e4d98f9716..1dea866cbc062e5562c5ef1f670cd0bca04edc72 100644
--- a/src/Classic/AbsBeamline/RFCavity.cpp
+++ b/src/Classic/AbsBeamline/RFCavity.cpp
@@ -21,14 +21,15 @@
 #include "AbsBeamline/RFCavity.h"
 #include "AbsBeamline/BeamlineVisitor.h"
 #include "Algorithms/PartBunch.h"
+#include "Algorithms/PartPusher.h"
 #include "Fields/Fieldmap.h"
 #include "Utilities/GeneralClassicException.h"
+#include "Utilities/Util.h"
 
 #include "gsl/gsl_interp.h"
-#include "gsl/gsl_spline.h"
+//#include "gsl/gsl_spline.h"
 #include <iostream>
 #include <fstream>
-
 #ifdef OPAL_NOCPLUSPLUS11_NULLPTR
 #define nullptr NULL
 #endif
@@ -44,11 +45,13 @@ RFCavity::RFCavity():
     Component(),
     filename_m(""),
     scale_m(1.0),
+    scaleError_m(0.0),
     phase_m(0.0),
+    phaseError_m(0.0),
     frequency_m(0.0),
-    ElementEdge_m(0.0),
     startField_m(0.0),
     endField_m(0.0),
+    length_m(0.0),
     type_m(SW),
     fast_m(false),
     autophaseVeto_m(false),
@@ -60,6 +63,7 @@ RFCavity::RFCavity():
     pdis_m(0.0),
     gapwidth_m(0.0),
     phi0_m(0.0),
+    designEnergy_m(-1.0),
     RNormal_m(nullptr),
     VrNormal_m(nullptr),
     DvDr_m(nullptr),
@@ -79,11 +83,13 @@ RFCavity::RFCavity(const RFCavity &right):
     Component(right),
     filename_m(right.filename_m),
     scale_m(right.scale_m),
+    scaleError_m(right.scaleError_m),
     phase_m(right.phase_m),
+    phaseError_m(right.phaseError_m),
     frequency_m(right.frequency_m),
-    ElementEdge_m(right.ElementEdge_m),
     startField_m(right.startField_m),
     endField_m(right.endField_m),
+    length_m(right.length_m),
     type_m(right.type_m),
     fast_m(right.fast_m),
     autophaseVeto_m(right.autophaseVeto_m),
@@ -95,6 +101,7 @@ RFCavity::RFCavity(const RFCavity &right):
     pdis_m(right.pdis_m),
     gapwidth_m(right.gapwidth_m),
     phi0_m(right.phi0_m),
+    designEnergy_m(right.designEnergy_m),
     RNormal_m(nullptr),
     VrNormal_m(nullptr),
     DvDr_m(nullptr),
@@ -104,30 +111,9 @@ RFCavity::RFCavity(const RFCavity &right):
     frequency_td_m(right.frequency_td_m),
     phase_name_m(right.phase_name_m),
     amplitude_name_m(right.amplitude_name_m),
-    frequency_name_m(right.frequency_name_m) {
-
+    frequency_name_m(right.frequency_name_m)
+{
     setElType(isRF);
-
-    std::vector<string>::const_iterator fname_it;
-    for(fname_it = right.multiFilenames_m.begin(); fname_it != right.multiFilenames_m.end(); ++ fname_it) {
-        multiFilenames_m.push_back(*fname_it);
-    }
-    std::vector<Fieldmap *>::const_iterator fmap_it;
-    for(fmap_it = right.multiFieldmaps_m.begin(); fmap_it != right.multiFieldmaps_m.end(); ++ fmap_it) {
-        multiFieldmaps_m.push_back(*fmap_it);
-    }
-    std::vector<double>::const_iterator scale_it;
-    for(scale_it = right.multiScales_m.begin(); scale_it != right.multiScales_m.end(); ++ scale_it) {
-        multiScales_m.push_back(*scale_it);
-    }
-    std::vector<double>::const_iterator phase_it;
-    for(phase_it = right.multiPhases_m.begin(); phase_it != right.multiPhases_m.end(); ++ phase_it) {
-        multiPhases_m.push_back(*phase_it);
-    }
-    std::vector<double>::const_iterator freq_it;
-    for(freq_it = right.multiFrequencies_m.begin(); freq_it != right.multiFrequencies_m.end(); ++ freq_it) {
-        multiFrequencies_m.push_back(*freq_it);
-    }
 }
 
 
@@ -135,11 +121,13 @@ RFCavity::RFCavity(const std::string &name):
     Component(name),
     filename_m(""),
     scale_m(1.0),
+    scaleError_m(0.0),
     phase_m(0.0),
+    phaseError_m(0.0),
     frequency_m(0.0),
-    ElementEdge_m(0.0),
     startField_m(0.0),
     endField_m(0.0),
+    length_m(0.0),
     type_m(SW),
     fast_m(false),
     autophaseVeto_m(false),
@@ -151,16 +139,18 @@ RFCavity::RFCavity(const std::string &name):
     pdis_m(0.0),
     gapwidth_m(0.0),
     phi0_m(0.0),
+    designEnergy_m(-1.0),
     RNormal_m(nullptr),
     VrNormal_m(nullptr),
     DvDr_m(nullptr),
-    phase_td_m(nullptr),
-    amplitude_td_m(nullptr),
-    frequency_td_m(nullptr),
     //     RNormal_m(std::nullptr_t(NULL)),
     //     VrNormal_m(std::nullptr_t(NULL)),
     //     DvDr_m(std::nullptr_t(NULL)),
-    num_points_m(0) {
+    num_points_m(0),
+    phase_td_m(nullptr),
+    amplitude_td_m(nullptr),
+    frequency_td_m(nullptr)
+{
     setElType(isRF);
 }
 
@@ -175,126 +165,10 @@ RFCavity::~RFCavity() {
     //~ }
 }
 
-
-void RFCavity::setAmplitudeModel(std::shared_ptr<AbstractTimeDependence> amplitude_td) {
-  amplitude_td_m = amplitude_td;
-}
-
-void RFCavity::setPhaseModel(std::shared_ptr<AbstractTimeDependence> phase_td) {
-  phase_td_m = phase_td;
-}
-
-void RFCavity::setFrequencyModel(std::shared_ptr<AbstractTimeDependence> frequency_td) {
-  frequency_td_m = frequency_td;
-}
-
-
-void RFCavity::setFrequencyModelName(std::string name) {
-  frequency_name_m=name;
-}
-
-
-
-
 void RFCavity::accept(BeamlineVisitor &visitor) const {
     visitor.visitRFCavity(*this);
 }
 
-void RFCavity::dropFieldmaps() {
-    std::vector<Fieldmap *>::iterator fmap_it;
-    for(fmap_it = multiFieldmaps_m.begin(); fmap_it != multiFieldmaps_m.end(); ++ fmap_it) {
-        *fmap_it = NULL;
-    }
-    multiFilenames_m.clear();
-    multiFieldmaps_m.clear();
-    multiScales_m.clear();
-    multiPhases_m.clear();
-    multiFrequencies_m.clear();
-}
-
-void RFCavity::setFieldMapFN(std::string fn) {
-    multiFilenames_m.push_back(fn);
-    filename_m = multiFilenames_m[0];
-}
-
-string RFCavity::getFieldMapFN() const {
-    std::string filename("No_fieldmap");
-    if(numFieldmaps() > 0) {
-        filename = multiFilenames_m[0];
-    }
-    return filename;
-}
-
-void RFCavity::setAmplitudem(double vPeak) {
-    multiScales_m.push_back(vPeak);
-    scale_m = multiScales_m[0];
-}
-
-void RFCavity::setFrequency(double freq) {
-    frequency_m = freq;
-}
-
-void RFCavity::setFrequencym(double freq) {
-    multiFrequencies_m.push_back(freq);
-    frequency_m = multiFrequencies_m[0];
-}
-
-
-double RFCavity::getFrequencym() const {
-    return frequency_m;
-}
-
-void RFCavity::setPhasem(double phase) {
-    multiPhases_m.push_back(phase);
-    phase_m = multiPhases_m[0];
-}
-
-void RFCavity::updatePhasem(double phase) {
-    if(multiPhases_m.size() == 0) {
-        multiPhases_m.push_back(phase);
-    } else {
-        double diff = phase - multiPhases_m[0];
-        multiPhases_m[0] = phase;
-        for(size_t i = 1; i < numFieldmaps(); ++ i) {
-            multiPhases_m[i] += diff;
-        }
-    }
-    phase_m = multiPhases_m[0];
-}
-
-double RFCavity::getPhasem() const {
-    return phase_m;
-}
-
-void RFCavity::setCavityType(std::string type) {
-
-}
-
-string RFCavity::getCavityType() const {
-    return "SW";
-}
-
-void RFCavity::setFast(bool fast) {
-    fast_m = fast;
-}
-
-
-bool RFCavity::getFast() const {
-    return fast_m;
-}
-
-
-
-void RFCavity::setAutophaseVeto(bool veto) {
-    autophaseVeto_m = veto;
-}
-
-
-bool RFCavity::getAutophaseVeto() const {
-    return autophaseVeto_m;
-}
-
-
 /**
  * ENVELOPE COMPONENT for radial focussing of the beam
  * Calculates the transverse envelope component for the RF cavity
@@ -302,27 +176,20 @@ bool RFCavity::getAutophaseVeto() const {
 */
 void RFCavity::addKR(int i, double t, Vector_t &K) {
 
-    double pz = RefPartBunch_m->getZ(i) - startField_m - ds_m;
-    const Vector_t tmpR(RefPartBunch_m->getX(i) - dx_m, RefPartBunch_m->getY(i) - dy_m, pz);
+    double pz = RefPartBunch_m->getZ(i) - startField_m;
+    const Vector_t tmpR(RefPartBunch_m->getX(i), RefPartBunch_m->getY(i), pz);
     double k = -Physics::q_e / (2.0 * RefPartBunch_m->getGamma(i) * Physics::EMASS);
 
-    for(size_t j = 0; j < numFieldmaps(); ++ j) {
-        Fieldmap *fieldmap = multiFieldmaps_m[j];
-        double frequency = multiFrequencies_m[j];
-        double scale = multiScales_m[j];
-        double phase = multiPhases_m[j];
+    Vector_t tmpE(0.0, 0.0, 0.0), tmpB(0.0, 0.0, 0.0);
+    fieldmap_m->getFieldstrength(tmpR, tmpE, tmpB);
+    double Ez = tmpE(2);
 
-        Vector_t tmpE(0.0, 0.0, 0.0), tmpB(0.0, 0.0, 0.0);
-        fieldmap->getFieldstrength(tmpR, tmpE, tmpB);
-        double Ez = tmpE(2);
-
-        tmpE = Vector_t(0.0);
-        fieldmap->getFieldDerivative(tmpR, tmpE, tmpB, DZ);
+    tmpE = Vector_t(0.0);
+    fieldmap_m->getFieldDerivative(tmpR, tmpE, tmpB, DZ);
 
-        double wtf = frequency * t + phase;
-        double kj = k * scale * (tmpE(2) * cos(wtf) - RefPartBunch_m->getBeta(i) * frequency * Ez * sin(wtf) / Physics::c);
-        K += Vector_t(kj, kj, 0.0);
-    }
+    double wtf = frequency_m * t + phase_m;
+    double kj = k * scale_m * (tmpE(2) * cos(wtf) - RefPartBunch_m->getBeta(i) * frequency_m * Ez * sin(wtf) / Physics::c);
+    K += Vector_t(kj, kj, 0.0);
 }
 
 
@@ -340,27 +207,20 @@ void RFCavity::addKT(int i, double t, Vector_t &K) {
     bool cxy = false; // default
     double kx = 0.0, ky = 0.0;
     if(cxy) {
-        for(size_t j = 0; j < numFieldmaps(); ++ j) {
-            Fieldmap *fieldmap = multiFieldmaps_m[j];
-            double scale = multiScales_m[j];
-            double frequency = multiFrequencies_m[j];
-            double phase = multiPhases_m[j];
-
-            double pz = RefPartBunch_m->getZ(i) - startField_m - ds_m;
-            const Vector_t tmpA(RefPartBunch_m->getX(i) - dx_m, RefPartBunch_m->getY(i) - dy_m, pz);
-
-            Vector_t tmpE(0.0, 0.0, 0.0), tmpB(0.0, 0.0, 0.0);
-            fieldmap->getFieldstrength(tmpA, tmpE, tmpB);
-
-            double cwtf = cos(frequency * t + phase);
-            double cf = -Physics::q_e / (RefPartBunch_m->getGamma(i) * Physics::m_e);
-            kx += -cf * scale * tmpE(0) * cwtf;
-            ky += -cf * scale * tmpE(1) * cwtf;
-        }
+        double pz = RefPartBunch_m->getZ(i) - startField_m;
+        const Vector_t tmpA(RefPartBunch_m->getX(i), RefPartBunch_m->getY(i), pz);
+
+        Vector_t tmpE(0.0, 0.0, 0.0), tmpB(0.0, 0.0, 0.0);
+        fieldmap_m->getFieldstrength(tmpA, tmpE, tmpB);
+
+        double cwtf = cos(frequency_m * t + phase_m);
+        double cf = -Physics::q_e / (RefPartBunch_m->getGamma(i) * Physics::m_e);
+        kx += -cf * scale_m * tmpE(0) * cwtf;
+        ky += -cf * scale_m * tmpE(1) * cwtf;
     }
 
-    double dx = RefPartBunch_m->getX0(i) - dx_m;
-    double dy = RefPartBunch_m->getY0(i) - dy_m;
+    double dx = RefPartBunch_m->getX0(i);
+    double dy = RefPartBunch_m->getY0(i);
 
     Vector_t KR(0.0, 0.0, 0.0);
     addKR(i, t, KR);
@@ -371,190 +231,97 @@ void RFCavity::addKT(int i, double t, Vector_t &K) {
 }
 
 
-bool RFCavity::apply(const size_t &i, const double &t, double E[], double B[]) {
-    Vector_t Ev(0, 0, 0), Bv(0, 0, 0);
-    Vector_t Rt(RefPartBunch_m->getX(i), RefPartBunch_m->getY(i), RefPartBunch_m->getZ(i));
+bool RFCavity::apply(const size_t &i, const double &t, Vector_t &E, Vector_t &B) {
+    return apply(RefPartBunch_m->R[i], RefPartBunch_m->P[i], t, E, B);
+}
 
-    if(apply(Rt, Vector_t(0.0), t, Ev, Bv)) return true;
+bool RFCavity::apply(const Vector_t &R,
+                     const Vector_t &P,
+                     const double &t,
+                     Vector_t &E,
+                     Vector_t &B) {
+    Vector_t tmpR(R(0), R(1), R(2) - startField_m);
+    Vector_t tmpE(0.0, 0.0, 0.0), tmpB(0.0, 0.0, 0.0);
 
-    E[0] = Ev(0);
-    E[1] = Ev(1);
-    E[2] = Ev(2);
-    B[0] = Bv(0);
-    B[1] = Bv(1);
-    B[2] = Bv(2);
+    if (tmpR(2) >= 0.0 &&
+        tmpR(2) < length_m) {
+        bool outOfBounds = fieldmap_m->getFieldstrength(tmpR, tmpE, tmpB);
+        if (outOfBounds) return true;
 
-    return false;
-}
+        E += (scale_m + scaleError_m) * cos(frequency_m * t + phase_m + phaseError_m) * tmpE;
+        B -= (scale_m + scaleError_m) * sin(frequency_m * t + phase_m + phaseError_m) * tmpB;
 
-bool RFCavity::apply(const size_t &i, const double &t, Vector_t &E, Vector_t &B) {
-    bool out_of_bounds = true;
-    const Vector_t tmpR(RefPartBunch_m->getX(i) - dx_m, RefPartBunch_m->getY(i) - dy_m , RefPartBunch_m->getZ(i) - startField_m - ds_m);
-
-    if (tmpR(2) >= 0.0) {
-        // inside the cavity
-        for(size_t j = 0; j < numFieldmaps(); ++ j) {
-            Fieldmap *fieldmap = multiFieldmaps_m[j];
-            Vector_t tmpE(0.0, 0.0, 0.0), tmpB(0.0, 0.0, 0.0);
-            const std::pair<double, double> & start_end = multi_start_end_field_m[j];
-
-            if(tmpR(2) > start_end.first &&
-               tmpR(2) < start_end.second &&
-               !fieldmap->getFieldstrength(tmpR, tmpE, tmpB)) {
-                const double phase = multiFrequencies_m[j] * t + multiPhases_m[j];
-                const double &scale = multiScales_m[j];
-                E += scale * cos(phase) * tmpE;
-                B -= scale * sin(phase) * tmpB;
-                out_of_bounds = false;
-            }
-        }
     }
-    else {
-        /*
-           some of the bunch is still outside of the cavity
-           so let them drift in
-        */
-        out_of_bounds = false;
-    }
-    return out_of_bounds;
+    return false;
 }
 
-bool RFCavity::apply(const Vector_t &R, const Vector_t &centroid, const double &t, Vector_t &E, Vector_t &B) {
-    bool out_of_bounds = true;
-    const Vector_t tmpR(R(0) - dx_m, R(1) - dy_m, R(2) - startField_m - ds_m);
+bool RFCavity::applyToReferenceParticle(const Vector_t &R,
+                                        const Vector_t &P,
+                                        const double &t,
+                                        Vector_t &E,
+                                        Vector_t &B) {
+
+    Vector_t tmpR(R(0), R(1), R(2) - startField_m);
+    Vector_t tmpE(0.0, 0.0, 0.0), tmpB(0.0, 0.0, 0.0);
+
+    if (tmpR(2) >= 0.0 &&
+        tmpR(2) < length_m) {
+        bool outOfBounds = fieldmap_m->getFieldstrength(tmpR, tmpE, tmpB);
+        if (outOfBounds) return true;
+
+        E += scale_m * cos(frequency_m * t + phase_m) * tmpE;
+        B -= scale_m * sin(frequency_m * t + phase_m) * tmpB;
 
-    for(size_t i = 0; i < numFieldmaps(); ++ i) {
-        Fieldmap *fieldmap = multiFieldmaps_m[i];
-        Vector_t tmpE(0.0, 0.0, 0.0), tmpB(0.0, 0.0, 0.0);
-        const std::pair<double, double> & start_end = multi_start_end_field_m[i];
-
-        if(tmpR(2) > start_end.first &&
-           tmpR(2) < start_end.second &&
-           !fieldmap->getFieldstrength(tmpR, tmpE, tmpB)) {
-            const double phase = multiFrequencies_m[i] * t + multiPhases_m[i];
-            const double &scale = multiScales_m[i];
-            E += scale * cos(phase) * tmpE;
-            B -= scale * sin(phase) * tmpB;
-            out_of_bounds = false;
-        }
     }
-    return out_of_bounds;
+    return false;
 }
 
-void RFCavity::initialise(PartBunch *bunch, double &startField, double &endField, const double &scaleFactor) {
+void RFCavity::initialise(PartBunch *bunch, double &startField, double &endField) {
     using Physics::two_pi;
-    double zBegin = 0.0, zEnd = 0.0, rBegin = 0.0, rEnd = 0.0;
+
+    if (bunch == NULL) {
+        startField = startField_m;
+        endField = endField_m;
+
+        return;
+    }
+
+    double rBegin = 0.0, rEnd = 0.0;
     Inform msg("RFCavity ", *gmsg);
     std::stringstream errormsg;
     RefPartBunch_m = bunch;
 
-    for(size_t i = 0; i < numFieldmaps(); ++ i) {
-        std::string fname = multiFilenames_m[i];
-        Fieldmap *fmap = Fieldmap::getFieldmap(fname, fast_m);
-        if(fmap != NULL) {
-            multiFieldmaps_m.push_back(fmap);
-        } else {
-            for(size_t j = i; j < numFieldmaps() - 1; ++ j) {
-                multiFieldmaps_m[j] = multiFieldmaps_m[j + 1];
-            }
-            multiFieldmaps_m.pop_back();
-            -- i;
-        }
-    }
-    if(multiScales_m.size() > 0) {
-        while(multiScales_m.size() < numFieldmaps()) {
-            multiScales_m.push_back(multiScales_m[0]);
-        }
-    } else {
-        while(multiScales_m.size() < numFieldmaps()) {
-            multiScales_m.push_back(1.0);
-        }
-    }
-    if(multiFrequencies_m.size() > 0) {
-        while(multiFrequencies_m.size() < numFieldmaps()) {
-            multiFrequencies_m.push_back(multiFrequencies_m[0]);
-        }
-    } else {
-        while(multiFrequencies_m.size() < numFieldmaps()) {
-            multiFrequencies_m.push_back(0.0);
-        }
-    }
-    if(multiPhases_m.size() > 0) {
-        while(multiPhases_m.size() < numFieldmaps()) {
-            multiPhases_m.push_back(multiPhases_m[0]);
-        }
-    } else {
-        while(multiPhases_m.size() < multiFilenames_m.size()) {
-            multiPhases_m.push_back(0.0);
-        }
-    }
+    fieldmap_m = Fieldmap::getFieldmap(filename_m, fast_m);
 
-    if(numFieldmaps() > 0) {
-        double overall_zBegin = 999999999.99, overall_zEnd = -999999999.99;
-        for(size_t i = 0; i < numFieldmaps(); ++ i) {
-            Fieldmap *fmap = multiFieldmaps_m[i];
-            double &frequency = multiFrequencies_m[i];
-            const std::string &filename = multiFilenames_m[i];
-
-            fmap->getFieldDimensions(zBegin, zEnd, rBegin, rEnd);
-            if(zEnd > zBegin) {
-                msg << level2 << getName() << " using file ";
-                fmap->getInfo(&msg);
-                if(fabs((frequency - fmap->getFrequency()) / frequency) > 0.01) {
-                    errormsg << "FREQUENCY IN INPUT FILE DIFFERENT THAN IN FIELD MAP '" << filename << "';\n"
-                             << frequency / two_pi * 1e-6 << " MHz <> "
-                             << fmap->getFrequency() / two_pi * 1e-6 << " MHz; TAKE ON THE LATTER";
-                    std::string errormsg_str = Fieldmap::typeset_msg(errormsg.str(), "warning");
-                    ERRORMSG(errormsg_str << "\n" << endl);
-                    if(Ippl::myNode() == 0) {
-                        std::ofstream omsg("errormsg.txt", std::ios_base::app);
-                        omsg << errormsg_str << std::endl;
-                        omsg.close();
-                    }
-                    frequency = fmap->getFrequency();
-                }
-                multi_start_end_field_m.push_back(std::pair<double, double>(zBegin, zEnd));
-
-                overall_zBegin = std::min(overall_zBegin, zBegin);
-                overall_zEnd = std::max(overall_zEnd, zEnd);
-            } else {
-                for(size_t j = i; j < numFieldmaps() - 1; ++ j) {
-                    multiFilenames_m[j] = multiFilenames_m[j + 1];
-                    multiFieldmaps_m[j] = multiFieldmaps_m[j + 1];
-                    multiScales_m[j] = multiScales_m[j + 1];
-                    multiPhases_m[j] = multiPhases_m[j + 1];
-                    multiFrequencies_m[j] = multiFrequencies_m[j + 1];
-                }
-                multiFilenames_m.pop_back();
-                multiFieldmaps_m.back() = NULL;
-                multiFieldmaps_m.pop_back();
-                multiScales_m.pop_back();
-                multiPhases_m.pop_back();
-                multiFrequencies_m.pop_back();
-                -- i;
+    fieldmap_m->getFieldDimensions(startField_m, endField_m, rBegin, rEnd);
+    if(endField_m > startField_m) {
+        msg << level2 << getName() << " using file ";
+        fieldmap_m->getInfo(&msg);
+        if(std::abs((frequency_m - fieldmap_m->getFrequency()) / frequency_m) > 0.01) {
+            errormsg << "FREQUENCY IN INPUT FILE DIFFERENT THAN IN FIELD MAP '" << filename_m << "';\n"
+                     << frequency_m / two_pi * 1e-6 << " MHz <> "
+                     << fieldmap_m->getFrequency() / two_pi * 1e-6 << " MHz; TAKE ON THE LATTER";
+            std::string errormsg_str = Fieldmap::typeset_msg(errormsg.str(), "warning");
+            ERRORMSG(errormsg_str << "\n" << endl);
+            if(Ippl::myNode() == 0) {
+                std::ofstream omsg("errormsg.txt", std::ios_base::app);
+                omsg << errormsg_str << std::endl;
+                omsg.close();
             }
+            frequency_m = fieldmap_m->getFrequency();
         }
-        zBegin = overall_zBegin;
-        zEnd = overall_zEnd;
-        for(size_t i = 0; i < numFieldmaps(); ++ i) {
-            multi_start_end_field_m[i].first -= zBegin;
-            multi_start_end_field_m[i].second -= zBegin;
-        }
-    }
-
-    if(zEnd > zBegin) {
-        ElementEdge_m = startField;
-        startField_m = startField = ElementEdge_m + zBegin;
-        endField_m = endField = ElementEdge_m + zEnd;
+        length_m = endField_m - startField_m;
+        endField = startField + length_m;
     } else {
         endField = startField - 1e-3;
     }
 }
 
 // In current version ,this function reads in the cavity voltage profile data from file.
-void RFCavity::initialise(PartBunch *bunch, const double &scaleFactor, std::shared_ptr<AbstractTimeDependence> freq_atd,
-                          std::shared_ptr<AbstractTimeDependence> ampl_atd, std::shared_ptr<AbstractTimeDependence> phase_atd) {
-
+void RFCavity::initialise(PartBunch *bunch,
+                          std::shared_ptr<AbstractTimeDependence> freq_atd,
+                          std::shared_ptr<AbstractTimeDependence> ampl_atd,
+                          std::shared_ptr<AbstractTimeDependence> phase_atd) {
     using Physics::pi;
 
     RefPartBunch_m = bunch;
@@ -592,7 +359,7 @@ void RFCavity::initialise(PartBunch *bunch, const double &scaleFactor, std::shar
 
     if (frequency_name_m != "")
       *gmsg << "* Timedependent frequency model " << frequency_name_m << endl;
-    
+
     *gmsg << "* Cavity voltage data read successfully!" << endl;
 }
 
@@ -605,18 +372,14 @@ bool RFCavity::bends() const {
 
 
 void RFCavity::goOnline(const double &) {
-    std::vector<string>::iterator fmap_it;
-    for(fmap_it = multiFilenames_m.begin(); fmap_it != multiFilenames_m.end(); ++ fmap_it) {
-        Fieldmap::readMap(*fmap_it);
-    }
+    Fieldmap::readMap(filename_m);
+
     online_m = true;
 }
 
 void RFCavity::goOffline() {
-    std::vector<string>::iterator fmap_it;
-    for(fmap_it = multiFilenames_m.begin(); fmap_it != multiFilenames_m.end(); ++ fmap_it) {
-        Fieldmap::freeMap(*fmap_it);
-    }
+    Fieldmap::freeMap(filename_m);
+
     online_m = false;
 }
 
@@ -677,23 +440,23 @@ double RFCavity::getPhi0() const {
 }
 
 void RFCavity::setComponentType(std::string name) {
+    name = Util::toUpper(name);
     if(name == "STANDING") {
         type_m = SW;
     } else if(name == "SINGLEGAP") {
         type_m = SGSW;
-    } else {
-        if(name != "") {
-            std::stringstream errormsg;
-            errormsg << "CAVITY TYPE " << name << " DOES NOT EXIST; \n"
-                     << "CHANGING TO REGULAR STANDING WAVE";
-            std::string errormsg_str = Fieldmap::typeset_msg(errormsg.str(), "warning");
-            ERRORMSG(errormsg_str << "\n" << endl);
-            if(Ippl::myNode() == 0) {
-                ofstream omsg("errormsg.txt", ios_base::app);
-                omsg << errormsg_str << endl;
-                omsg.close();
-            }
+    } else if(name != "") {
+        std::stringstream errormsg;
+        errormsg << getName() << ": CAVITY TYPE " << name << " DOES NOT EXIST;";
+        std::string errormsg_str = Fieldmap::typeset_msg(errormsg.str(), "warning");
+        ERRORMSG(errormsg_str << "\n" << endl);
+        if(Ippl::myNode() == 0) {
+            ofstream omsg("errormsg.txt", ios_base::app);
+            omsg << errormsg_str << endl;
+            omsg.close();
         }
+        throw GeneralClassicException("RFCavity::setComponentType", errormsg_str);
+    } else {
         type_m = SW;
     }
 
@@ -710,12 +473,10 @@ double RFCavity::getCycFrequency()const {
     return  frequency_m;
 }
 
-
-
 /**
    \brief used in OPAL-cycl
 
-   Is called from OPAL-cycl and can handle 
+   Is called from OPAL-cycl and can handle
    time dependent frequency, amplitude and phase
 
    At the moment (test) only the frequence is time
@@ -740,18 +501,17 @@ void RFCavity::getMomentaKick(const double normalRadius, double momentum[], cons
     double transit_factor = 0.0;
     double Ufactor = 1.0;
 
-    double frequency_save = frequency_m;
-    frequency_m *= frequency_td_m->getValue(t);
+    double frequency = frequency_m * frequency_td_m->getValue(t);
 
     if(gapwidth_m > 0.0) {
-        transit_factor = 0.5 * frequency_m * gapwidth_m * 1.0e-3 / (c * beta);
+        transit_factor = 0.5 * frequency * gapwidth_m * 1.0e-3 / (c * beta);
         Ufactor = sin(transit_factor) / transit_factor;
     }
 
     Voltage *= Ufactor;
 
     double dgam = 0.0;
-    double nphase = (frequency_m * (t + dtCorrt) * 1.0e-9) - phi0_m / 180.0 * pi ; // rad/s, ns --> rad
+    double nphase = (frequency * (t + dtCorrt) * 1.0e-9) - phi0_m / 180.0 * pi ; // rad/s, ns --> rad
 
     dgam = Voltage * cos(nphase) / (restMass);
 
@@ -767,7 +527,7 @@ void RFCavity::getMomentaKick(const double normalRadius, double momentum[], cons
     double px = pr * cosAngle_m - ptheta * sinAngle_m ; // x
     double py = pr * sinAngle_m + ptheta * cosAngle_m; // y
 
-    double rotate = -derivate * (scale_m * 1.0e6) / ((rmax_m - rmin_m) / 1000.0) * sin(nphase) / (frequency_m * two_pi) / (betgam * restMass / c / chargenumber); // radian
+    double rotate = -derivate * (scale_m * 1.0e6) / ((rmax_m - rmin_m) / 1000.0) * sin(nphase) / (frequency * two_pi) / (betgam * restMass / c / chargenumber); // radian
 
     /// B field effects
     momentum[0] =  cos(rotate) * px + sin(rotate) * py;
@@ -778,7 +538,7 @@ void RFCavity::getMomentaKick(const double normalRadius, double momentum[], cons
             << " dE= " << dgam *restMass * 1.0e-6 << " [MeV]"
             << " E_kin= " << (gamma - 1.0)*restMass * 1.0e-6 << " [MeV] Time dep freq = " << frequency_td_m->getValue(t) << endl;
     }
-    frequency_m = frequency_save;
+
 }
 
 /* cubic spline subrutine */
@@ -854,173 +614,126 @@ ElementBase::ElementType RFCavity::getType() const {
 
 double RFCavity::getAutoPhaseEstimate(const double &E0, const double &t0, const double &q, const double &mass) {
     vector<double> t, E, t2, E2;
-    std::vector< std::vector< double > > F(numFieldmaps());
+    std::vector< double > F;
     std::vector< std::pair< double, double > > G;
-    std::vector< double > begin(numFieldmaps());
-    std::vector< double > end(numFieldmaps());
-    std::vector<gsl_spline *> onAxisInterpolants(numFieldmaps());
-    std::vector<gsl_interp_accel *> onAxisAccel(numFieldmaps());
+    gsl_spline *onAxisInterpolants;
+    gsl_interp_accel *onAxisAccel;
 
     unsigned int N;
     double A, B;
     double phi = 0.0, tmp_phi, dphi = 0.5 * Physics::pi / 180.;
-    double min_dz = 1.0, max_length = 0.0, min_begin = 99999999.99;
-    double max_frequency = 0.0;
-    for(size_t i = 0; i < numFieldmaps(); ++ i) {
-        multiFieldmaps_m[i]->getOnaxisEz(G);
-        begin[i] = (G.front()).first;
-        end[i] = (G.back()).first;
-        max_frequency = std::max(max_frequency, multiFrequencies_m[i]);
-        std::unique_ptr<double[]> zvals(new double[G.size()]);
-        std::unique_ptr<double[]> onAxisField(new double[G.size()]);
-
-        for(size_t j = 0; j < G.size(); ++ j) {
-            zvals[j] = G[j].first;
-            onAxisField[j] = G[j].second;
+    double dz = 1.0, length = 0.0;
+    fieldmap_m->getOnaxisEz(G);
+    double begin = (G.front()).first;
+    double end = (G.back()).first;
+    std::unique_ptr<double[]> zvals(new double[G.size()]);
+    std::unique_ptr<double[]> onAxisField(new double[G.size()]);
+
+    for(size_t j = 0; j < G.size(); ++ j) {
+        zvals[j] = G[j].first;
+        onAxisField[j] = G[j].second;
+    }
+    onAxisInterpolants = gsl_spline_alloc(gsl_interp_cspline, G.size());
+    onAxisAccel = gsl_interp_accel_alloc();
+    gsl_spline_init(onAxisInterpolants, zvals.get(), onAxisField.get(), G.size());
+
+    length = end - begin;
+    dz = length / G.size();
+
+    G.clear();
+
+    N = (int)floor(length / dz + 1);
+    dz = length / N;
+
+    F.resize(N);
+    double z = begin;
+    for(size_t j = 0; j < N; ++ j, z += dz) {
+        F[j] = gsl_spline_eval(onAxisInterpolants, z, onAxisAccel);
+    }
+    gsl_spline_free(onAxisInterpolants);
+    gsl_interp_accel_free(onAxisAccel);
+
+    t.resize(N, t0);
+    t2.resize(N, t0);
+    E.resize(N, E0);
+    E2.resize(N, E0);
+
+    z = begin + dz;
+    for(unsigned int i = 1; i < N; ++ i, z += dz) {
+        E[i] = E[i - 1] + dz * scale_m / mass;
+        E2[i] = E[i];
+    }
+
+    for(int iter = 0; iter < 10; ++ iter) {
+        A = B = 0.0;
+        for(unsigned int i = 1; i < N; ++ i) {
+            t[i] = t[i - 1] + getdT(i, E, dz, mass);
+            t2[i] = t2[i - 1] + getdT(i, E2, dz, mass);
+            A += scale_m * (1. + frequency_m * (t2[i] - t[i]) / dphi) * getdA(i, t, dz, frequency_m, F);
+            B += scale_m * (1. + frequency_m * (t2[i] - t[i]) / dphi) * getdB(i, t, dz, frequency_m, F);
         }
-        onAxisInterpolants[i] = gsl_spline_alloc(gsl_interp_cspline, G.size());
-        onAxisAccel[i] = gsl_interp_accel_alloc();
-        gsl_spline_init(onAxisInterpolants[i], zvals.get(), onAxisField.get(), G.size());
-
-        double length = end[i] - begin[i];
-        min_dz = std::min(min_dz, length / G.size());
-        max_length = std::max(max_length, length);
-        min_begin = std::min(min_begin, begin[i]);
-
-        G.clear();
-        //~ delete[] zvals;
-        //~ delete[] onAxisField;
-    }
 
-    N = (int)floor(max_length / min_dz + 1);
-    min_dz = max_length / N;
-
-    for(size_t i = 0; i < numFieldmaps(); ++ i) {
-        F[i].resize(N);
-        double z = min_begin;
-        for(size_t j = 0; j < N; ++ j, z += min_dz) {
-            if(z >= begin[i] && z <= end[i]) {
-                F[i][j] = gsl_spline_eval(onAxisInterpolants[i], z, onAxisAccel[i]);
-            } else {
-                F[i][j] = 0.0;
-            }
+        if(std::abs(B) > 0.0000001) {
+            tmp_phi = atan(A / B);
+        } else {
+            tmp_phi = Physics::pi / 2;
         }
-        gsl_spline_free(onAxisInterpolants[i]);
-        gsl_interp_accel_free(onAxisAccel[i]);
-    }
-
-    //~ delete[] onAxisInterpolants;
-    //~ delete[] onAxisAccel;
-
-    if(N > 0) {
-
-        t.resize(N, t0);
-        t2.resize(N, t0);
-        E.resize(N, E0);
-        E2.resize(N, E0);
-
-        double z = min_begin + min_dz;
-        for(unsigned int i = 1; i < N; ++ i, z += min_dz) {
-            E[i] = E[i - 1] + min_dz * scale_m / mass;
-            E2[i] = E[i];
+        if(q * (A * sin(tmp_phi) + B * cos(tmp_phi)) < 0) {
+            tmp_phi += Physics::pi;
         }
 
-        for(int iter = 0; iter < 10; ++ iter) {
-            A = B = 0.0;
+        if(std::abs(phi - tmp_phi) < frequency_m * (t[N - 1] - t[0]) / (10 * N)) {
             for(unsigned int i = 1; i < N; ++ i) {
-                t[i] = t[i - 1] + getdT(i, E, min_dz, mass);
-                t2[i] = t2[i - 1] + getdT(i, E2, min_dz, mass);
-                for(size_t j = 0; j < numFieldmaps(); ++ j) {
-                    const double &frequency = multiFrequencies_m[j];
-                    const double &scale = multiScales_m[j];
-                    const double Dphi = multiPhases_m[j] - multiPhases_m[0];
-                    A += scale * (1. + frequency * (t2[i] - t[i]) / dphi) * getdA(i, t, min_dz, Dphi, frequency, F[j]);
-                    B += scale * (1. + frequency * (t2[i] - t[i]) / dphi) * getdB(i, t, min_dz, Dphi, frequency, F[j]);
-                }
+                E[i] = E[i - 1];
+                E[i] += q * scale_m * getdE(i, t, dz, phi, frequency_m, F) ;
             }
+            const int prevPrecision = Ippl::Info->precision(8);
+            INFOMSG(level2 << "estimated phase= " << tmp_phi << " rad, "
+                    << "Ekin= " << E[N - 1] << " MeV" << setprecision(prevPrecision) << endl);
 
-            if(fabs(B) > 0.0000001) {
-                tmp_phi = atan(A / B);
-            } else {
-                tmp_phi = Physics::pi / 2;
-            }
-            if(q * (A * sin(tmp_phi) + B * cos(tmp_phi)) < 0) {
-                tmp_phi += Physics::pi;
-            }
+            return tmp_phi;
+        }
+        phi = tmp_phi - floor(tmp_phi / Physics::two_pi + 0.5) * Physics::two_pi;
 
-            if(fabs(phi - tmp_phi) < max_frequency * (t[N - 1] - t[0]) / (10 * N)) {
-                for(unsigned int i = 1; i < N; ++ i) {
-                    E[i] = E[i - 1];
-                    for(size_t j = 0; j < numFieldmaps(); ++ j) {
-                        const double &frequency = multiFrequencies_m[j];
-                        const double &scale = multiScales_m[j];
-                        const double Dphi = multiPhases_m[j] - multiPhases_m[0];
-                        E[i] += q * scale * getdE(i, t, min_dz, phi + Dphi, frequency, F[j]) ;
-                    }
-                }
-                const int prevPrecision = Ippl::Info->precision(8);
-                INFOMSG(level2 << "estimated phase= " << tmp_phi << " rad, "
-                        << "Ekin= " << E[N - 1] << " MeV" << setprecision(prevPrecision) << endl);
-
-                return tmp_phi;
-            }
-            phi = tmp_phi - floor(tmp_phi / Physics::two_pi + 0.5) * Physics::two_pi;
 
+        for(unsigned int i = 1; i < N; ++ i) {
+            E[i] = E[i - 1];
+            E2[i] = E2[i - 1];
+            E[i] += q * scale_m * getdE(i, t, dz, phi, frequency_m, F) ;
+            E2[i] += q * scale_m * getdE(i, t2, dz, phi + dphi, frequency_m, F);
 
-            for(unsigned int i = 1; i < N; ++ i) {
-                E[i] = E[i - 1];
-                E2[i] = E2[i - 1];
-                for(size_t j = 0; j < numFieldmaps(); ++ j) {
-                    const double &frequency = multiFrequencies_m[j];
-                    const double &scale = multiScales_m[j];
-                    const double Dphi = multiPhases_m[j] - multiPhases_m[0];
-                    E[i] += q * scale * getdE(i, t, min_dz, phi + Dphi, frequency, F[j]) ;
-                    E2[i] += q * scale * getdE(i, t2, min_dz, phi + dphi + Dphi, frequency, F[j]);
-                }
-                t[i] = t[i - 1] + getdT(i, E, min_dz, mass);
-                t2[i] = t2[i - 1] + getdT(i, E2, min_dz, mass);
+            t[i] = t[i - 1] + getdT(i, E, dz, mass);
+            t2[i] = t2[i - 1] + getdT(i, E2, dz, mass);
 
-                E[i] = E[i - 1];
-                E2[i] = E2[i - 1];
-                for(size_t j = 0; j < numFieldmaps(); ++ j) {
-                    const double &frequency = multiFrequencies_m[j];
-                    const double &scale = multiScales_m[j];
-                    const double Dphi = multiPhases_m[j] - multiPhases_m[0];
-                    E[i] += q * scale * getdE(i, t, min_dz, phi + Dphi, frequency, F[j]) ;
-                    E2[i] += q * scale * getdE(i, t2, min_dz, phi + dphi + Dphi, frequency, F[j]);
-                }
-            }
+            E[i] = E[i - 1];
+            E2[i] = E2[i - 1];
+            E[i] += q * scale_m * getdE(i, t, dz, phi, frequency_m, F) ;
+            E2[i] += q * scale_m * getdE(i, t2, dz, phi + dphi, frequency_m, F);
+        }
 
-            double totalEz0 = 0.0, cosine_part = 0.0, sine_part = 0.0;
-            double p0 = sqrt((E0 / mass + 1) * (E0 / mass + 1) - 1);
-            for(size_t j = 0; j < numFieldmaps(); ++ j) {
-                const double &frequency = multiFrequencies_m[j];
-                const double &scale = multiScales_m[j];
-                const double Dphi = multiPhases_m[j] - multiPhases_m[0];
-                cosine_part += scale * cos(frequency * t0 + Dphi) * F[j][0];
-                sine_part += scale * sin(frequency * t0 + Dphi) * F[j][0];
-            }
-            totalEz0 = cos(phi) * cosine_part - sin(phi) * sine_part;
-
-            if(p0 + q * totalEz0 * (t[1] - t[0]) * Physics::c / mass < 0) {
-                // make totalEz0 = 0
-                tmp_phi = atan(cosine_part / sine_part);
-                if(abs(tmp_phi - phi) > Physics::pi) {
-                    phi = tmp_phi + Physics::pi;
-                } else {
-                    phi = tmp_phi;
-                }
+        double totalEz0 = 0.0, cosine_part = 0.0, sine_part = 0.0;
+        double p0 = sqrt((E0 / mass + 1) * (E0 / mass + 1) - 1);
+        cosine_part += scale_m * cos(frequency_m * t0) * F[0];
+        sine_part += scale_m * sin(frequency_m * t0) * F[0];
+
+        totalEz0 = cos(phi) * cosine_part - sin(phi) * sine_part;
+
+        if(p0 + q * totalEz0 * (t[1] - t[0]) * Physics::c / mass < 0) {
+            // make totalEz0 = 0
+            tmp_phi = atan(cosine_part / sine_part);
+            if(abs(tmp_phi - phi) > Physics::pi) {
+                phi = tmp_phi + Physics::pi;
+            } else {
+                phi = tmp_phi;
             }
         }
+    }
 
-        const int prevPrecision = Ippl::Info->precision(8);
-        INFOMSG(level2 << "estimated phase= " << tmp_phi << " rad, "
-                << "Ekin= " << E[N - 1] << " MeV" << setprecision(prevPrecision) << endl);
+    const int prevPrecision = Ippl::Info->precision(8);
+    INFOMSG(level2 << "estimated phase= " << tmp_phi << " rad, "
+            << "Ekin= " << E[N - 1] << " MeV" << setprecision(prevPrecision) << endl);
 
-        return phi;
-    } else {
-        return 0.0;
-    }
+    return phi;
 }
 
 pair<double, double> RFCavity::trackOnAxisParticle(const double &p0,
@@ -1028,71 +741,45 @@ pair<double, double> RFCavity::trackOnAxisParticle(const double &p0,
         const double &dt,
         const double &q,
         const double &mass) {
-    double p = p0;
+    Vector_t p(0, 0, p0);
     double t = t0;
+    BorisPusher integrator(*RefPartBunch_m->getReference());
     double cdt = Physics::c * dt;
-    vector<pair<double, double> > F;
-    vector<size_t> length_fieldmaps(numFieldmaps());
-    for(size_t i = 0; i < numFieldmaps(); ++ i) {
-        vector<pair<double, double> > G;
-        multiFieldmaps_m[i]->getOnaxisEz(G);
-        length_fieldmaps[i] = G.size();
-        F.insert(F.end(), G.begin(), G.end());
-    }
+    double zbegin = startField_m;
+    double zend = length_m + startField_m;
 
-    std::unique_ptr<double[]> zvals(new double[F.size()]);
-    std::unique_ptr<double[]> onAxisField(new double[F.size()]);
-    for(unsigned int i = 0; i < F.size(); ++i) {
-        zvals[i] = F[i].first;
-        onAxisField[i] = F[i].second;
-    }
-    double zbegin = zvals[0];
-    double zend = zvals[F.size() - 1];
-    std::vector<std::pair<double, double> > begin_end(numFieldmaps());
-    std::vector<gsl_spline *> onAxisInterpolants(numFieldmaps());
-    std::vector<gsl_interp_accel *> onAxisAccel(numFieldmaps());
-    size_t start = 0;
-    for(size_t i = 0; i < numFieldmaps(); ++ i) {
-        begin_end[i].first = zvals[start];
-        onAxisInterpolants[i] = gsl_spline_alloc(gsl_interp_cspline, length_fieldmaps[i]);
-        onAxisAccel[i] = gsl_interp_accel_alloc();
-        gsl_spline_init(onAxisInterpolants[i], &(zvals[start]), &(onAxisField[start]), length_fieldmaps[i]);
-        start += length_fieldmaps[i];
-        begin_end[i].second = zvals[start - 1];
-
-        zbegin = std::min(zbegin, begin_end[i].first);
-        zend = std::max(zend, begin_end[i].second);
-    }
+    Vector_t z(0.0, 0.0, startField_m);
+    double dz = 0.5 * p(2) / sqrt(1.0 + dot(p, p)) * cdt;
+    Vector_t Ef(0.0), Bf(0.0);
 
-    //~ delete[] zvals;
-    //~ delete[] onAxisField;
-
-    double z = zbegin;
-    double dz = 0.5 * p / sqrt(1.0 + p * p) * cdt;
-    while(z + dz < zend && z + dz > zbegin) {
-        z += dz;
-        for(size_t i = 0; i < numFieldmaps(); ++ i) {
-            if(z >= begin_end[i].first && z <= begin_end[i].second) {
-                double phase = multiFrequencies_m[i] * t + multiPhases_m[i];
-                double scale = multiScales_m[i];
-                double ez = scale * gsl_spline_eval(onAxisInterpolants[i], z, onAxisAccel[i]);
-                p += cos(phase) * ez * q * cdt / mass;
-            }
+    while(z(2) + dz < zend && z(2) + dz > zbegin) {
+        z /= cdt;
+        integrator.push(z, p, dt);
+        z *= cdt;
+
+        if(z(2) >= zbegin && z(2) <= zend) {
+            Ef = 0.0;
+            applyToReferenceParticle(z, p, t + 0.5 * dt, Ef, Bf);
         }
-        dz = 0.5 * p / sqrt(1.0 + p * p) * cdt;
-        z += dz;
+        integrator.kick(z, p, Ef, Bf, dt);
+
+        dz = 0.5 * p(2) / sqrt(1.0 + dot(p, p)) * cdt;
+        z /= cdt;
+        integrator.push(z, p, dt);
+        z *= cdt;
         t += dt;
     }
 
-    for(size_t i = 0; i < numFieldmaps(); ++ i) {
-        gsl_spline_free(onAxisInterpolants[i]);
-        gsl_interp_accel_free(onAxisAccel[i]);
-    }
-    //~ delete[] onAxisInterpolants;
-    //~ delete[] onAxisAccel;
+    const double beta = sqrt(1. - 1 / (dot(p, p) + 1.));
+    const double tErr  = (z(2) - zend) / (Physics::c * beta);
 
-    const double beta = sqrt(1. - 1 / (p * p + 1.));
-    const double tErr  = (z - zend) / (Physics::c * beta);
+    return pair<double, double>(p(2), t - tErr);
+}
 
-    return pair<double, double>(p, t - tErr);
+bool RFCavity::isInside(const Vector_t &r) const {
+    if (isInsideTransverse(r)) {
+        return fieldmap_m->isInside(r);
+    }
+
+    return false;
 }
diff --git a/src/Classic/AbsBeamline/RFCavity.h b/src/Classic/AbsBeamline/RFCavity.h
index d6fddb74c053baf12efc6ddf022ee2605f8a32ea..df20bcf16c1a3d822e34ba8ee432e9a00159f58b 100644
--- a/src/Classic/AbsBeamline/RFCavity.h
+++ b/src/Classic/AbsBeamline/RFCavity.h
@@ -21,8 +21,9 @@
 //
 // ------------------------------------------------------------------------
 
-#include "Algorithms/AbstractTimeDependence.h"
+
 #include "AbsBeamline/Component.h"
+#include "Algorithms/AbstractTimeDependence.h"
 #include "Physics/Physics.h"
 
 class Fieldmap;
@@ -65,6 +66,9 @@ public:
     std::string getFieldMapFN() const;
 
     void setAmplitudem(double vPeak);
+    double getAmplitudem() const;
+    void setAmplitudeError(double vPeakError);
+    double getAmplitudeError() const;
 
     void setFrequencym(double freq);
 
@@ -74,9 +78,11 @@ public:
 
     void setPhasem(double phase);
 
-    void updatePhasem(double phase);
-
     double getPhasem() const;
+    double getPhasem(double t) const;
+
+    void setPhaseError(double phaseError);
+    double getPhaseError() const;
 
     void setCavityType(std::string type);
 
@@ -86,37 +92,45 @@ public:
 
     bool getFast() const;
 
-    void setAutophaseVeto(bool veto);
+    void setAutophaseVeto(bool veto = true);
 
     bool getAutophaseVeto() const;
 
     double getAutoPhaseEstimate(const double & E0, const double & t0, const double & q, const double & m);
 
-    std::pair<double, double> trackOnAxisParticle(const double & p0, 
-                                                  const double & t0, 
-                                                  const double & dt, 
-                                                  const double & q, 
+    std::pair<double, double> trackOnAxisParticle(const double & p0,
+                                                  const double & t0,
+                                                  const double & dt,
+                                                  const double & q,
                                                   const double & mass);
 
     virtual void addKR(int i, double t, Vector_t &K);
 
     virtual void addKT(int i, double t, Vector_t &K);
 
-    virtual bool apply(const size_t &i, const double &t, double E[], double B[]);
-
-    virtual bool apply(const size_t &i, const double &t, Vector_t &E, Vector_t &B);
-
-    virtual bool apply(const Vector_t &R, const Vector_t &centroid, const double &t, Vector_t &E, Vector_t &B);
-
-    virtual void initialise(PartBunch *bunch, double &startField, double &endField, const double &scaleFactor);
+    virtual bool apply(const size_t &i,
+                       const double &t,
+                       Vector_t &E,
+                       Vector_t &B);
 
-//    virtual void initialise(PartBunch *bunch, const double &scaleFactor);
-
-    virtual void initialise(PartBunch *bunch, const double &scaleFactor, std::shared_ptr<AbstractTimeDependence> freq_atd,
-                            std::shared_ptr<AbstractTimeDependence> ampl_atd, std::shared_ptr<AbstractTimeDependence> phase_atd);
+    virtual bool apply(const Vector_t &R,
+                       const Vector_t &P,
+                       const double &t,
+                       Vector_t &E,
+                       Vector_t &B);
 
+    virtual bool applyToReferenceParticle(const Vector_t &R,
+                                          const Vector_t &P,
+                                          const double &t,
+                                          Vector_t &E,
+                                          Vector_t &B);
 
+    virtual void initialise(PartBunch *bunch, double &startField, double &endField);
 
+    virtual void initialise(PartBunch *bunch,
+                            std::shared_ptr<AbstractTimeDependence> freq_atd,
+                            std::shared_ptr<AbstractTimeDependence> ampl_atd,
+                            std::shared_ptr<AbstractTimeDependence> phase_atd);
 
     virtual void finalise();
 
@@ -126,6 +140,9 @@ public:
 
     virtual void goOffline();
 
+    virtual void setDesignEnergy(double ekin);
+    virtual double getDesignEnergy() const;
+
     void setRmin(double rmin);
 
     void setRmax(double rmax);
@@ -168,40 +185,40 @@ public:
 
     virtual void getDimensions(double &zBegin, double &zEnd) const;
 
+    virtual bool isInside(const Vector_t &r) const;
 
-    virtual void setAmplitudeModel(std::shared_ptr<AbstractTimeDependence> time_dep);
-    void setAmplitudeModelName(std::string name) {amplitude_name_m=name;}
-    std::string getAmplitudeModelName() { return amplitude_name_m;}
+    void setAmplitudeModel(std::shared_ptr<AbstractTimeDependence> time_dep);
+    void setAmplitudeModelName(std::string name);
+    std::string getAmplitudeModelName();
 
-    virtual void setPhaseModel(std::shared_ptr<AbstractTimeDependence> time_dep);
-    void setPhaseModelName(std::string name) {phase_name_m=name;}
-    std::string getPhaseModelName() { return phase_name_m;}
+    void setPhaseModel(std::shared_ptr<AbstractTimeDependence> time_dep);
+    void setPhaseModelName(std::string name);
+    std::string getPhaseModelName();
 
-    virtual void setFrequencyModel(std::shared_ptr<AbstractTimeDependence> time_dep);
-    virtual void setFrequencyModelName(std::string name);
-    std::string getFrequencyModelName() { return frequency_name_m;}
+    void setFrequencyModel(std::shared_ptr<AbstractTimeDependence> time_dep);
+    void setFrequencyModelName(std::string name);
+    std::string getFrequencyModelName();
 
- protected:
+protected:
     std::shared_ptr<AbstractTimeDependence> phase_td_m;
     std::string phase_name_m;
     std::shared_ptr<AbstractTimeDependence> amplitude_td_m;
     std::string amplitude_name_m;
     std::shared_ptr<AbstractTimeDependence> frequency_td_m;
     std::string frequency_name_m;
+
 private:
     std::string filename_m;             /**< The name of the inputfile*/
-    std::vector<std::string> multiFilenames_m;
-    std::vector<Fieldmap*> multiFieldmaps_m;
+    Fieldmap* fieldmap_m;
     double scale_m;              /**< scale multiplier*/
-    std::vector<double> multiScales_m;
-    double phase_m;              /**< phase shift of time varying field(degrees)*/
-    std::vector<double> multiPhases_m;
-    double frequency_m;          /**< Read in frequency of time varying field(MHz)*/
-    std::vector<double> multiFrequencies_m;
-    double ElementEdge_m;
+    double scaleError_m;         /**< additive scale error*/
+    double phase_m;              /**< phase shift of time varying field (rad)*/
+    double phaseError_m;         /**< phase shift error (rad)*/
+    double frequency_m;          /**< Read in frequency of time varying field(Hz)*/
+
     double startField_m;         /**< starting point of field(m)*/
     double endField_m;
-    std::vector<std::pair<double, double> > multi_start_end_field_m;
+    double length_m;
 
     CavityType type_m;
 
@@ -217,39 +234,34 @@ private:
     double gapwidth_m;
     double phi0_m;
 
+    double designEnergy_m;
+
     std::unique_ptr<double[]> RNormal_m;
     std::unique_ptr<double[]> VrNormal_m;
     std::unique_ptr<double[]> DvDr_m;
     int num_points_m;
 
-    inline size_t numFieldmaps() const {
-        return multiFilenames_m.size();
-    }
-
-    
-    double getdE(const int & i, 
-                 const std::vector<double> & t, 
+    double getdE(const int & i,
+                 const std::vector<double> & t,
                  const double & dz,
                  const double & phi,
                  const double & frequency,
                  const std::vector<double> & F) const;
 
-    double getdT(const int & i, 
+    double getdT(const int & i,
                  const std::vector<double> & E,
                  const double & dz,
                  const double mass) const;
-    
+
     double getdA(const int & i,
-                 const std::vector<double> & t, 
+                 const std::vector<double> & t,
                  const double & dz,
-                 const double & phi,
                  const double & frequency,
                  const std::vector<double> & F) const;
 
     double getdB(const int & i,
-                 const std::vector<double> & t, 
+                 const std::vector<double> & t,
                  const double & dz,
-                 const double & phi,
                  const double & frequency,
                  const std::vector<double> & F) const;
 
@@ -259,18 +271,18 @@ private:
 
 inline
 double RFCavity::getdE(const int & i,
-                       const std::vector<double> & t, 
+                       const std::vector<double> & t,
                        const double & dz,
                        const double & phi,
                        const double & frequency,
                        const std::vector<double> & F) const {
-    return dz / (frequency * frequency * (t[i] - t[i-1]) * (t[i] - t[i-1])) * 
+    return dz / (frequency * frequency * (t[i] - t[i-1]) * (t[i] - t[i-1])) *
         (frequency * (t[i] - t[i-1]) * (F[i] * sin(frequency * t[i] + phi) - F[i-1] * sin(frequency * t[i-1] + phi)) +
          (F[i] - F[i-1]) * (cos(frequency * t[i] + phi) - cos(frequency * t[i-1] + phi)));
 }
 
 inline
-double RFCavity::getdT(const int & i, 
+double RFCavity::getdT(const int & i,
                        const std::vector<double> & E,
                        const double & dz,
                        const double mass) const {
@@ -299,28 +311,188 @@ double RFCavity::getdT(const int & i,
 
 inline
 double RFCavity::getdA(const int & i,
-                       const std::vector<double> & t, 
+                       const std::vector<double> & t,
                        const double & dz,
-                       const double & phi,
                        const double & frequency,
                        const std::vector<double> & F) const {
     double dt = t[i] - t[i-1];
     return dz / (frequency * frequency * dt * dt) *
-        (frequency * dt * (F[i] * cos(frequency * t[i] + phi) - F[i-1] * cos(frequency * t[i-1] + phi)) -
-         (F[i] - F[i-1]) * (sin(frequency * t[i] + phi) - sin(frequency * t[i-1] + phi)));
+        (frequency * dt * (F[i] * cos(frequency * t[i]) - F[i-1] * cos(frequency * t[i-1])) -
+         (F[i] - F[i-1]) * (sin(frequency * t[i]) - sin(frequency * t[i-1])));
 }
 
 inline
 double RFCavity::getdB(const int & i,
-                       const std::vector<double> & t, 
+                       const std::vector<double> & t,
                        const double & dz,
-                       const double & phi,
                        const double & frequency,
                        const std::vector<double> & F) const {
     double dt = t[i] - t[i-1];
-    return dz / (frequency * frequency * dt * dt) * 
-        (frequency * dt * (F[i] * sin(frequency * t[i] + phi) - F[i-1] * sin(frequency * t[i-1] + phi)) +
-         (F[i] - F[i-1]) * (cos(frequency * t[i] + phi) - cos(frequency * t[i-1] + phi)));
+    return dz / (frequency * frequency * dt * dt) *
+        (frequency * dt * (F[i] * sin(frequency * t[i]) - F[i-1] * sin(frequency * t[i-1])) +
+         (F[i] - F[i-1]) * (cos(frequency * t[i]) - cos(frequency * t[i-1])));
+}
+
+inline
+void RFCavity::setDesignEnergy(double ekin)
+{
+    designEnergy_m = ekin;
+}
+
+inline
+double RFCavity::getDesignEnergy() const
+{
+    return designEnergy_m;
+}
+
+inline
+void RFCavity::dropFieldmaps() {
+    fieldmap_m = NULL;
+}
+
+inline
+void RFCavity::setFieldMapFN(std::string fn) {
+    filename_m = fn;
+}
+
+inline
+std::string RFCavity::getFieldMapFN() const {
+    return filename_m;
+}
+
+inline
+void RFCavity::setAmplitudem(double vPeak) {
+    scale_m = vPeak;
+}
+
+inline
+double RFCavity::getAmplitudem() const {
+    return scale_m;
+}
+
+inline
+void RFCavity::setAmplitudeError(double vPeakError) {
+    scaleError_m = vPeakError;
+}
+
+inline
+double RFCavity::getAmplitudeError() const {
+    return scaleError_m;
+}
+
+inline
+void RFCavity::setFrequency(double freq) {
+    frequency_m = freq;
+}
+
+inline
+void RFCavity::setFrequencym(double freq) {
+    frequency_m = freq;
+}
+
+inline
+double RFCavity::getFrequencym() const {
+    return frequency_m;
+}
+
+inline
+void RFCavity::setPhasem(double phase) {
+    phase_m = phase;
+}
+
+inline
+double RFCavity::getPhasem() const {
+    return phase_m;
+}
+
+inline
+double RFCavity::getPhasem(double t) const {
+    return phase_m + t * frequency_m;
+}
+
+inline
+void RFCavity::setPhaseError(double phaseError) {
+    phaseError_m = phaseError;
+}
+
+inline
+double RFCavity::getPhaseError() const {
+    return phaseError_m;
+}
+
+inline
+void RFCavity::setCavityType(std::string type) {
+
+}
+
+inline
+std::string RFCavity::getCavityType() const {
+    return "SW";
+}
+
+inline
+void RFCavity::setFast(bool fast) {
+    fast_m = fast;
+}
+
+inline
+bool RFCavity::getFast() const {
+    return fast_m;
+}
+
+inline
+void RFCavity::setAutophaseVeto(bool veto) {
+    autophaseVeto_m = veto;
+}
+
+inline
+bool RFCavity::getAutophaseVeto() const {
+    return autophaseVeto_m;
+}
+
+inline
+void RFCavity::setAmplitudeModel(std::shared_ptr<AbstractTimeDependence> amplitude_td) {
+  amplitude_td_m = amplitude_td;
+}
+
+inline
+void RFCavity::setAmplitudeModelName(std::string name) {
+    amplitude_name_m=name;
+}
+
+inline
+std::string RFCavity::getAmplitudeModelName() {
+    return amplitude_name_m;
+}
+
+inline
+void RFCavity::setPhaseModel(std::shared_ptr<AbstractTimeDependence> phase_td) {
+  phase_td_m = phase_td;
+}
+
+inline
+void RFCavity::setPhaseModelName(std::string name) {
+    phase_name_m=name;
+}
+
+inline
+std::string RFCavity::getPhaseModelName() {
+    return phase_name_m;
+}
+
+inline
+void RFCavity::setFrequencyModel(std::shared_ptr<AbstractTimeDependence> frequency_td) {
+  frequency_td_m = frequency_td;
+}
+
+inline
+void RFCavity::setFrequencyModelName(std::string name) {
+  frequency_name_m=name;
+}
+
+inline
+std::string RFCavity::getFrequencyModelName() {
+    return frequency_name_m;
 }
 
 #endif // CLASSIC_RFCavity_HH
diff --git a/src/Classic/AbsBeamline/RFQuadrupole.cpp b/src/Classic/AbsBeamline/RFQuadrupole.cpp
index 893f90bc0fa4d764e9f4abc2afc9850bfc3606ae..475eebcfaaa419ead514885ee7791beba503d122 100644
--- a/src/Classic/AbsBeamline/RFQuadrupole.cpp
+++ b/src/Classic/AbsBeamline/RFQuadrupole.cpp
@@ -49,19 +49,7 @@ void RFQuadrupole::accept(BeamlineVisitor &visitor) const {
     visitor.visitRFQuadrupole(*this);
 }
 
-bool RFQuadrupole::apply(const size_t &i, const double &t, double E[], double B[]) {
-    return false;
-}
-
-bool RFQuadrupole::apply(const size_t &i, const double &t, Vector_t &E, Vector_t &B) {
-    return false;
-}
-
-bool RFQuadrupole::apply(const Vector_t &R, const Vector_t &centroid, const double &t, Vector_t &E, Vector_t &B) {
-    return false;
-}
-
-void RFQuadrupole::initialise(PartBunch *bunch, double &startField, double &endField, const double &scaleFactor) {
+void RFQuadrupole::initialise(PartBunch *bunch, double &startField, double &endField) {
     RefPartBunch_m = bunch;
 }
 
@@ -80,5 +68,4 @@ void RFQuadrupole::getDimensions(double &zBegin, double &zEnd) const {
 
 ElementBase::ElementType RFQuadrupole::getType() const {
     return RFQUADRUPOLE;
-}
-
+}
\ No newline at end of file
diff --git a/src/Classic/AbsBeamline/RFQuadrupole.h b/src/Classic/AbsBeamline/RFQuadrupole.h
index 956ab06b1bceef4633563be1605f14c77fa6f138..9c5bf28825f38f711cf7f162a40980f25046b2fa 100644
--- a/src/Classic/AbsBeamline/RFQuadrupole.h
+++ b/src/Classic/AbsBeamline/RFQuadrupole.h
@@ -41,13 +41,7 @@ public:
     /// Apply visitor to RFQuadrupole.
     virtual void accept(BeamlineVisitor &) const;
 
-    virtual bool apply(const size_t &i, const double &t, double E[], double B[]);
-
-    virtual bool apply(const size_t &i, const double &t, Vector_t &E, Vector_t &B);
-
-    virtual bool apply(const Vector_t &R, const Vector_t &centroid, const double &t, Vector_t &E, Vector_t &B);
-
-    virtual void initialise(PartBunch *bunch, double &startField, double &endField, const double &scaleFactor);
+    virtual void initialise(PartBunch *bunch, double &startField, double &endField);
 
     virtual void finalise();
 
@@ -63,4 +57,4 @@ private:
     void operator=(const RFQuadrupole &);
 };
 
-#endif // CLASSIC_RFQuadrupole_HH
+#endif // CLASSIC_RFQuadrupole_HH
\ No newline at end of file
diff --git a/src/Classic/AbsBeamline/Ring.cpp b/src/Classic/AbsBeamline/Ring.cpp
index 81f2eb1f4a17b5f0fd8eee4e347a407929545f09..aaefd7506185dd78b6130aa13a03782377188d3b 100644
--- a/src/Classic/AbsBeamline/Ring.cpp
+++ b/src/Classic/AbsBeamline/Ring.cpp
@@ -97,7 +97,7 @@ Ring::~Ring() {
 bool Ring::apply(const size_t &id, const double &t, Vector_t &E,
                  Vector_t &B) {
     bool flagNeedUpdate =
-        apply(refPartBunch_m->R[id], refPartBunch_m->get_centroid(), t, E, B);
+        apply(refPartBunch_m->R[id], refPartBunch_m->P[id], t, E, B);
     if(flagNeedUpdate) {
         Inform gmsgALL("OPAL ", INFORM_ALL_NODES);
         gmsgALL << getName() << ": particle " << id
@@ -110,24 +110,7 @@ bool Ring::apply(const size_t &id, const double &t, Vector_t &E,
     return flagNeedUpdate;
 }
 
-bool Ring::apply(const size_t &id, const double &t,
-                 double E[], double B[]) {
-    Vector_t Ev(0, 0, 0), Bv(0, 0, 0);
-
-    if(apply(id, t, Ev, Bv))
-        return true;
-
-    E[0] = Ev(0);
-    E[1] = Ev(1);
-    E[2] = Ev(2);
-    B[0] = Bv(0);
-    B[1] = Bv(1);
-    B[2] = Bv(2);
-
-    return false;
-}
-
-bool Ring::apply(const Vector_t &R, const Vector_t &centroid,
+bool Ring::apply(const Vector_t &R, const Vector_t &P,
                  const double &t, Vector_t &E, Vector_t &B) {
     B = Vector_t(0.0, 0.0, 0.0);
     E = Vector_t(0.0, 0.0, 0.0);
@@ -138,7 +121,7 @@ bool Ring::apply(const Vector_t &R, const Vector_t &centroid,
     for (size_t i = 0; i < sections.size(); ++i) {
         Vector_t B_temp(0.0, 0.0, 0.0);
         Vector_t E_temp(0.0, 0.0, 0.0);
-        outOfBounds &= sections[i]->getFieldValue(R, centroid, t, E_temp, B_temp);
+        outOfBounds &= sections[i]->getFieldValue(R, refPartBunch_m->get_centroid(), t, E_temp, B_temp);
         B += (scale_m * B_temp);
         E += (scale_m * E_temp);
     }
@@ -165,7 +148,7 @@ void Ring::initialise(PartBunch *bunch) {
 }
 
 void Ring::initialise(PartBunch * bunch, double &startField,
-                      double &endField, const double &scaleFactor) {
+                      double &endField) {
     initialise(bunch);
 }
 
diff --git a/src/Classic/AbsBeamline/Ring.h b/src/Classic/AbsBeamline/Ring.h
index 3b337a9326f887562fec072ac472b6956b8f5bb8..6d3be452160551ebe44028c8dea8673116b70584 100644
--- a/src/Classic/AbsBeamline/Ring.h
+++ b/src/Classic/AbsBeamline/Ring.h
@@ -79,23 +79,6 @@ class Ring : public Component {
     /** Destructor - deletes lossDS_m if not NULL */
     virtual ~Ring();
 
-    /** Overwrite data in array E and B with electric and magnetic fields and
-     *  flag particles outside of the ring aperture
-     *
-     *  @param id index of item in RefPartBunch_m - particle bunch
-     *  @param t time
-     *  @param E array where electric field vector is stored - any
-     *         existing data is overwritten
-     *  @param B array where magnetic field vector is stored - any
-     *         existing data is overwritten
-     *
-     *  @returns false if particle is outside of the field map apertures, else
-     *  true. If particle is off the field maps, then set flag on the particle
-     *  "Bin" data to -1
-     */
-    virtual bool apply(const size_t &id, const double &t, double E[],
-                       double B[]);
-
     /** Overwrite data in vector E and B with electric and magnetic field
      *
      *  @param i index of item in RefPartBunch_m - particle bunch
@@ -116,6 +99,7 @@ class Ring : public Component {
      *
      *  @param R 3 vector position at which the field is found in Cartesian
      *         coordinates (i.e. x, y, z with z=vertical)
+     *  @param P 3 vector momentum
      *  @param centroid unknown, but not used - bunch mean maybe?
      *  @param t time
      *  @param E vector where electric field vector will be stored - any
@@ -127,7 +111,7 @@ class Ring : public Component {
      *  If particle is off the field maps, then set flag on the particle
      *  "Bin" data to -1
      */
-    virtual bool apply(const Vector_t &R, const Vector_t &centroid,
+    virtual bool apply(const Vector_t &R, const Vector_t &P,
                        const double &t, Vector_t &E, Vector_t &B);
 
     /** Initialise the Ring
@@ -139,7 +123,7 @@ class Ring : public Component {
      *  @param scaleFactor - not used
      */
     virtual void initialise(PartBunch *bunch, double &startField,
-                            double &endField, const double &scaleFactor);
+                            double &endField);
 
     /** Initialise the Ring - set the bunch and allocate a new LossDataSink
      *
@@ -416,4 +400,4 @@ Vector3D Ring::convert(const Vector_t& vec_t) {
     return Vector3D(vec_t[0], vec_t[1], vec_t[2]);
 }
 
-#endif //#ifndef RING_H
+#endif //#ifndef RING_H
\ No newline at end of file
diff --git a/src/Classic/AbsBeamline/SBend.cpp b/src/Classic/AbsBeamline/SBend.cpp
index 81813aa23aa971480b5969d9e5537d04184ffaac..ecf5e0e6d620aa08a0b431140dcb9d1fac8644ec 100644
--- a/src/Classic/AbsBeamline/SBend.cpp
+++ b/src/Classic/AbsBeamline/SBend.cpp
@@ -94,31 +94,13 @@ ElementBase::ElementType SBend::getType() const {
 }
 
 
-bool SBend::FindChordLength(Inform &msg,
-                            double &chordLength,
-                            bool &chordLengthFromMap) {
+bool SBend::findChordLength(Inform &msg,
+                            double &chordLength) {
 
     /*
      * Find bend chord length. If this was not set by the user using the
      * L (length) attribute, infer it from the field map.
      */
     chordLength = getLength();
-    if(chordLength > 0.0) {
-        chordLengthFromMap = false;
-        return true;
-    } else {
-
-        if(chordLength == 0.0)
-            chordLength = getLength();
-
-        chordLengthFromMap = true;
-
-        if(chordLength <= 0.0) {
-            ERRORMSG(level2 << "Magnet length inferred from field map is less than or equal"
-                     << " to zero. Check your bend magnet input." << endl);
-            return false;
-        } else
-            return true;
-
-    }
+    return true;
 }
\ No newline at end of file
diff --git a/src/Classic/AbsBeamline/SBend.h b/src/Classic/AbsBeamline/SBend.h
index f1ce282b4d5176010345768d2e1795d48c4e8a24..e7474137ebe44fa7c7f213dc4dc0a08edceae3d1 100644
--- a/src/Classic/AbsBeamline/SBend.h
+++ b/src/Classic/AbsBeamline/SBend.h
@@ -174,9 +174,8 @@ private:
     // Not implemented.
     void operator=(const SBend &);
 
-    virtual bool FindChordLength(Inform &msg,
-                                 double &chordLength,
-                                 bool &chordLengthFromMap);
+    virtual bool findChordLength(Inform &msg,
+                                 double &chordLength);
 
 };
 
diff --git a/src/Classic/AbsBeamline/SBend3D.cpp b/src/Classic/AbsBeamline/SBend3D.cpp
index cfad3d205e06af65c2277fd9bf03bc4c30f66b2a..4eb7ec876b56a03d72284c3a87410a92e7acb0ee 100644
--- a/src/Classic/AbsBeamline/SBend3D.cpp
+++ b/src/Classic/AbsBeamline/SBend3D.cpp
@@ -1,27 +1,27 @@
-/* 
+/*
  *  Copyright (c) 2012, Chris Rogers
  *  All rights reserved.
- *  Redistribution and use in source and binary forms, with or without 
- *  modification, are permitted provided that the following conditions are met: 
+ *  Redistribution and use in source and binary forms, with or without
+ *  modification, are permitted provided that the following conditions are met:
  *  1. Redistributions of source code must retain the above copyright notice,
- *     this list of conditions and the following disclaimer. 
- *  2. Redistributions in binary form must reproduce the above copyright notice, 
- *     this list of conditions and the following disclaimer in the documentation 
+ *     this list of conditions and the following disclaimer.
+ *  2. Redistributions in binary form must reproduce the above copyright notice,
+ *     this list of conditions and the following disclaimer in the documentation
  *     and/or other materials provided with the distribution.
- *  3. Neither the name of STFC nor the names of its contributors may be used to 
- *     endorse or promote products derived from this software without specific 
+ *  3. Neither the name of STFC nor the names of its contributors may be used to
+ *     endorse or promote products derived from this software without specific
  *     prior written permission.
  *
- *  THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" 
- *  AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE 
- *  IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE 
- *  ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE 
- *  LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR 
- *  CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF 
- *  SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS 
- *  INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN 
- *  CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) 
- *  ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE 
+ *  THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
+ *  AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ *  IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ *  ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
+ *  LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+ *  CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+ *  SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
+ *  INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+ *  CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ *  ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
  *  POSSIBILITY OF SUCH DAMAGE.
  */
 
@@ -63,36 +63,18 @@ const EMField &SBend3D::getField() const {
     return dummy;
 }
 
-bool SBend3D::apply(const size_t &i, const double &t, double E[], double B[]) {
-    Vector_t Ev(0, 0, 0), Bv(0, 0, 0);
-
-    if (apply(i, t, Ev, Bv))
-        return true;
-
-    E[0] = Ev(0);
-    E[1] = Ev(1);
-    E[2] = Ev(2);
-    B[0] = Bv(0);
-    B[1] = Bv(1);
-    B[2] = Bv(2);
-
-    return false;
-}
-
 bool SBend3D::apply(const size_t &i, const double &t,
                     Vector_t &E, Vector_t &B) {
-    return apply(RefPartBunch_m->R[i], RefPartBunch_m->get_centroid(), t,
-                 E, B);
+    return apply(RefPartBunch_m->R[i], RefPartBunch_m->P[i], t, E, B);
 }
 
-bool SBend3D::apply(const Vector_t &R, const Vector_t &centroid,
-           const double &t, Vector_t &E, Vector_t &B) {
+bool SBend3D::apply(const Vector_t &R, const Vector_t &P,
+                    const double &t, Vector_t &E, Vector_t &B) {
     //std::cerr << "ROGERS SBend3D::apply " << R << " " << B << std::endl;
     return map_m->getFieldstrength(R, E, B);
 }
 
-void SBend3D::initialise(PartBunch *bunch, double &startField, double &endField,
-                const double &scaleFactor) {
+void SBend3D::initialise(PartBunch *bunch, double &startField, double &endField) {
     RefPartBunch_m = bunch;
 }
 
@@ -135,6 +117,4 @@ void SBend3D::setFieldMapFileName(std::string name) {
 
 void SBend3D::accept(BeamlineVisitor& visitor) const {
     visitor.visitSBend3D(*this);
-}
-
-
+}
\ No newline at end of file
diff --git a/src/Classic/AbsBeamline/SBend3D.h b/src/Classic/AbsBeamline/SBend3D.h
index 4983618b4e7647b118bdbbf7acc03523589724a0..7746874be0ab191f037947ad8f855b6e91f1fbe3 100644
--- a/src/Classic/AbsBeamline/SBend3D.h
+++ b/src/Classic/AbsBeamline/SBend3D.h
@@ -1,27 +1,27 @@
-/* 
+/*
  *  Copyright (c) 2012, Chris Rogers
  *  All rights reserved.
- *  Redistribution and use in source and binary forms, with or without 
- *  modification, are permitted provided that the following conditions are met: 
+ *  Redistribution and use in source and binary forms, with or without
+ *  modification, are permitted provided that the following conditions are met:
  *  1. Redistributions of source code must retain the above copyright notice,
- *     this list of conditions and the following disclaimer. 
- *  2. Redistributions in binary form must reproduce the above copyright notice, 
- *     this list of conditions and the following disclaimer in the documentation 
+ *     this list of conditions and the following disclaimer.
+ *  2. Redistributions in binary form must reproduce the above copyright notice,
+ *     this list of conditions and the following disclaimer in the documentation
  *     and/or other materials provided with the distribution.
- *  3. Neither the name of STFC nor the names of its contributors may be used to 
- *     endorse or promote products derived from this software without specific 
+ *  3. Neither the name of STFC nor the names of its contributors may be used to
+ *     endorse or promote products derived from this software without specific
  *     prior written permission.
  *
- *  THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" 
- *  AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE 
- *  IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE 
- *  ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE 
- *  LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR 
- *  CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF 
- *  SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS 
- *  INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN 
- *  CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) 
- *  ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE 
+ *  THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
+ *  AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ *  IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ *  ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
+ *  LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+ *  CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+ *  SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
+ *  INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+ *  CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ *  ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
  *  POSSIBILITY OF SUCH DAMAGE.
  */
 
@@ -64,17 +64,6 @@ class SBend3D : public Component {
     /** Inheritable copy constructor */
     ElementBase* clone() const;
 
-    /** Calculate the field at the position of the ith particle
-     *
-     *  \param i index of the particle event; field is calculated at this
-     *         position
-     *  \param t time at which the field is to be calculated
-     *  \param E calculated electric field - always 0 (no E-field)
-     *  \param B calculated magnetic field
-     *  \returns true if particle is outside the field map
-     */
-    bool apply(const size_t &i, const double &t, double E[], double B[]);
-
     /** Calculate the field at the position of the ith particle
      *
      *  \param i index of the particle event; field is calculated at this
@@ -89,13 +78,12 @@ class SBend3D : public Component {
     /** Calculate the field at some arbitrary position
      *
      *  \param R position in the local coordinate system of the bend
-     *  \param centroid not used
      *  \param t time at which the field is to be calculated
      *  \param E calculated electric field - always 0 (no E-field)
      *  \param B calculated magnetic field
      *  \returns true if particle is outside the field map, else false
      */
-    bool apply(const Vector_t &R, const Vector_t &centroid, const double &t,
+    bool apply(const Vector_t &R, const Vector_t &P, const double &t,
                Vector_t &E, Vector_t &B);
 
      /** Initialise the SBend3D
@@ -103,10 +91,8 @@ class SBend3D : public Component {
       *  \param bunch the global bunch object
       *  \param startField not used
       *  \param endField not used
-      *  \param scaleFactor not used
       */
-    void initialise(PartBunch *bunch, double &startField, double &endField,
-                    const double &scaleFactor);
+    void initialise(PartBunch *bunch, double &startField, double &endField);
 
      /** Finalise the SBend3D - sets bunch to NULL */
     void finalise();
@@ -189,5 +175,4 @@ std::string SBend3D::getFieldMapFileName() const {
     return map_m->getFieldMapFileName();
 }
 
-#endif
-
+#endif
\ No newline at end of file
diff --git a/src/Classic/AbsBeamline/SectorFieldMapComponent.h b/src/Classic/AbsBeamline/SectorFieldMapComponent.h
index 3462722ffe74e638bb0fef6b6f780755fcf50ba7..50a4914d63187e2123babfe94898dd0769f50175 100644
--- a/src/Classic/AbsBeamline/SectorFieldMapComponent.h
+++ b/src/Classic/AbsBeamline/SectorFieldMapComponent.h
@@ -19,13 +19,13 @@ public:
     //  (version for constant object).
     virtual const EMField &getField() const = 0;
 
-    virtual bool apply(const size_t &i, const double &t, double E[], double B[]) = 0;
+    virtual bool apply(const double &t, Vector_t &E, Vector_t &B) = 0;
 
     virtual bool apply(const size_t &i, const double &t, Vector_t &E, Vector_t &B) = 0;
 
     virtual bool apply(const Vector_t &R, const Vector_t &centroid, const double &t, Vector_t &E, Vector_t &B) = 0;
 
-    virtual void initialise(PartBunch *bunch, double &startField, double &endField, const double &scaleFactor) = 0;
+    virtual void initialise(PartBunch *bunch, double &startField, double &endField) = 0;
 
     virtual void finalise() = 0;
 
diff --git a/src/Classic/AbsBeamline/Separator.cpp b/src/Classic/AbsBeamline/Separator.cpp
index ddc24c57f0fadaa618657ed11491cd65781cea77..bbca24cff7956b5335e33597b549fd053bfdc092 100644
--- a/src/Classic/AbsBeamline/Separator.cpp
+++ b/src/Classic/AbsBeamline/Separator.cpp
@@ -48,19 +48,7 @@ void Separator::accept(BeamlineVisitor &visitor) const {
     visitor.visitSeparator(*this);
 }
 
-bool Separator::apply(const size_t &i, const double &t, double E[], double B[]) {
-    return false;
-}
-
-bool Separator::apply(const size_t &i, const double &t, Vector_t &E, Vector_t &B) {
-    return false;
-}
-
-bool Separator::apply(const Vector_t &R, const Vector_t &centroid, const double &t, Vector_t &E, Vector_t &B) {
-    return false;
-}
-
-void Separator::initialise(PartBunch *bunch, double &startField, double &endField, const double &scaleFactor) {
+void Separator::initialise(PartBunch *bunch, double &startField, double &endField) {
     RefPartBunch_m = bunch;
 }
 
@@ -78,5 +66,4 @@ void Separator::getDimensions(double &zBegin, double &zEnd) const {
 
 ElementBase::ElementType Separator::getType() const {
     return SEPARATOR;
-}
-
+}
\ No newline at end of file
diff --git a/src/Classic/AbsBeamline/Separator.h b/src/Classic/AbsBeamline/Separator.h
index e53981922df8f2ce0423f234019b769a766d42bc..8dab1b92ddfbd1075adb36ae4d756868cb40cf30 100644
--- a/src/Classic/AbsBeamline/Separator.h
+++ b/src/Classic/AbsBeamline/Separator.h
@@ -50,13 +50,7 @@ public:
     /// Get vertical component Ey of field in V/m.
     virtual double getEy() const = 0;
 
-    virtual bool apply(const size_t &i, const double &t, double E[], double B[]);
-
-    virtual bool apply(const size_t &i, const double &t, Vector_t &E, Vector_t &B);
-
-    virtual bool apply(const Vector_t &R, const Vector_t &centroid, const double &t, Vector_t &E, Vector_t &B);
-
-    virtual void initialise(PartBunch *bunch, double &startField, double &endField, const double &scaleFactor);
+    virtual void initialise(PartBunch *bunch, double &startField, double &endField);
 
     virtual void finalise();
 
@@ -72,4 +66,4 @@ private:
     void operator=(const Separator &);
 };
 
-#endif // CLASSIC_Separator_HH
+#endif // CLASSIC_Separator_HH
\ No newline at end of file
diff --git a/src/Classic/AbsBeamline/Septum.cpp b/src/Classic/AbsBeamline/Septum.cpp
index ff84055dc81d120e12303b81b83ea243f1130a38..ab978c2321b2a69b228529107dae730493de0091 100644
--- a/src/Classic/AbsBeamline/Septum.cpp
+++ b/src/Classic/AbsBeamline/Septum.cpp
@@ -76,23 +76,7 @@ void Septum::accept(BeamlineVisitor &visitor) const {
     visitor.visitSeptum(*this);
 }
 
-bool Septum::apply(const size_t &i, const double &t, double E[], double B[]) {
-
-    Vector_t Ev(0, 0, 0), Bv(0, 0, 0);
-    return apply(i, t, Ev, Bv);
-}
-
-bool Septum::apply(const size_t &i, const double &t, Vector_t &E, Vector_t &B) {
-
-    return false;
-}
-
-bool Septum::apply(const Vector_t &R, const Vector_t &centroid, const double &t, Vector_t &E, Vector_t &B) {
-
-    return false;
-}
-
-void Septum::initialise(PartBunch *bunch, double &startField, double &endField, const double &scaleFactor) {
+void Septum::initialise(PartBunch *bunch, double &startField, double &endField) {
     RefPartBunch_m = bunch;
     position_m = startField;
     startField -= 0.005;
@@ -101,7 +85,7 @@ void Septum::initialise(PartBunch *bunch, double &startField, double &endField,
 
 }
 
-void Septum::initialise(PartBunch *bunch, const double &scaleFactor) {
+void Septum::initialise(PartBunch *bunch) {
     *gmsg << "Septum initialise" << endl;
 }
 
@@ -217,4 +201,4 @@ void Septum::getDimensions(double &zBegin, double &zEnd) const {
 
 ElementBase::ElementType Septum::getType() const {
     return SEPTUM;
-}
+}
\ No newline at end of file
diff --git a/src/Classic/AbsBeamline/Septum.h b/src/Classic/AbsBeamline/Septum.h
index 826add543a4d5f80fda033b9e9fc69fc6ce71fb5..a7a1bcd5c3180fe08db3f80916e4d18a51a87e1c 100644
--- a/src/Classic/AbsBeamline/Septum.h
+++ b/src/Classic/AbsBeamline/Septum.h
@@ -43,14 +43,8 @@ public:
     /// Apply visitor to Septum.
     virtual void accept(BeamlineVisitor &) const;
 
-    virtual bool apply(const size_t &i, const double &t, double E[], double B[]);
-
-    virtual bool apply(const size_t &i, const double &t, Vector_t &E, Vector_t &B);
-
-    virtual bool apply(const Vector_t &R, const Vector_t &centroid, const double &t, Vector_t &E, Vector_t &B);
-
-    virtual void initialise(PartBunch *bunch, double &startField, double &endField, const double &scaleFactor);
-    virtual void initialise(PartBunch *bunch, const double &scaleFactor);
+    virtual void initialise(PartBunch *bunch, double &startField, double &endField);
+    virtual void initialise(PartBunch *bunch);
 
     virtual void finalise();
 
diff --git a/src/Classic/AbsBeamline/Solenoid.cpp b/src/Classic/AbsBeamline/Solenoid.cpp
index 9f3dc86042f2ae48cab6684a901562861bed4844..72a5706d676d82033ad917ba25d6521ce4c7ad81 100644
--- a/src/Classic/AbsBeamline/Solenoid.cpp
+++ b/src/Classic/AbsBeamline/Solenoid.cpp
@@ -37,9 +37,9 @@ Solenoid::Solenoid():
     filename_m(""),
     myFieldmap_m(NULL),
     scale_m(1.0),
-    ElementEdge_m(0.0),
+    scaleError_m(0.0),
     startField_m(0.0),
-    endField_m(0.0),
+    length_m(0.0),
     fast_m(false) {
     setElType(isSolenoid);
 }
@@ -50,9 +50,9 @@ Solenoid::Solenoid(const Solenoid &right):
     filename_m(right.filename_m),
     myFieldmap_m(right.myFieldmap_m),
     scale_m(right.scale_m),
-    ElementEdge_m(right.ElementEdge_m),
+    scaleError_m(right.scaleError_m),
     startField_m(right.startField_m),
-    endField_m(right.endField_m),
+    length_m(right.length_m),
     fast_m(right.fast_m) {
     setElType(isSolenoid);
 }
@@ -63,9 +63,9 @@ Solenoid::Solenoid(const std::string &name):
     filename_m(""),
     myFieldmap_m(NULL),
     scale_m(1.0),
-    ElementEdge_m(0.0),
+    scaleError_m(0.0),
     startField_m(0.0),
-    endField_m(0.0),
+    length_m(0.0),
     fast_m(false) {
     setElType(isSolenoid);
 }
@@ -103,8 +103,8 @@ void Solenoid::addKR(int i, double t, Vector_t &K) {
 
     Vector_t tmpE(0.0, 0.0, 0.0);
     Vector_t tmpB(0.0, 0.0, 0.0);
-    double pz = RefPartBunch_m->getZ(i) - startField_m - ds_m;
-    const Vector_t tmpA(RefPartBunch_m->getX(i) - dx_m, RefPartBunch_m->getY(i) - dy_m, pz);
+    double pz = RefPartBunch_m->getZ(i) - startField_m;
+    const Vector_t tmpA(RefPartBunch_m->getX(i), RefPartBunch_m->getY(i), pz);
 
     myFieldmap_m->getFieldstrength(tmpA, tmpE, tmpB);
     double k = Physics::q_e * scale_m * tmpB(2) / (2.0 * Physics::EMASS * RefPartBunch_m->getGamma(i));
@@ -125,8 +125,8 @@ void Solenoid::addKT(int i, double t, Vector_t &K) {
     Vector_t tmpB(0.0, 0.0, 0.0);
     Vector_t tmpE_diff(0.0, 0.0, 0.0);
     Vector_t tmpB_diff(0.0, 0.0, 0.0);
-    double pz = RefPartBunch_m->getZ(i) - startField_m - ds_m;
-    const Vector_t tmpA(RefPartBunch_m->getX(i) - dx_m, RefPartBunch_m->getY(i) - dy_m, pz);
+    double pz = RefPartBunch_m->getZ(i) - startField_m;
+    const Vector_t tmpA(RefPartBunch_m->getX(i), RefPartBunch_m->getY(i), pz);
 
     // define z direction:
     DiffDirection zdir(DZ);
@@ -149,8 +149,8 @@ void Solenoid::addKT(int i, double t, Vector_t &K) {
      *              0.0);
     */
 
-    double dx = RefPartBunch_m->getX0(i) - dx_m;
-    double dy = RefPartBunch_m->getY0(i) - dy_m;
+    double dx = RefPartBunch_m->getX0(i);
+    double dy = RefPartBunch_m->getY0(i);
 
     //FIXME: Py0, Px0?
     Vector_t temp(emg * (bz * (RefPartBunch_m->getPy0(i)) + dbdz * dy),
@@ -160,46 +160,39 @@ void Solenoid::addKT(int i, double t, Vector_t &K) {
     K += temp;
 }
 
-bool Solenoid::apply(const size_t &i, const double &t, double E[], double B[]) {
-    Vector_t Ev(0, 0, 0), Bv(0, 0, 0);
-    Vector_t Rt(RefPartBunch_m->getX(i), RefPartBunch_m->getY(i), RefPartBunch_m->getZ(i));
-    if(apply(Rt, Vector_t(0.0), t, Ev, Bv)) return true;
-
-    E[0] = Ev(0);
-    E[1] = Ev(1);
-    E[2] = Ev(2);
-    B[0] = Bv(0);
-    B[1] = Bv(1);
-    B[2] = Bv(2);
-
-    return false;
+bool Solenoid::apply(const size_t &i, const double &t, Vector_t &E, Vector_t &B) {
+    return apply(RefPartBunch_m->R[i], RefPartBunch_m->P[i], t, E, B);
 }
 
-bool Solenoid::apply(const size_t &i, const double &t, Vector_t &E, Vector_t &B) {
+bool Solenoid::apply(const Vector_t &R, const Vector_t &P, const  double &t, Vector_t &E, Vector_t &B) {
+    const Vector_t tmpR(R(0), R(1), R(2) - startField_m);
     Vector_t tmpE(0.0, 0.0, 0.0), tmpB(0.0, 0.0, 0.0);
-    const Vector_t tmpR(RefPartBunch_m->getX(i) - dx_m, RefPartBunch_m->getY(i) - dy_m, RefPartBunch_m->getZ(i) - startField_m - ds_m);
 
-    if(!myFieldmap_m->getFieldstrength(tmpR, tmpE, tmpB)) {
-        B += scale_m * tmpB;
-        return false;
+    if (tmpR(2) >= 0.0 && tmpR(2) < length_m) {
+        const bool out_of_bounds = myFieldmap_m->getFieldstrength(tmpR, tmpE, tmpB);
+        if (out_of_bounds) return true;
+
+        B += (scale_m + scaleError_m) * tmpB;
     }
 
-    return true;
+    return false;
 }
 
-bool Solenoid::apply(const Vector_t &R, const Vector_t &centroid, const  double &t, Vector_t &E, Vector_t &B) {
-    // why was it here R(2) - ElementEdge_m - ds_m ?
-    //     const Vector_t tmpR(R(0) - dx_m, R(1) - dy_m, R(2) - ElementEdge_m - ds_m);
-    const Vector_t tmpR(R(0) - dx_m, R(1) - dy_m, R(2) - startField_m - ds_m);
+bool Solenoid::applyToReferenceParticle(const Vector_t &R, const Vector_t &P, const  double &t, Vector_t &E, Vector_t &B) {
+    const Vector_t tmpR(R(0), R(1), R(2) - startField_m);
     Vector_t tmpE(0.0, 0.0, 0.0), tmpB(0.0, 0.0, 0.0);
 
-    const bool out_of_bounds = myFieldmap_m->getFieldstrength(tmpR, tmpE, tmpB);
-    B += scale_m * tmpB;
+    if (tmpR(2) >= 0.0 && tmpR(2) < length_m) {
+        const bool out_of_bounds = myFieldmap_m->getFieldstrength(tmpR, tmpE, tmpB);
+        if (out_of_bounds) return true;
 
-    return out_of_bounds;
+        B += scale_m * tmpB;
+    }
+
+    return false;
 }
 
-void Solenoid::initialise(PartBunch *bunch, double &startField, double &endField, const double &scaleFactor) {
+void Solenoid::initialise(PartBunch *bunch, double &startField, double &endField) {
     Inform msg("Solenoid ", *gmsg);
     double zBegin = 0.0, zEnd = 0.0, rBegin = 0.0, rEnd = 0.0;
 
@@ -210,15 +203,12 @@ void Solenoid::initialise(PartBunch *bunch, double &startField, double &endField
     if(myFieldmap_m != NULL) {
         msg << level2 << getName() << " using file ";
         myFieldmap_m->getInfo(&msg);
-        if(std::abs(dx_m) > EPS_MISALIGNMENT || std::abs(dy_m) > EPS_MISALIGNMENT || std::abs(ds_m) > EPS_MISALIGNMENT) {
-            msg << level2 << "misaligned by dx = " << dx_m << ", dy = " << dy_m << ", dz = " << ds_m << endl;
-        }
 
         myFieldmap_m->getFieldDimensions(zBegin, zEnd, rBegin, rEnd);
 
-        ElementEdge_m = startField;
-        startField_m = startField = ElementEdge_m + zBegin;
-        endField_m = endField = ElementEdge_m + zEnd;
+        startField_m = zBegin;
+        length_m = zEnd - zBegin;
+        endField = startField + length_m;
     } else {
         endField = startField;
     }
@@ -246,12 +236,20 @@ void Solenoid::setKS(double ks) {
     scale_m = ks;
 }
 
+void Solenoid::setDKS(double ks) {
+    scaleError_m = ks;
+}
+
 void Solenoid::getDimensions(double &zBegin, double &zEnd) const {
     zBegin = startField_m;
-    zEnd = endField_m;
+    zEnd = startField_m + length_m;
 }
 
 
 ElementBase::ElementType Solenoid::getType() const {
     return SOLENOID;
-}
\ No newline at end of file
+}
+
+bool Solenoid::isInside(const Vector_t &r) const {
+    return (r(2) >= startField_m && r(2) < startField_m + length_m && isInsideTransverse(r) && myFieldmap_m->isInside(r));
+}
diff --git a/src/Classic/AbsBeamline/Solenoid.h b/src/Classic/AbsBeamline/Solenoid.h
index 15bd21704726938f3eb49c58e35f16b3f1ac31ad..201f1a17f2fc22bb01d77e9011f34d3d8ddc5ff8 100644
--- a/src/Classic/AbsBeamline/Solenoid.h
+++ b/src/Classic/AbsBeamline/Solenoid.h
@@ -50,18 +50,19 @@ public:
     virtual double getBz() const = 0;
 
     void setKS(double ks);
+    void setDKS(double ks);
 
     virtual void addKR(int i, double t, Vector_t &K);
 
     virtual void addKT(int i, double t, Vector_t &K);
 
-    virtual bool apply(const size_t &i, const double &t, double E[], double B[]);
-
     virtual bool apply(const size_t &i, const double &t, Vector_t &E, Vector_t &B);
 
-    virtual bool apply(const Vector_t &R, const Vector_t &centroid, const double &t, Vector_t &E, Vector_t &B);
+    virtual bool apply(const Vector_t &R, const Vector_t &P, const double &t, Vector_t &E, Vector_t &B);
+
+    virtual bool applyToReferenceParticle(const Vector_t &R, const Vector_t &P, const double &t, Vector_t &E, Vector_t &B);
 
-    virtual void initialise(PartBunch *bunch, double &startField, double &endField, const double &scaleFactor);
+    virtual void initialise(PartBunch *bunch, double &startField, double &endField);
 
     virtual void finalise();
 
@@ -82,15 +83,17 @@ public:
 
     virtual void getDimensions(double &zBegin, double &zEnd) const;
 
+    virtual bool isInside(const Vector_t &r) const;
 private:
 
     //  std::string name;                   /**< The name of the object*/
     std::string filename_m;               /**< The name of the inputfile*/
     Fieldmap *myFieldmap_m;
     double scale_m;                /**< scale multiplier*/
-    double ElementEdge_m;
+    double scaleError_m;                /**< scale multiplier error*/
+
     double startField_m;           /**< startingpoint of field, m*/
-    double endField_m;
+    double length_m;
 
     bool fast_m;
     // Not implemented.
diff --git a/src/Classic/AbsBeamline/SpecificElementVisitor.h b/src/Classic/AbsBeamline/SpecificElementVisitor.h
index e161d830f65c01e992c00a2e91dce021c82b7375..27575c1999432555510f41ee0ba03cf6fe69de14 100644
--- a/src/Classic/AbsBeamline/SpecificElementVisitor.h
+++ b/src/Classic/AbsBeamline/SpecificElementVisitor.h
@@ -32,6 +32,7 @@
 #include "AbsBeamline/Separator.h"
 #include "AbsBeamline/Septum.h"
 #include "AbsBeamline/Solenoid.h"
+#include "AbsBeamline/Source.h"
 #include "AbsBeamline/ParallelPlate.h"
 #include "AbsBeamline/CyclotronValley.h"
 #include "AbsBeamline/Stripper.h"
@@ -123,6 +124,9 @@ public:
     /// Apply the algorithm to a rectangular bend.
     virtual void visitRBend(const RBend &);
 
+    /// Apply the algorithm to a rectangular bend.
+    virtual void visitRBend3D(const RBend3D &);
+
     /// Apply the algorithm to a RF cavity.
     virtual void visitVariableRFCavity(const VariableRFCavity &vcav);
 
@@ -150,6 +154,9 @@ public:
     /// Apply the algorithm to a solenoid.
     virtual void visitSolenoid(const Solenoid &);
 
+    /// Apply the algorithm to a solenoid.
+    virtual void visitSource(const Source &);
+
     /// Apply the algorithm to a ParallelPlate.
     virtual void visitParallelPlate(const ParallelPlate &);
 
@@ -313,6 +320,11 @@ void SpecificElementVisitor<ELEM>::visitRBend(const RBend &element) {
     CastsTrait<ELEM, RBend>::apply(allElementsOfTypeE, element);
 }
 
+template<class ELEM>
+void SpecificElementVisitor<ELEM>::visitRBend3D(const RBend3D &element) {
+    CastsTrait<ELEM, RBend3D>::apply(allElementsOfTypeE, element);
+}
+
 template<class ELEM>
 void SpecificElementVisitor<ELEM>::visitVariableRFCavity(const VariableRFCavity &element) {
     CastsTrait<ELEM, VariableRFCavity>::apply(allElementsOfTypeE, element);
@@ -358,6 +370,11 @@ void SpecificElementVisitor<ELEM>::visitSolenoid(const Solenoid &element) {
     CastsTrait<ELEM, Solenoid>::apply(allElementsOfTypeE, element);
 }
 
+template<class ELEM>
+void SpecificElementVisitor<ELEM>::visitSource(const Source &element) {
+    CastsTrait<ELEM, Source>::apply(allElementsOfTypeE, element);
+}
+
 template<class ELEM>
 void SpecificElementVisitor<ELEM>::visitParallelPlate(const ParallelPlate &element) {
     CastsTrait<ELEM, ParallelPlate>::apply(allElementsOfTypeE, element);
diff --git a/src/Classic/AbsBeamline/Stripper.cpp b/src/Classic/AbsBeamline/Stripper.cpp
index 662b0d88384fa17c2591423411d1ac6a0a9c7b98..6cf1e05cd365957ea98426a15d45f96cfaa7b858 100644
--- a/src/Classic/AbsBeamline/Stripper.cpp
+++ b/src/Classic/AbsBeamline/Stripper.cpp
@@ -138,27 +138,14 @@ void Stripper::accept(BeamlineVisitor &visitor) const {
     visitor.visitStripper(*this);
 }
 
-bool Stripper::apply(const size_t &i, const double &t, double E[], double B[]) {
-    Vector_t Ev(0, 0, 0), Bv(0, 0, 0);
-    return false;
-}
-
-bool Stripper::apply(const size_t &i, const double &t, Vector_t &E, Vector_t &B) {
-    return false;
-}
-
-bool Stripper::apply(const Vector_t &R, const Vector_t &centroid, const double &t, Vector_t &E, Vector_t &B) {
-    return false;
-}
-
-void Stripper::initialise(PartBunch *bunch, double &startField, double &endField, const double &scaleFactor) {
+void Stripper::initialise(PartBunch *bunch, double &startField, double &endField) {
     if (filename_m == std::string(""))
         lossDs_m = std::unique_ptr<LossDataSink>(new LossDataSink(getName(), !Options::asciidump));
     else
         lossDs_m = std::unique_ptr<LossDataSink>(new LossDataSink(filename_m.substr(0, filename_m.rfind(".")), !Options::asciidump));
 }
 
-void Stripper::initialise(PartBunch *bunch, const double &scaleFactor) {
+void Stripper::initialise(PartBunch *bunch) {
     if (filename_m == std::string(""))
         lossDs_m = std::unique_ptr<LossDataSink>(new LossDataSink(getName(), !Options::asciidump));
     else
@@ -403,4 +390,4 @@ int Stripper::checkPoint(const double &x, const double &y) {
     }
     return (cn & 1);  // 0 if even (out), and 1 if odd (in)
 
-}
+}
\ No newline at end of file
diff --git a/src/Classic/AbsBeamline/Stripper.h b/src/Classic/AbsBeamline/Stripper.h
index f08dbd569782698a09f4cc8abc197ee5c6f0a796..70f19a44e95f4c365ce9f4ea25c7b28c09ad391e 100644
--- a/src/Classic/AbsBeamline/Stripper.h
+++ b/src/Classic/AbsBeamline/Stripper.h
@@ -42,14 +42,8 @@ public:
     /// Apply visitor to Stripper.
     virtual void accept(BeamlineVisitor &) const;
 
-    virtual bool apply(const size_t &i, const double &t, double E[], double B[]);
-
-    virtual bool apply(const size_t &i, const double &t, Vector_t &E, Vector_t &B);
-
-    virtual bool apply(const Vector_t &R, const Vector_t &centroid, const double &t, Vector_t &E, Vector_t &B);
-
-    virtual void initialise(PartBunch *bunch, double &startField, double &endField, const double &scaleFactor);
-    virtual void initialise(PartBunch *bunch, const double &scaleFactor);
+    virtual void initialise(PartBunch *bunch, double &startField, double &endField);
+    virtual void initialise(PartBunch *bunch);
 
     virtual void finalise();
 
diff --git a/src/Classic/AbsBeamline/TravelingWave.cpp b/src/Classic/AbsBeamline/TravelingWave.cpp
index 55f020932141fa73e9f2251ba8751067f502326a..141d5cf883885d753f206d5ecd7cfd37d65597a9 100644
--- a/src/Classic/AbsBeamline/TravelingWave.cpp
+++ b/src/Classic/AbsBeamline/TravelingWave.cpp
@@ -38,13 +38,16 @@ TravelingWave::TravelingWave():
     CoreFilename_m(""),
     CoreFieldmap_m(NULL),
     scale_m(1.0),
+    scaleError_m(0.0),
     scaleCore_m(1.0),
+    scaleCoreError_m(0.0),
     phase_m(0.0),
     phaseCore1_m(0.0),
     phaseCore2_m(0.0),
     phaseExit_m(0.0),
+    phaseError_m(0.0),
     frequency_m(0.0),
-    startField_m(0.0),
+    length_m(0.0),
     startCoreField_m(0.0),
     startExitField_m(0.0),
     mappedStartExitField_m(0.0),
@@ -53,7 +56,8 @@ TravelingWave::TravelingWave():
     CellLength_m(0.0),
     Mode_m(1),
     fast_m(false),
-    autophaseVeto_m(false)
+    autophaseVeto_m(false),
+    designEnergy_m(-1.0)
 {}
 
 
@@ -62,13 +66,16 @@ TravelingWave::TravelingWave(const TravelingWave &right):
     CoreFilename_m(right.CoreFilename_m),
     CoreFieldmap_m(NULL),
     scale_m(right.scale_m),
+    scaleError_m(right.scaleError_m),
     scaleCore_m(right.scaleCore_m),
+    scaleCoreError_m(right.scaleCoreError_m),
     phase_m(right.phase_m),
     phaseCore1_m(right.phaseCore1_m),
     phaseCore2_m(right.phaseCore2_m),
     phaseExit_m(right.phaseExit_m),
+    phaseError_m(right.phaseError_m),
     frequency_m(right.frequency_m),
-    startField_m(right.startField_m),
+    length_m(right.length_m),
     startCoreField_m(right.startCoreField_m),
     startExitField_m(right.startExitField_m),
     mappedStartExitField_m(right.mappedStartExitField_m),
@@ -77,7 +84,8 @@ TravelingWave::TravelingWave(const TravelingWave &right):
     CellLength_m(right.CellLength_m),
     Mode_m(right.Mode_m),
     fast_m(right.fast_m),
-    autophaseVeto_m(right.autophaseVeto_m)
+    autophaseVeto_m(right.autophaseVeto_m),
+    designEnergy_m(right.designEnergy_m)
 {}
 
 
@@ -86,13 +94,16 @@ TravelingWave::TravelingWave(const std::string &name):
     CoreFilename_m(""),
     CoreFieldmap_m(NULL),
     scale_m(1.0),
+    scaleError_m(0.0),
     scaleCore_m(1.0),
+    scaleCoreError_m(0.0),
     phase_m(0.0),
     phaseCore1_m(0.0),
     phaseCore2_m(0.0),
     phaseExit_m(0.0),
+    phaseError_m(0.0),
     frequency_m(0.0),
-    startField_m(0.0),
+    length_m(0.0),
     startCoreField_m(0.0),
     startExitField_m(0.0),
     mappedStartExitField_m(0.0),
@@ -101,7 +112,8 @@ TravelingWave::TravelingWave(const std::string &name):
     CellLength_m(0.0),
     Mode_m(1),
     fast_m(false),
-    autophaseVeto_m(false)
+    autophaseVeto_m(false),
+    designEnergy_m(-1.0)
 {}
 
 
@@ -116,74 +128,6 @@ void TravelingWave::accept(BeamlineVisitor &visitor) const {
     visitor.visitTravelingWave(*this);
 }
 
-void TravelingWave::setFieldMapFN(std::string fn) {
-    CoreFilename_m = fn;
-}
-
-// void TravelingWave::setEntryFieldMapFN(std::string fn)
-// {
-//   EntryFilename_m = fn;
-// }
-
-// void TravelingWave::setExitFieldMapFN(std::string fn)
-// {
-//   ExitFilename_m = fn;
-// }
-
-std::string TravelingWave::getFieldMapFN() const {
-    return CoreFilename_m;
-}
-
-void TravelingWave::setAmplitudem(double vPeak) {
-    scale_m = vPeak;
-}
-
-void TravelingWave::setFrequencym(double freq) {
-    frequency_m = freq;
-}
-
-
-double TravelingWave::getFrequencym() const {
-    return frequency_m;
-}
-
-
-void TravelingWave::setPhasem(double phase) {
-    using Physics::pi;
-
-    phase_m = phase;
-    phaseCore1_m = phase_m + pi * Mode_m / 2.0;
-    phaseCore2_m = phase_m + pi * Mode_m * 1.5;
-    phaseExit_m = phase_m - 2.0 * pi * ((NumCells_m - 1) * Mode_m - std::floor((NumCells_m - 1) * Mode_m));
-}
-
-double TravelingWave::getPhasem() const {
-    return phase_m;
-}
-
-void TravelingWave::setNumCells(int NumCells) {
-    NumCells_m = NumCells;
-}
-
-void TravelingWave::setFast(bool fast) {
-    fast_m = fast;
-}
-
-
-bool TravelingWave::getFast() const {
-    return fast_m;
-}
-
-void TravelingWave::setAutophaseVeto(bool veto) {
-    autophaseVeto_m = veto;
-}
-
-
-bool TravelingWave::getAutophaseVeto() const {
-    return autophaseVeto_m;
-}
-
-
 /**
  * ENVELOPE COMPONENT for radial focussing of the beam
  * Calculates the transverse envelope component for the traveling wave
@@ -194,7 +138,7 @@ void TravelingWave::addKR(int i, double t, Vector_t &K) {
 
     Vector_t tmpE(0.0, 0.0, 0.0), tmpB(0.0, 0.0, 0.0);
     Vector_t tmpE_diff(0.0, 0.0, 0.0), tmpB_diff(0.0, 0.0, 0.0);
-    Vector_t tmpA0(RefPartBunch_m->getX(i) - dx_m, RefPartBunch_m->getY(i) - dy_m, RefPartBunch_m->getZ(i) - startField_m);
+    Vector_t tmpA0(RefPartBunch_m->getX(i), RefPartBunch_m->getY(i), RefPartBunch_m->getZ(i) - 0.5 * PeriodLength_m);
 
     double g = RefPartBunch_m->getGamma(i);
     double b = RefPartBunch_m->getBeta(i);
@@ -268,8 +212,8 @@ void TravelingWave::addKT(int i, double t, Vector_t &K) {
     double oldK = tempK(0);
 
     //get coordinates
-    double dx = RefPartBunch_m->getX0(i) - dx_m;
-    double dy = RefPartBunch_m->getY0(i) - dy_m;
+    double dx = RefPartBunch_m->getX0(i);
+    double dy = RefPartBunch_m->getY0(i);
 
     K += Vector_t(oldK * dx, oldK * dy, 0.0);
 }
@@ -306,43 +250,32 @@ void TravelingWave::addKT(int i, double t, Vector_t &K) {
 */
 
 
-bool TravelingWave::apply(const size_t &i, const double &t, double E[], double B[]) {
-    Vector_t Ev(0, 0, 0), Bv(0, 0, 0);
-    Vector_t Rt(RefPartBunch_m->getX(i), RefPartBunch_m->getY(i), RefPartBunch_m->getZ(i));
-    if(apply(Rt, Vector_t(0.0), t, Ev, Bv)) return true;
-
-    E[0] = Ev(0);
-    E[1] = Ev(1);
-    E[2] = Ev(2);
-    B[0] = Bv(0);
-    B[1] = Bv(1);
-    B[2] = Bv(2);
-
-    return false;
+bool TravelingWave::apply(const size_t &i, const double &t, Vector_t &E, Vector_t &B) {
+    return apply(RefPartBunch_m->R[i], RefPartBunch_m->P[i], t, E, B);
 }
 
-bool TravelingWave::apply(const size_t &i, const double &t, Vector_t &E, Vector_t &B) {
+bool TravelingWave::apply(const Vector_t &R, const Vector_t &P, const double &t, Vector_t &E, Vector_t &B) {
+    Vector_t tmpR = R - Vector_t(0, 0, 0.5 * PeriodLength_m);
     double tmpcos, tmpsin;
-
-    Vector_t tmpR(RefPartBunch_m->getX(i) - dx_m, RefPartBunch_m->getY(i) - dy_m , RefPartBunch_m->getZ(i) - startField_m);
     Vector_t tmpE(0.0, 0.0, 0.0), tmpB(0.0, 0.0, 0.0);
-    bool out_of_bounds = false;
 
+    if (tmpR(2) < 0.0 && tmpR(2) >= length_m) return false;
+    if (!CoreFieldmap_m->isInside(tmpR)) return true;
 
-    if(tmpR(2) < startCoreField_m) {
-        tmpcos =  scale_m * cos(frequency_m * t + phase_m);
-        tmpsin = -scale_m * sin(frequency_m * t + phase_m);
+    if (tmpR(2) < startCoreField_m) {
+        tmpcos =  (scale_m + scaleError_m) * cos(frequency_m * t + phase_m + phaseError_m);
+        tmpsin = -(scale_m + scaleError_m) * sin(frequency_m * t + phase_m + phaseError_m);
 
-    } else if(tmpR(2) < startExitField_m) {
+    } else if (tmpR(2) < startExitField_m) {
         Vector_t tmpE2(0.0, 0.0, 0.0), tmpB2(0.0, 0.0, 0.0);
         tmpR(2) -= startCoreField_m;
         const double z = tmpR(2);
         tmpR(2) = tmpR(2) - PeriodLength_m * floor(tmpR(2) / PeriodLength_m);
         tmpR(2) += startCoreField_m;
 
-        tmpcos =  scaleCore_m * cos(frequency_m * t + phaseCore1_m);
-        tmpsin = -scaleCore_m * sin(frequency_m * t + phaseCore1_m);
-        out_of_bounds = CoreFieldmap_m->getFieldstrength(tmpR, tmpE, tmpB);
+        tmpcos =  (scaleCore_m + scaleCoreError_m) * cos(frequency_m * t + phaseCore1_m + phaseError_m);
+        tmpsin = -(scaleCore_m + scaleCoreError_m) * sin(frequency_m * t + phaseCore1_m + phaseError_m);
+        CoreFieldmap_m->getFieldstrength(R, tmpE, tmpB);
         E += tmpcos * tmpE;
         B += tmpsin * tmpB;
 
@@ -353,34 +286,36 @@ bool TravelingWave::apply(const size_t &i, const double &t, Vector_t &E, Vector_
         tmpR(2) = tmpR(2) - PeriodLength_m * floor(tmpR(2) / PeriodLength_m);
         tmpR(2) += startCoreField_m;
 
-        tmpcos =  scaleCore_m * cos(frequency_m * t + phaseCore2_m);
-        tmpsin = -scaleCore_m * sin(frequency_m * t + phaseCore2_m);
+        tmpcos =  (scaleCore_m + scaleCoreError_m) * cos(frequency_m * t + phaseCore2_m + phaseError_m);
+        tmpsin = -(scaleCore_m + scaleCoreError_m) * sin(frequency_m * t + phaseCore2_m + phaseError_m);
 
     } else {
-        tmpcos =  scale_m * cos(frequency_m * t + phaseExit_m);
-        tmpsin = -scale_m * sin(frequency_m * t + phaseExit_m);
+        tmpcos =  (scale_m + scaleError_m) * cos(frequency_m * t + phaseExit_m + phaseError_m);
+        tmpsin = -(scale_m + scaleError_m) * sin(frequency_m * t + phaseExit_m + phaseError_m);
         tmpR(2) -= mappedStartExitField_m;
-
     }
 
-    out_of_bounds = out_of_bounds || CoreFieldmap_m->getFieldstrength(tmpR, tmpE, tmpB);
+    CoreFieldmap_m->getFieldstrength(tmpR, tmpE, tmpB);
+
     E += tmpcos * tmpE;
     B += tmpsin * tmpB;
 
-    return out_of_bounds;
+    return false;
 }
 
-bool TravelingWave::apply(const Vector_t &R, const Vector_t &centroid, const double &t, Vector_t &E, Vector_t &B) {
+bool TravelingWave::applyToReferenceParticle(const Vector_t &R, const Vector_t &P, const double &t, Vector_t &E, Vector_t &B) {
     double tmpcos, tmpsin;
-    Vector_t tmpR(R(0) - dx_m, R(1) - dy_m , R(2) - startField_m);
     Vector_t tmpE(0.0, 0.0, 0.0), tmpB(0.0, 0.0, 0.0);
-    bool out_of_bounds = false;
 
+    Vector_t tmpR(R(0), R(1), R(2) - 0.5 * PeriodLength_m);
+    if (tmpR(2) < 0.0 && tmpR(2) >= length_m) return false;
+    if (!CoreFieldmap_m->isInside(tmpR)) return true;
 
-    if(tmpR(2) < startCoreField_m) {
+    if (tmpR(2) < startCoreField_m) {
         tmpcos =  scale_m * cos(frequency_m * t + phase_m);
         tmpsin = -scale_m * sin(frequency_m * t + phase_m);
-    } else if(tmpR(2) < startExitField_m) {
+
+    } else if (tmpR(2) < startExitField_m) {
         Vector_t tmpE2(0.0, 0.0, 0.0), tmpB2(0.0, 0.0, 0.0);
         tmpR(2) -= startCoreField_m;
         const double z = tmpR(2);
@@ -389,7 +324,7 @@ bool TravelingWave::apply(const Vector_t &R, const Vector_t &centroid, const dou
 
         tmpcos =  scaleCore_m * cos(frequency_m * t + phaseCore1_m);
         tmpsin = -scaleCore_m * sin(frequency_m * t + phaseCore1_m);
-        out_of_bounds = CoreFieldmap_m->getFieldstrength(tmpR, tmpE, tmpB);
+        CoreFieldmap_m->getFieldstrength(R, tmpE, tmpB);
         E += tmpcos * tmpE;
         B += tmpsin * tmpB;
 
@@ -409,18 +344,24 @@ bool TravelingWave::apply(const Vector_t &R, const Vector_t &centroid, const dou
         tmpR(2) -= mappedStartExitField_m;
     }
 
-    out_of_bounds = out_of_bounds || CoreFieldmap_m->getFieldstrength(tmpR, tmpE, tmpB);
+    CoreFieldmap_m->getFieldstrength(tmpR, tmpE, tmpB);
+
     E += tmpcos * tmpE;
     B += tmpsin * tmpB;
 
-    return out_of_bounds;
-
+    return false;
 }
 
-void TravelingWave::initialise(PartBunch *bunch, double &startField, double &endField, const double &scaleFactor) {
+void TravelingWave::initialise(PartBunch *bunch, double &startField, double &endField) {
     using Physics::pi;
     using Physics::two_pi;
 
+    if (bunch == NULL) {
+        startField = - 0.5 * PeriodLength_m;
+        endField = startExitField_m;
+        return;
+    }
+
     Inform msg("TravelingWave ", *gmsg);
     std::stringstream errormsg;
 
@@ -448,20 +389,6 @@ void TravelingWave::initialise(PartBunch *bunch, double &startField, double &end
                 frequency_m = CoreFieldmap_m->getFrequency();
             }
 
-
-            /**
-               NOT needed anymore in the new AUTOPHASE procedure
-               const double dPhi = OpalData::getInstance()->getGlobalPhaseShift() * frequency_m;
-
-               msg << "Global Phase-Shift is " << dPhi / two_pi * 360.0 << " (deg)"
-               << " old phase = " << phase_m << " (rad) ";
-               phase_m -= dPhi;
-               msg << "new phase = " << phase_m << " (rad) " << endl;
-            */
-
-            if(dx_m > 1e-10 || dy_m > 1e-10)
-                msg << level2 << "misaligned by dx = " << dx_m << ", dy = " << dy_m << endl;
-
             if(hasAttribute("MODE")) {
                 Mode_m = getAttribute("MODE");
             } else {
@@ -485,11 +412,12 @@ void TravelingWave::initialise(PartBunch *bunch, double &startField, double &end
             startExitField_m = startCoreField_m + (NumCells_m - 1) * CellLength_m;
             mappedStartExitField_m = startExitField_m - 3.0 * PeriodLength_m / 2.0;
 
-            startField -= PeriodLength_m / 2.0;
+            startField = -PeriodLength_m / 2.0;
             endField = startField + startExitField_m + PeriodLength_m / 2.0;
-            startField_m = startField;
+            length_m = endField - startField;
 
             scaleCore_m = scale_m / sin(2.0 * pi * Mode_m);
+            scaleCoreError_m = scaleError_m / sin(2.0 * pi * Mode_m);
             phaseCore1_m = phase_m + pi * Mode_m / 2.0;
             phaseCore2_m = phase_m + pi * Mode_m * 1.5;
             phaseExit_m = phase_m - 2.0 * pi * ((NumCells_m - 1) * Mode_m - floor((NumCells_m - 1) * Mode_m));
@@ -520,8 +448,8 @@ void TravelingWave::goOffline() {
 }
 
 void TravelingWave::getDimensions(double &zBegin, double &zEnd) const {
-    zBegin = startField_m;
-    zEnd = startField_m + (NumCells_m - 1) * CellLength_m + PeriodLength_m;
+    zBegin = -0.5 * PeriodLength_m;
+    zEnd = zBegin + length_m;
 }
 
 
@@ -752,4 +680,8 @@ std::pair<double, double> TravelingWave::trackOnAxisParticle(const double &p0,
     const double tErr  = (z - (startExitField_m + 0.5 * PeriodLength_m + zbegin)) / (Physics::c * beta);
 
     return std::pair<double, double>(p, t - tErr);
-}
\ No newline at end of file
+}
+
+bool TravelingWave::isInside(const Vector_t &r) const {
+    return (isInsideTransverse(r) && r(2) >= -0.5 * PeriodLength_m && r(2) < startExitField_m);
+}
diff --git a/src/Classic/AbsBeamline/TravelingWave.h b/src/Classic/AbsBeamline/TravelingWave.h
index fb72946669a68e7f6c6ee8696cd53a0647845cb6..86a3140f96fc0ac67550defecd696201e9636deb 100644
--- a/src/Classic/AbsBeamline/TravelingWave.h
+++ b/src/Classic/AbsBeamline/TravelingWave.h
@@ -71,22 +71,25 @@ public:
 
     bool getFast() const;
 
-    void setAutophaseVeto(bool veto);
+    void setAutophaseVeto(bool veto = true);
 
     bool getAutophaseVeto() const;
 
     void setAmplitudem(double vPeak);
+    void setAmplitudeError(double voltError);
+    double getAmplitudem() const;
+    double getAmplitudeError() const;
 
     void setFrequencym(double freq);
-
     double getFrequencym() const;
 
     void setPhasem(double phase);
+    void setPhaseError(double phaseError);
+    double getPhasem() const;
+    double getPhaseError() const;
 
     void updatePhasem(double phase);
 
-    double getPhasem() const;
-
     void setNumCells(int NumCells);
 
     double getAutoPhaseEstimate(const double & E0, const double & t0, const double & q, const double & m);
@@ -101,13 +104,13 @@ public:
 
     virtual void addKT(int i, double t, Vector_t &K);
 
-    virtual bool apply(const size_t &i, const double &t, double E[], double B[]);
-
     virtual bool apply(const size_t &i, const double &t, Vector_t &E, Vector_t &B);
 
-    virtual bool apply(const Vector_t &R, const Vector_t &centroid, const double &t, Vector_t &E, Vector_t &B);
+    virtual bool apply(const Vector_t &R, const Vector_t &P, const double &t, Vector_t &E, Vector_t &B);
 
-    virtual void initialise(PartBunch *bunch, double &startField, double &endField, const double &scaleFactor);
+    virtual bool applyToReferenceParticle(const Vector_t &R, const Vector_t &P, const double &t, Vector_t &E, Vector_t &B);
+
+    virtual void initialise(PartBunch *bunch, double &startField, double &endField);
 
     virtual void finalise();
 
@@ -121,6 +124,10 @@ public:
 
     virtual void getDimensions(double &zBegin, double &zEnd) const;
 
+    virtual bool isInside(const Vector_t &r) const;
+
+    virtual void setDesignEnergy(double ekin);
+    virtual double getDesignEnergy() const;
 private:
     std::string CoreFilename_m;             /**< The name of the inputfile*/
     /*   std::string EntryFilename_m; */
@@ -132,15 +139,18 @@ private:
 
     double scale_m;              /**< scale multiplier*/
     double scaleCore_m;
+    double scaleError_m;
+    double scaleCoreError_m;
 
     double phase_m;              /**< phase shift of time varying field(degrees)*/
     double phaseCore1_m;
     double phaseCore2_m;
     double phaseExit_m;
+    double phaseError_m;
 
     double frequency_m;          /**< Read in frequency of time varying field(MHz)*/
 
-    double startField_m;
+    double length_m;
     double startCoreField_m;         /**< starting point of field(m)*/
     double startExitField_m;
     double mappedStartExitField_m;
@@ -153,6 +163,7 @@ private:
     bool fast_m;
 
     bool autophaseVeto_m;
+    double designEnergy_m;
 
     inline double getdE(const int & i,
                         const int & I,
@@ -246,4 +257,107 @@ double TravelingWave::getdB(const int & i,
          (F[I].second - F[I-1].second) * (cos(frequency_m * t[i] + phi) - cos(frequency_m * t[i-1] + phi)));
 }
 
+
+inline
+void TravelingWave::setDesignEnergy(double ekin)
+{
+    designEnergy_m = ekin;
+}
+
+inline
+double TravelingWave::getDesignEnergy() const
+{
+    return designEnergy_m;
+}
+
+inline
+void TravelingWave::setFieldMapFN(std::string fn) {
+    CoreFilename_m = fn;
+}
+
+inline
+std::string TravelingWave::getFieldMapFN() const {
+    return CoreFilename_m;
+}
+
+inline
+void TravelingWave::setAmplitudem(double vPeak) {
+    scale_m = vPeak;
+}
+
+inline
+void TravelingWave::setAmplitudeError(double voltError) {
+    scaleError_m = voltError;
+}
+
+inline
+double TravelingWave::getAmplitudem() const {
+    return scale_m;
+}
+
+inline
+double TravelingWave::getAmplitudeError() const {
+    return scaleError_m;
+}
+
+inline
+void TravelingWave::setFrequencym(double freq) {
+    frequency_m = freq;
+}
+
+inline
+double TravelingWave::getFrequencym() const {
+    return frequency_m;
+}
+
+inline
+void TravelingWave::setPhasem(double phase) {
+    using Physics::pi;
+
+    phase_m = phase;
+    phaseCore1_m = phase_m + pi * Mode_m / 2.0;
+    phaseCore2_m = phase_m + pi * Mode_m * 1.5;
+    phaseExit_m = phase_m - 2.0 * pi * ((NumCells_m - 1) * Mode_m - std::floor((NumCells_m - 1) * Mode_m));
+}
+
+inline
+void TravelingWave::setPhaseError(double phaseError) {
+    phaseError_m = phaseError;
+}
+
+inline
+double TravelingWave::getPhasem() const {
+    return phase_m;
+}
+
+inline
+double TravelingWave::getPhaseError() const {
+    return phaseError_m;
+}
+
+inline
+void TravelingWave::setNumCells(int NumCells) {
+    NumCells_m = NumCells;
+}
+
+inline
+void TravelingWave::setFast(bool fast) {
+    fast_m = fast;
+}
+
+inline
+bool TravelingWave::getFast() const {
+    return fast_m;
+}
+
+inline
+void TravelingWave::setAutophaseVeto(bool veto) {
+    autophaseVeto_m = veto;
+}
+
+inline
+bool TravelingWave::getAutophaseVeto() const {
+    return autophaseVeto_m;
+}
+
 #endif // CLASSIC_TravelingWave_HH
diff --git a/src/Classic/AbsBeamline/VariableRFCavity.cpp b/src/Classic/AbsBeamline/VariableRFCavity.cpp
index 283128180655c8daaa9e3df0eadfa26294d8767e..c61573808a2bd936441fb8e3edcb96073b5d5c05 100644
--- a/src/Classic/AbsBeamline/VariableRFCavity.cpp
+++ b/src/Classic/AbsBeamline/VariableRFCavity.cpp
@@ -141,25 +141,8 @@ const EMField &VariableRFCavity::getField() const {
 
 
 bool VariableRFCavity::apply(const size_t &i, const double &t,
-                    Vector_t &E, Vector_t &B) {
-    return apply(RefPartBunch_m->R[i], RefPartBunch_m->get_centroid(), t,
-                 E, B);
-}
-
-bool VariableRFCavity::apply(const size_t &i, const double &t, double E[], double B[]) {
-    Vector_t Ev(0, 0, 0), Bv(0, 0, 0);
-
-    if (apply(i, t, Ev, Bv))
-        return true;
-
-    E[0] = Ev(0);
-    E[1] = Ev(1);
-    E[2] = Ev(2);
-    B[0] = Bv(0);
-    B[1] = Bv(1);
-    B[2] = Bv(2);
-
-    return false;
+                             Vector_t &E, Vector_t &B) {
+    return apply(RefPartBunch_m->R[i], RefPartBunch_m->P[i], t, E, B);
 }
 
 // If this is too slow: a quicker implementation would be to use templates not
@@ -168,22 +151,41 @@ bool VariableRFCavity::apply(const size_t &i, const double &t, double E[], doubl
 //
 // Do I need bound checking here? I have no "radius" parameter, but I do have a
 // "length".
-bool VariableRFCavity::apply(const Vector_t &R, const Vector_t &centroid,
-           const double &t, Vector_t &E, Vector_t &B) {
+bool VariableRFCavity::apply(const Vector_t &R, const Vector_t &P,
+                             const double &t, Vector_t &E, Vector_t &B) {
+    // std::cerr << "VariableRFCavity::apply " << R[0] << " " << R[1] << " " << R[2] << " * " << halfWidth_m << " " << halfHeight_m << std::endl;
+    if (R[2] >= 0. && R[2] < _length) {
+        if (std::abs(R[0]) > halfWidth_m || std::abs(R[1]) > halfHeight_m) {
+            return true;
+        }
+
+        double E0 = _amplitude_td->getValue(t);
+        double f = _frequency_td->getValue(t);
+        double phi = _phase_td->getValue(t);
+        E = Vector_t(0., 0., E0*sin(Physics::two_pi * f * t + phi));
+    // std::cerr << "                        t: " << t << " f: " << f << " phi: " << phi << " E0: " << E0 << " E[2]: " << E[2] << std::endl;
+    }
+    return false;
+}
+
+bool VariableRFCavity::applyToReferenceParticle(const Vector_t &R, const Vector_t &P,
+                                                const double &t, Vector_t &E, Vector_t &B) {
     // std::cerr << "VariableRFCavity::apply " << R[0] << " " << R[1] << " " << R[2] << " * " << halfWidth_m << " " << halfHeight_m << std::endl;
-    if (R[2] < 0. || R[2] > _length ||
-        fabs(R[0]) > halfWidth_m || fabs(R[1]) > halfHeight_m)
-        return true;
-    double E0 = _amplitude_td->getValue(t);
-    double f = _frequency_td->getValue(t);
-    double phi = _phase_td->getValue(t);
-    E = Vector_t(0., 0., E0*sin(Physics::two_pi*f*t+phi));
+    if (R[2] >= 0. && R[2] < _length) {
+        if (std::abs(R[0]) > halfWidth_m || std::abs(R[1]) > halfHeight_m) {
+            return true;
+        }
+
+        double E0 = _amplitude_td->getValue(t);
+        double f = _frequency_td->getValue(t);
+        double phi = _phase_td->getValue(t);
+        E = Vector_t(0., 0., E0*sin(Physics::two_pi * f * t + phi));
     // std::cerr << "                        t: " << t << " f: " << f << " phi: " << phi << " E0: " << E0 << " E[2]: " << E[2] << std::endl;
+    }
     return false;
 }
 
-void VariableRFCavity::initialise(PartBunch *bunch, double &startField, double &endField,
-                const double &scaleFactor) {
+void VariableRFCavity::initialise(PartBunch *bunch, double &startField, double &endField) {
     RefPartBunch_m = bunch;
 }
 
@@ -216,4 +218,4 @@ void VariableRFCavity::accept(BeamlineVisitor& visitor) const {
 void VariableRFCavity::setLength(double length) {
     _length = length;
     geometry.setElementLength(length);
-}
+}
\ No newline at end of file
diff --git a/src/Classic/AbsBeamline/VariableRFCavity.h b/src/Classic/AbsBeamline/VariableRFCavity.h
index fa10dba34fa08156bb3b0c54f863a968dcefb1bd..1bbb1d16e0f59f76a5df5d83bbf0eef1bbc06129 100644
--- a/src/Classic/AbsBeamline/VariableRFCavity.h
+++ b/src/Classic/AbsBeamline/VariableRFCavity.h
@@ -59,10 +59,10 @@ class VariableRFCavity: public Component {
 
     virtual ElementBase* clone() const;
 
-    virtual bool apply(const size_t &i, const double &t, double E[], double B[]);
     virtual bool apply(const size_t &i, const double &t, Vector_t &E, Vector_t &B);
-    virtual bool apply(const Vector_t &R, const Vector_t &centroid, const double &t, Vector_t &E, Vector_t &B);
-    virtual void initialise(PartBunch *bunch, double &startField, double &endField, const double &scaleFactor);
+    virtual bool apply(const Vector_t &R, const Vector_t &P, const double &t, Vector_t &E, Vector_t &B);
+    virtual bool applyToReferenceParticle(const Vector_t &R, const Vector_t &P, const double &t, Vector_t &E, Vector_t &B);
+    virtual void initialise(PartBunch *bunch, double &startField, double &endField);
     virtual void finalise();
     virtual bool bends() const {return false;}
     virtual void getDimensions(double &zBegin, double &zEnd) const {}
@@ -133,4 +133,4 @@ double VariableRFCavity::getFrequency(double time) const {
 }
 
 
-#endif // CLASSIC_VirtualRFCavity_HH
+#endif // CLASSIC_VirtualRFCavity_HH
\ No newline at end of file
diff --git a/src/Classic/Algebra/CMakeLists.txt b/src/Classic/Algebra/CMakeLists.txt
index c738d1118b38e04880a06f51fcfc6a1a1994ff07..fc685f96280571f9cf22ebaf2c12883b3f699b46 100644
--- a/src/Classic/Algebra/CMakeLists.txt
+++ b/src/Classic/Algebra/CMakeLists.txt
@@ -15,4 +15,31 @@ include_directories (
   ${CMAKE_CURRENT_SOURCE_DIR}
   )
 
-add_sources(${_SRCS})
\ No newline at end of file
+ADD_OPAL_SOURCES(${_SRCS})
+
+set (HDRS
+    Array1D.h
+    Array2D.h
+    ComplexEigen.h
+    DoubleEigen.h
+    DynamicFixedPoint.h
+    LieMap.h
+    LUMatrix.h
+    Matrix.h
+    NormalForm.h
+    SliceIterator.h
+    StaticFixedPoint.h
+    TpsData.h
+    Tps.h
+    Tps.hpp
+    TpsMath.h
+    TpsMonomial.h
+    TpsSubstitution.h
+    Vector.h
+    Vps.h
+    Vps.hpp
+    VpsInvMap.h
+    VpsMap.h
+)
+
+install (FILES ${HDRS} DESTINATION "${CMAKE_INSTALL_PREFIX}/include/Algebra")
\ No newline at end of file
diff --git a/src/Classic/Algorithms/CMakeLists.txt b/src/Classic/Algorithms/CMakeLists.txt
index 7a6eb9f37ffe9ea213bc40b0fe89d61bb59b98c4..cd9c0411a218f602919ab84370a2d3aaf42bdb58 100644
--- a/src/Classic/Algorithms/CMakeLists.txt
+++ b/src/Classic/Algorithms/CMakeLists.txt
@@ -2,6 +2,7 @@ set (_SRCS
   AbstractMapper.cpp
   AbstractTimeDependence.cpp
   AbstractTracker.cpp
+  CoordinateSystemTrafo.cpp
   DefaultVisitor.cpp
   Flagger.cpp
   IdealMapper.cpp
@@ -20,11 +21,44 @@ set (_SRCS
   ThinTracker.cpp
   TrackIntegrator.cpp
   Tracker.cpp
-  Vektor.cpp
+  Quaternion.cpp
   )
 
 include_directories (
   ${CMAKE_CURRENT_SOURCE_DIR}
   )
 
-add_sources(${_SRCS})
+ADD_OPAL_SOURCES(${_SRCS})
+
+set (HDRS
+    AbstractMapper.h
+    AbstractTimeDependence.h
+    AbstractTracker.h
+    CoordinateSystemTrafo.h
+    DefaultVisitor.h
+    Flagger.h
+    IdealMapper.h
+    LinearMapper.h
+    ListElem.h
+    MapIntegrator.h
+    Mapper.h
+    OrbitTracker.h
+    PartBinsCyc.h
+    PartBins.h
+    PartBunch.h
+    PartData.h
+    Particle.h
+    PartPusher.h
+    PBunchDefs.h
+    PolynomialTimeDependence.h
+    Quaternion.h
+    rbendmap.h
+    Surveyor.h
+    ThinMapper.h
+    ThinTracker.h
+    Tracker.h
+    TrackIntegrator.h
+    Vektor.h
+)
+
+install (FILES ${HDRS} DESTINATION "${CMAKE_INSTALL_PREFIX}/include/Algorithms")
\ No newline at end of file
diff --git a/src/Classic/Algorithms/DefaultVisitor.cpp b/src/Classic/Algorithms/DefaultVisitor.cpp
index 592bbc96e6a1c0dc73c4f2d5989b66b5e630d3dd..dd61ba654a5bf209b98796c2a5cb4f179d37de31 100644
--- a/src/Classic/Algorithms/DefaultVisitor.cpp
+++ b/src/Classic/Algorithms/DefaultVisitor.cpp
@@ -37,6 +37,7 @@
 #include "AbsBeamline/Patch.h"
 #include "AbsBeamline/Probe.h"
 #include "AbsBeamline/RBend.h"
+#include "AbsBeamline/RBend3D.h"
 #include "AbsBeamline/RFCavity.h"
 #include "AbsBeamline/VariableRFCavity.h"
 #include "AbsBeamline/TravelingWave.h"
@@ -46,6 +47,7 @@
 #include "AbsBeamline/Separator.h"
 #include "AbsBeamline/Septum.h"
 #include "AbsBeamline/Solenoid.h"
+#include "AbsBeamline/Source.h"
 #include "AbsBeamline/ParallelPlate.h"
 #include "AbsBeamline/CyclotronValley.h"
 #include "AbsBeamline/Stripper.h"
@@ -160,6 +162,9 @@ void DefaultVisitor::visitRBend(const RBend &bend) {
     applyDefault(bend);
 }
 
+void DefaultVisitor::visitRBend3D(const RBend3D &bend) {
+    applyDefault(bend);
+}
 
 void DefaultVisitor::visitVariableRFCavity(const VariableRFCavity &vcav) {
     applyDefault(vcav);
@@ -204,6 +209,10 @@ void DefaultVisitor::visitSolenoid(const Solenoid &sol) {
     applyDefault(sol);
 }
 
+void DefaultVisitor::visitSource(const Source &sou) {
+    applyDefault(sou);
+}
+
 void DefaultVisitor::visitParallelPlate(const ParallelPlate &pplate) {
     applyDefault(pplate);
 }
@@ -283,4 +292,4 @@ void DefaultVisitor::visitTrackIntegrator(const TrackIntegrator &i) {
 
 
 void DefaultVisitor::applyDefault(const ElementBase &)
-{}
+{}
\ No newline at end of file
diff --git a/src/Classic/Algorithms/DefaultVisitor.h b/src/Classic/Algorithms/DefaultVisitor.h
index c9dfb1a730c254cc75f8488d7a2d9104aefe4b3b..5275c34a939539c64149c991b2d35f3b9e2a25d3 100644
--- a/src/Classic/Algorithms/DefaultVisitor.h
+++ b/src/Classic/Algorithms/DefaultVisitor.h
@@ -102,6 +102,9 @@ public:
     /// Apply the algorithm to a rectangular bend.
     virtual void visitRBend(const RBend &);
 
+    /// Apply the algorithm to a rectangular bend.
+    virtual void visitRBend3D(const RBend3D &);
+
     /// Apply the algorithm to a RF cavity.
     virtual void visitVariableRFCavity(const VariableRFCavity &vcav);
 
@@ -129,6 +132,9 @@ public:
     /// Apply the algorithm to a solenoid.
     virtual void visitSolenoid(const Solenoid &);
 
+    /// Apply the algorithm to a source.
+    virtual void visitSource(const Source &);
+
     /// Apply the algorithm to a ParallelPlate.
     virtual void visitParallelPlate(const ParallelPlate &);
 
@@ -203,4 +209,4 @@ private:
     bool local_flip;
 };
 
-#endif // CLASSIC_DefaultVisitor_HH
+#endif // CLASSIC_DefaultVisitor_HH
\ No newline at end of file
diff --git a/src/Classic/Algorithms/PartBins.cpp b/src/Classic/Algorithms/PartBins.cpp
index 93c7f82e456fa3462e72fe56d41e45cd4b1bdee1..0d9ce8e1ea565c3ca5dc4ac1425e1f20f6c7fc96 100644
--- a/src/Classic/Algorithms/PartBins.cpp
+++ b/src/Classic/Algorithms/PartBins.cpp
@@ -63,19 +63,15 @@ void PartBins::updateStatus(const int bunchCount, const size_t partInBin) {
 }
 
 void PartBins::updateDeletedPartsInBin(size_t countLost[]) {
-    Inform m2all("updateDeletedPartsInBin ", INFORM_ALL_NODES);
+    Inform msg("updateDeletedPartsInBin ");
 
-    for(int ii = 0; ii < getLastemittedBin(); ii++) {
-        bool flagNeedUpdate = false;
-        flagNeedUpdate = (countLost[ii] > 0);
-
-        reduce(flagNeedUpdate, flagNeedUpdate, OpOr());
-
-        if(flagNeedUpdate) {
-            reduce(countLost[ii], countLost[ii], OpAddAssign());
+    const int lastEmittedBin = getLastemittedBin();
+    reduce(&(countLost[0]), &(countLost[0]) + lastEmittedBin, &(countLost[0]), OpAddAssign());
+    for(int ii = 0; ii < lastEmittedBin; ii++) {
+        if(countLost[ii] > 0) {
             nDelBin_m[ii] = countLost[ii];
+            msg << "In Bin: " << ii << ", " << nDelBin_m[ii] << " particle(s) lost" << endl;
         }
-        m2all << "In Bin: " << ii << ", " << nDelBin_m[ii] << " particle(s) lost" << endl;
     }
 }
 
@@ -83,18 +79,14 @@ void PartBins::updateDeletedPartsInBin(size_t countLost[]) {
 void PartBins::updatePartInBin(size_t countLost[]) {
 
     Inform msg0("updatePartInBin ");
-    //  for (int ii=0; ii < bins_m; ii++){
+
     for(int ii = 0; ii < nemittedBins_m; ii++) {
         msg0 << "In Bin: " << ii << ", " << nBin_m[ii] << " particles " << endl;
     }
+
+    reduce(&(countLost[0]), &(countLost[0]) + nemittedBins_m, &(countLost[0]), OpAddAssign());
     for(int ii = 0; ii < nemittedBins_m; ii++) {
-        bool flagNeedUpdate = false;
-        if(countLost[ii] > 0)
-            flagNeedUpdate = true;
-        reduce(&flagNeedUpdate, &flagNeedUpdate + 1, &flagNeedUpdate, OpBitwiseOrAssign());
-        //          reduce(flagNeedUpdate, flagNeedUpdate, OpOr());
-        if(flagNeedUpdate) {
-            reduce(countLost[ii], countLost[ii], OpAddAssign());
+        if(countLost[ii] > 0) {
             nBin_m[ii] -= countLost[ii];
             msg0 << "In Bin: " << ii << ", " << countLost[ii] << " particle(s) lost" << endl;
         }
@@ -111,8 +103,8 @@ void PartBins::updatePartInBin_cyc(size_t countLost[]) {
 
 
 void PartBins::resetPartInBin(size_t newPartNum[]) {
+    reduce(&(newPartNum[0]), &(newPartNum[0]) + nemittedBins_m, &(newPartNum[0]), OpAddAssign());
     for(int ii = 0; ii < nemittedBins_m; ii++) {
-        reduce(newPartNum[ii], newPartNum[ii], OpAddAssign());
         nBin_m[ii] = newPartNum[ii];
         INFOMSG("After reset Bin: " << ii << ", particle(s): " << newPartNum[ii] << endl);
     }
@@ -255,4 +247,4 @@ int PartBins::getBin(double x) {
     int b = (int) floor(fabs(xmax_m - x) / hBin_m);
     nBin_m[b]++;
     return b;
-}
+}
\ No newline at end of file
diff --git a/src/Classic/Algorithms/PartBunch.cpp b/src/Classic/Algorithms/PartBunch.cpp
index e9705ddec451f5321d549e3099ff665d30964f1e..adea71a5466ee19d42a82bb5c65ed3c9e2ce9526 100644
--- a/src/Classic/Algorithms/PartBunch.cpp
+++ b/src/Classic/Algorithms/PartBunch.cpp
@@ -27,6 +27,7 @@
 #include <fstream>
 #include <iomanip>
 #include <memory>
+#include <utility>
 
 #include "AbstractObjects/OpalData.h"   // OPAL file
 #include "Distribution/Distribution.h"  // OPAL file
@@ -34,6 +35,7 @@
 #include "Structure/LossDataSink.h"
 #include "Utilities/Options.h"
 #include "Utilities/GeneralClassicException.h"
+#include "Utilities/Util.h"
 
 #include "Algorithms/ListElem.h"
 
@@ -71,14 +73,12 @@ PartBunch::PartBunch(const PartData *ref):
     reference(ref),
     unit_state_(units),
     stateOfLastBoundP_(unitless),
-    lineDensity_m(nullptr),
-    nBinsLineDensity_m(0),
     moments_m(),
     dt_m(0.0),
     t_m(0.0),
     eKin_m(0.0),
-    energy_m(nullptr),
     dE_m(0.0),
+    spos_m(0.0),
     rmax_m(0.0),
     rmin_m(0.0),
     rrms_m(0.0),
@@ -99,9 +99,6 @@ PartBunch::PartBunch(const PartData *ref):
     qi_m(0.0),
     interpolationCacheSet_m(false),
     distDump_m(0),
-    stash_Nloc_m(0),
-    stash_iniR_m(0.0),
-    bunchStashed_m(false),
     fieldDBGStep_m(0),
     dh_m(1e-12),
     tEmission_m(0.0),
@@ -121,7 +118,6 @@ PartBunch::PartBunch(const PartData *ref):
     lowParticleCount_m(false),
     dcBeam_m(false),
     minLocNum_m(0) {
-    addAttribute(X);
     addAttribute(P);
     addAttribute(Q);
     addAttribute(M);
@@ -132,12 +128,11 @@ PartBunch::PartBunch(const PartData *ref):
     addAttribute(Bf);
     addAttribute(Bin);
     addAttribute(dt);
-    addAttribute(LastSection);
     addAttribute(PType);
     addAttribute(TriID);
 
     boundpTimer_m = IpplTimings::getTimer("Boundingbox");
-    statParamTimer_m = IpplTimings::getTimer("Statistics");
+    statParamTimer_m = IpplTimings::getTimer("Compute Statistics");
     selfFieldTimer_m = IpplTimings::getTimer("SelfField total");
     compPotenTimer_m  = IpplTimings::getTimer("SF: Potential");
 
@@ -155,15 +150,15 @@ PartBunch::PartBunch(const PartData *ref):
     pmsg_m.release();
     //    f_stream.release();
     /*
-    if(Ippl::getNodes() == 1) {
-        f_stream = std::unique_ptr<ofstream>(new ofstream);
-        f_stream->open("data/dist.dat", ios::out);
-        pmsg_m = std::unique_ptr<Inform>(new Inform(0, *f_stream, 0));
-    }
+      if(Ippl::getNodes() == 1) {
+          f_stream = std::unique_ptr<ofstream>(new ofstream);
+          f_stream->open("data/dist.dat", ios::out);
+          pmsg_m = std::unique_ptr<Inform>(new Inform(0, *f_stream, 0));
+      }
     */
 
     // set the default IPPL behaviour
-    setMimumNumberOfParticlesPerCore(0);
+    setMinimumNumberOfParticlesPerCore(0);
 }
 
 PartBunch::PartBunch(const PartBunch &rhs):
@@ -177,14 +172,12 @@ PartBunch::PartBunch(const PartBunch &rhs):
     reference(rhs.reference),
     unit_state_(rhs.unit_state_),
     stateOfLastBoundP_(rhs.stateOfLastBoundP_),
-    lineDensity_m(nullptr),
-    nBinsLineDensity_m(rhs.nBinsLineDensity_m),
     moments_m(rhs.moments_m),
     dt_m(rhs.dt_m),
     t_m(rhs.t_m),
     eKin_m(rhs.eKin_m),
-    energy_m(nullptr),
     dE_m(rhs.dE_m),
+    spos_m(0.0),
     rmax_m(rhs.rmax_m),
     rmin_m(rhs.rmin_m),
     rrms_m(rhs.rrms_m),
@@ -205,9 +198,6 @@ PartBunch::PartBunch(const PartBunch &rhs):
     qi_m(rhs.qi_m),
     interpolationCacheSet_m(rhs.interpolationCacheSet_m),
     distDump_m(rhs.distDump_m),
-    stash_Nloc_m(rhs.stash_Nloc_m),
-    stash_iniR_m(rhs.stash_iniR_m),
-    bunchStashed_m(rhs.bunchStashed_m),
     fieldDBGStep_m(rhs.fieldDBGStep_m),
     dh_m(rhs.dh_m),
     tEmission_m(rhs.tEmission_m),
@@ -242,14 +232,12 @@ PartBunch::PartBunch(const std::vector<Particle> &rhs, const PartData *ref):
     reference(ref),
     unit_state_(units),
     stateOfLastBoundP_(unitless),
-    lineDensity_m(nullptr),
-    nBinsLineDensity_m(0),
     moments_m(),
     dt_m(0.0),
     t_m(0.0),
     eKin_m(0.0),
-    energy_m(nullptr),
     dE_m(0.0),
+    spos_m(0.0),
     rmax_m(0.0),
     rmin_m(0.0),
     rrms_m(0.0),
@@ -270,9 +258,6 @@ PartBunch::PartBunch(const std::vector<Particle> &rhs, const PartData *ref):
     qi_m(0.0),
     interpolationCacheSet_m(false),
     distDump_m(0),
-    stash_Nloc_m(0),
-    stash_iniR_m(0.0),
-    bunchStashed_m(false),
     fieldDBGStep_m(0),
     dh_m(1e-12),
     tEmission_m(0.0),
@@ -302,7 +287,7 @@ PartBunch::~PartBunch() {
 /// \brief Need Ek for the Schottky effect calculation (eV)
 double PartBunch::getEkin() const {
     if(dist_m)
-        return dist_m->GetEkin();
+        return dist_m->getEkin();
     else
         return 0.0;
 }
@@ -310,14 +295,14 @@ double PartBunch::getEkin() const {
 /// \brief Need the work function for the Schottky effect calculation (eV)
 double PartBunch::getWorkFunctionRf() const {
     if(dist_m)
-        return dist_m->GetWorkFunctionRf();
+        return dist_m->getWorkFunctionRf();
     else
         return 0.0;
 }
 /// \brief Need the laser energy for the Schottky effect calculation (eV)
 double PartBunch::getLaserEnergy() const {
     if(dist_m)
-        return dist_m->GetLaserEnergy();
+        return dist_m->getLaserEnergy();
     else
         return 0.0;
 }
@@ -330,24 +315,23 @@ std::string PartBunch::getFieldSolverType() const {
         return "";
 }
 
-
 void PartBunch::runTests() {
-    
+
     Vector_t ll(-0.005);
     Vector_t ur(0.005);
 
-    this->setBCAllPeriodic();
-    
+    setBCAllPeriodic();
+
     NDIndex<3> domain = getFieldLayout().getDomain();
     for(int i = 0; i < Dim; i++)
         nr_m[i] = domain[i].length();
-    
+
     for(int i = 0; i < 3; i++)
         hr_m[i] = (ur[i] - ll[i]) / nr_m[i];
-    
+
     getMesh().set_meshSpacing(&(hr_m[0]));
     getMesh().set_origin(ll);
-    
+
     rho_m.initialize(getMesh(),
                      getFieldLayout(),
                      GuardCellSizes<Dim>(1),
@@ -371,7 +355,7 @@ void PartBunch::cleanUpParticles() {
 
     destroy(getLocalNum(), 0, true);
 
-    dist_m->CreateOpalT(*this, np, scan);
+    dist_m->createOpalT(*this, np, scan);
 
     update();
 }
@@ -383,12 +367,12 @@ void PartBunch::setDistribution(Distribution *d,
     Inform m("setDistribution " );
     dist_m = d;
 
-    dist_m->CreateOpalT(*this, addedDistributions, np, scan);
+    dist_m->createOpalT(*this, addedDistributions, np, scan);
 
 //    if (Options::cZero)
-//        dist_m->Create(*this, addedDistributions, np / 2, scan);
+//        dist_m->create(*this, addedDistributions, np / 2, scan);
 //    else
-//        dist_m->Create(*this, addedDistributions, np, scan);
+//        dist_m->create(*this, addedDistributions, np, scan);
 }
 
 void PartBunch::resetIfScan()
@@ -457,125 +441,43 @@ double PartBunch::getZ(int i) {
  * DETAILED TODO
  *
  */
-void PartBunch::calcLineDensity() {
-    //   e_dim_tag decomp[3];
-    std::list<ListElem> listz;
-
-    //   for (int d=0; d < 3; ++d) {                                    // this does not seem to work properly
-    //     decomp[d] = getFieldLayout().getRequestedDistribution(d);
-    //   }
-
-    FieldLayout_t &FL  = getFieldLayout();
-    double hz = getMesh().get_meshSpacing(2); // * Physics::c * getdT();
-    //   FieldLayout_t *FL  = new FieldLayout_t(getMesh(), decomp);
-
-    if(!bool(lineDensity_m)) {
-        if(nBinsLineDensity_m == 0)
-            nBinsLineDensity_m = nr_m[2];
-        lineDensity_m = std::unique_ptr<double[]>(new double[nBinsLineDensity_m]);
+void PartBunch::calcLineDensity(unsigned int nBins, std::vector<double> &lineDensity, std::pair<double, double> &meshInfo) {
+    Vector_t rmin, rmax;
+    get_bounds(rmin, rmax);
+
+    if (nBins < 2) {
+        NDIndex<3> grid = getFieldLayout().getDomain();
+        nBins = grid[2].length();
     }
 
-    for(unsigned int i = 0; i < nBinsLineDensity_m; ++i)
-        lineDensity_m[i] = 0.0;
+    double length = rmax(2) - rmin(2);
+    double zmin = rmin(2) - dh_m * length, zmax = rmax(2) + dh_m * length;
+    double hz = (zmax - zmin) / (nBins - 2);
+    double perMeter = 1.0 / hz;//(zmax - zmin);
+    zmin -= hz;
 
-    rho_m = 0.0;
-    this->Q.scatter(this->rho_m, this->R, IntrplCIC_t());
-
-    //   NDIndex<Dim> idx = FL->getLocalNDIndex(); // gives the wrong indices!!
-    //   NDIndex<Dim> idxdom = FL->getDomain();
-    NDIndex<Dim> idx = FL.getLocalNDIndex();
-    NDIndex<Dim> idxdom = FL.getDomain();
-    NDIndex<Dim> elem;
-    int tag = Ippl::Comm->next_tag(IPPL_APP_TAG1, IPPL_APP_CYCLE);
-    double spos = get_sPos();
-    double T = getT();
-
-    if(Ippl::myNode() == 0) {
-        for(int i = idx[2].min(); i <= idx[2].max(); ++i) {
-            double localquantsum = 0.0;
-            elem[2] = Index(i, i);
-            for(int j = idx[1].min(); j <= idx[1].max(); ++j) {
-                elem[1] = Index(j, j);
-                for(int k = idx[0].min(); k <= idx[0].max(); ++k) {
-                    elem[0] = Index(k, k);
-                    localquantsum += rho_m.localElement(elem) / hz;
-                }
-            }
-            listz.push_back(ListElem(spos, T, i, i, localquantsum));
-        }
-        // wait for msg from all processors (EXEPT NODE 0)
-        int notReceived = Ippl::getNodes() - 1;
-        int dataBlocks = 0;
-        int coor;
-        double projVal;
-        while(notReceived > 0) {
-            int node = COMM_ANY_NODE;
-            std::unique_ptr<Message> rmsg(Ippl::Comm->receive_block(node, tag));
-            if(!bool(rmsg)) {
-                ERRORMSG("Could not receive from client nodes in main." << endl);
-            }
-            notReceived--;
-            rmsg->get(&dataBlocks);
-            for(int i = 0; i < dataBlocks; i++) {
-                rmsg->get(&coor);
-                rmsg->get(&projVal);
-                listz.push_back(ListElem(spos, T, coor, coor, projVal));
-            }
-        }
-        listz.sort();
-        /// copy line density in listz to array of double
-        fillArray(lineDensity_m.get(), listz);
-    } else {
-        Message *smsg = new Message();
-        smsg->put(idx[2].max() - idx[2].min() + 1);
-        for(int i = idx[2].min(); i <= idx[2].max(); ++i) {
-            double localquantsum = 0.0;
-            elem[2] = Index(i, i);
-            for(int j = idx[1].min(); j <= idx[1].max(); ++j) {
-                elem[1] = Index(j, j);
-                for(int k = idx[0].min(); k <= idx[0].max(); ++k) {
-                    elem[0] = Index(k, k);
-                    localquantsum +=  rho_m.localElement(elem) / hz;
-                }
-            }
-            smsg->put(i);
-            smsg->put(localquantsum);
-        }
-        bool res = Ippl::Comm->send(smsg, 0, tag);
-        if(! res)
-            ERRORMSG("Ippl::Comm->send(smsg, 0, tag) failed " << endl);
-    }
-    reduce(&(lineDensity_m[0]), &(lineDensity_m[0]) + nBinsLineDensity_m, &(lineDensity_m[0]), OpAddAssign());
-}
+    lineDensity.resize(nBins, 0.0);
+    std::fill(lineDensity.begin(), lineDensity.end(), 0.0);
 
-void PartBunch::fillArray(double *lineDensity, const std::list<ListElem> &l) {
-    unsigned int mmax = 0;
-    unsigned int nmax = 0;
-    unsigned int count = 0;
+    const unsigned int lN = getLocalNum();
+    for (unsigned int i = 0; i < lN; ++ i) {
+        const double z = R[i](2) - 0.5 * hz;
+        unsigned int idx = (z - zmin) / hz;
+        double tau = z - (zmin + idx * hz);
 
-    for(std::list<ListElem>::const_iterator it = l.begin(); it != l.end() ; ++it)  {
-        if(it->m > mmax) mmax = it->m;
-        if(it->n > nmax) nmax = it->n;
+        lineDensity[idx] += Q[i] * (1.0 - tau) * perMeter;
+        lineDensity[idx + 1] += Q[i] * tau * perMeter;
     }
-    for(std::list<ListElem>::const_iterator it = l.begin(); it != l.end(); ++it)
-        if((it->m < mmax) && (it->n < nmax)) {
-            lineDensity[count] = it->den;
-            count++;
-        }
-}
 
-void PartBunch::getLineDensity(std::vector<double> &lineDensity) {
-    if(bool(lineDensity_m)) {
-        if(lineDensity.size() != nBinsLineDensity_m)
-            lineDensity.resize(nBinsLineDensity_m, 0.0);
-        for(unsigned int i  = 0; i < nBinsLineDensity_m; ++i)
-            lineDensity[i] = lineDensity_m[i];
-    }
+    reduce(&(lineDensity[0]), &(lineDensity[0]) + nBins, &(lineDensity[0]), OpAddAssign());
+
+    meshInfo.first = zmin;
+    meshInfo.second = hz;
 }
 
 void PartBunch::calcGammas() {
 
-    const int emittedBins = dist_m->GetNumberOfEnergyBins();
+    const int emittedBins = dist_m->getNumberOfEnergyBins();
 
     size_t s = 0;
 
@@ -585,11 +487,11 @@ void PartBunch::calcGammas() {
     for(unsigned int n = 0; n < getLocalNum(); n++)
         bingamma_m[this->Bin[n]] += sqrt(1.0 + dot(this->P[n], this->P[n]));
 
+    std::unique_ptr<size_t[]> particlesInBin(new size_t[emittedBins]);
+    reduce(bingamma_m.get(), bingamma_m.get() + emittedBins, bingamma_m.get(), OpAddAssign());
+    reduce(binemitted_m.get(), binemitted_m.get() + emittedBins, particlesInBin.get(), OpAddAssign());
     for(int i = 0; i < emittedBins; i++) {
-        reduce(bingamma_m[i], bingamma_m[i], OpAddAssign());
-
-        size_t pInBin = (binemitted_m[i]);
-        reduce(pInBin, pInBin, OpAddAssign());
+        size_t &pInBin = particlesInBin[i];
         if(pInBin != 0) {
             bingamma_m[i] /= pInBin;
             INFOMSG(level2 << "Bin " << std::setw(3) << i << " gamma = " << std::setw(8) << std::scientific << std::setprecision(5) << bingamma_m[i] << "; NpInBin= " << std::setw(8) << std::setfill(' ') << pInBin << endl);
@@ -599,7 +501,7 @@ void PartBunch::calcGammas() {
         }
         s += pInBin;
     }
-
+    particlesInBin.reset();
 
 
     if(s != getTotalNum() && !OpalData::getInstance()->hasGlobalGeometry())
@@ -639,7 +541,7 @@ size_t PartBunch::calcNumPartsOutside(Vector_t x) {
     partPerNode_m[Ippl::myNode()] = 0;
     const Vector_t meanR = get_rmean();
 
-    for(unsigned long k = 0; k < this->getLocalNum(); ++ k)
+    for(unsigned long k = 0; k < getLocalNum(); ++ k)
         if (abs(R[k](0) - meanR(0)) > x(0) ||
             abs(R[k](1) - meanR(1)) > x(1) ||
             abs(R[k](2) - meanR(2)) > x(2)) {
@@ -664,9 +566,9 @@ void PartBunch::computeSelfFields(int binNumber) {
     eg_m = Vector_t(0.0);
 
     if(fs_m->hasValidSolver()) {
-         /// Mesh the whole domain
-         if(fs_m->getFieldSolverType() == "SAAMG")
-             resizeMesh();
+        /// Mesh the whole domain
+        if(fs_m->getFieldSolverType() == "SAAMG")
+            resizeMesh();
 
         /// Scatter charge onto space charge grid.
         this->Q *= this->dt;
@@ -778,9 +680,10 @@ void PartBunch::computeSelfFields(int binNumber) {
         /// is moving to -infinity (instead of +infinity) so the Lorentz transform is different.
 
         /// Find z shift for shifted Green's function.
-        Vector_t rmax, rmin;
-        get_bounds(rmin, rmax);
-        double zshift = - (rmax(2) + rmin(2)) * gammaz * scaleFactor;
+        NDIndex<3> domain = getFieldLayout().getDomain();
+        Vector_t origin = rho_m.get_mesh().get_origin();
+        double hz = rho_m.get_mesh().get_meshSpacing(2);
+        double zshift = -(2 * origin(2) + (domain[2].first() + domain[2].last() + 1) * hz) * gammaz * scaleFactor;
 
         /// Find potential from image charge in this bin using Poisson's
         /// equation (without coefficient: -1/(eps)).
@@ -910,7 +813,7 @@ void PartBunch::computeSelfFields(int binNumber) {
 
             INFOMSG("*** FINISHED DUMPING E FIELD ***" << endl);
         }
-            fieldDBGStep_m++;
+        fieldDBGStep_m++;
 #endif
 
         /// Interpolate electric field at particle positions.  We reuse the
@@ -1098,13 +1001,13 @@ void PartBunch::computeSelfFields() {
         int mz2 = (int)nr_m[2] / 2;
 
         for (int i=0; i<mx; i++ )
-         *gmsg << "Field along x axis Ex = " << eg_m[i][my2][mz2] << " Pot = " << rho_m[i][my2][mz2]  << endl;
+            *gmsg << "Field along x axis Ex = " << eg_m[i][my2][mz2] << " Pot = " << rho_m[i][my2][mz2]  << endl;
 
         for (int i=0; i<my; i++ )
-         *gmsg << "Field along y axis Ey = " << eg_m[mx2][i][mz2] << " Pot = " << rho_m[mx2][i][mz2]  << endl;
+            *gmsg << "Field along y axis Ey = " << eg_m[mx2][i][mz2] << " Pot = " << rho_m[mx2][i][mz2]  << endl;
 
         for (int i=0; i<mz; i++ )
-         *gmsg << "Field along z axis Ez = " << eg_m[mx2][my2][i] << " Pot = " << rho_m[mx2][my2][i]  << endl;
+            *gmsg << "Field along z axis Ez = " << eg_m[mx2][my2][i] << " Pot = " << rho_m[mx2][my2][i]  << endl;
 #endif
 
 #ifdef DBG_SCALARFIELD
@@ -1158,86 +1061,6 @@ void PartBunch::computeSelfFields() {
     IpplTimings::stopTimer(selfFieldTimer_m);
 }
 
-/*
-void PartBunch::computeSelfFields_cycl(double gamma) {
-    IpplTimings::startTimer(selfFieldTimer_m);
-
-    /// set initial charge density to zero.
-    rho_m = 0.0;
-
-    /// set initial E field to zero
-    eg_m = Vector_t(0.0);
-
-    if(fs_m->hasValidSolver()) {
-
-        /// scatter particles charge onto grid.
-        this->Q.scatter(this->rho_m, this->R, IntrplCIC_t());
-
-        /// from charge to charge density.
-        double tmp2 = 1.0 / gamma / (hr_m[0] * hr_m[1] * hr_m[2]);
-        rho_m *= tmp2;
-
-        /// Lorentz transformation
-        /// In particle rest frame, the longitudinal length enlarged
-        Vector_t hr_scaled = hr_m ;
-        hr_scaled[1] *= gamma;
-        /// now charge density is in rho_m
-        /// calculate Possion equation (without coefficient: -1/(eps))
-        fs_m->solver_m->computePotential(rho_m, hr_scaled);
-
-        //do the multiplication of the grid-cube volume coming
-        //from the discretization of the convolution integral.
-        //this is only necessary for the FFT solver
-        //FIXME: later move this scaling into FFTPoissonSolver
-        if(fs_m->getFieldSolverType() == "FFT" || fs_m->getFieldSolverType() == "FFTBOX")
-            rho_m *= hr_scaled[0] * hr_scaled[1] * hr_scaled[2];
-
-        /// retrive coefficient: -1/(eps)
-        rho_m *= getCouplingConstant();
-
-        /// calculate electric field vectors from field potential
-        eg_m = -Grad(rho_m, eg_m);
-
-        /// back Lorentz transformation
-        eg_m *= Vector_t(gamma, 1.0 / gamma, gamma);
-*/
-        /*
-        //debug
-        // output field on the grid points
-
-        int m1 = (int)nr_m[0]-1;
-        int m2 = (int)nr_m[0]/2;
-
-        for (int i=0; i<m1; i++ )
-         *gmsg << "Field along x axis E = " << eg_m[i][m2][m2] << " Pot = " << rho_m[i][m2][m2]  << endl;
-
-        for (int i=0; i<m1; i++ )
-         *gmsg << "Field along y axis E = " << eg_m[m2][i][m2] << " Pot = " << rho_m[m2][i][m2]  << endl;
-
-        for (int i=0; i<m1; i++ )
-         *gmsg << "Field along z axis E = " << eg_m[m2][m2][i] << " Pot = " << rho_m[m2][m2][i]  << endl;
-        // end debug
-         */
-/*
-        /// interpolate electric field at particle positions.
-        Ef.gather(eg_m, this->R,  IntrplCIC_t());
-
-        /// calculate coefficient
-        double betaC = sqrt(gamma * gamma - 1.0) / gamma / Physics::c;
-
-        /// calculate B field from E field
-        Bf(0) =  betaC * Ef(2);
-        Bf(2) = -betaC * Ef(0);
-
-    }
-    // *gmsg<<"gamma ="<<gamma<<endl;
-    // *gmsg<<"dx,dy,dz =("<<hr_m[0]<<", "<<hr_m[1]<<", "<<hr_m[2]<<") [m] "<<endl;
-    // *gmsg<<"max of bunch is ("<<rmax_m(0)<<", "<<rmax_m(1)<<", "<<rmax_m(2)<<") [m] "<<endl;
-    // *gmsg<<"min of bunch is ("<<rmin_m(0)<<", "<<rmin_m(1)<<", "<<rmin_m(2)<<") [m] "<<endl;
-    IpplTimings::stopTimer(selfFieldTimer_m);
-}
-*/
-
 /**
  * \method computeSelfFields_cycl()
  * \brief Calculates the self electric field from the charge density distribution for use in cyclotrons
@@ -1363,13 +1186,13 @@ void PartBunch::computeSelfFields_cycl(double gamma) {
         int mz2 = (int)nr_m[2] / 2;
 
         for (int i=0; i<mx; i++ )
-         *gmsg << "Field along x axis Ex = " << eg_m[i][my2][mz2] << " Pot = " << rho_m[i][my2][mz2]  << endl;
+            *gmsg << "Field along x axis Ex = " << eg_m[i][my2][mz2] << " Pot = " << rho_m[i][my2][mz2]  << endl;
 
         for (int i=0; i<my; i++ )
-         *gmsg << "Field along y axis Ey = " << eg_m[mx2][i][mz2] << " Pot = " << rho_m[mx2][i][mz2]  << endl;
+            *gmsg << "Field along y axis Ey = " << eg_m[mx2][i][mz2] << " Pot = " << rho_m[mx2][i][mz2]  << endl;
 
         for (int i=0; i<mz; i++ )
-         *gmsg << "Field along z axis Ez = " << eg_m[mx2][my2][i] << " Pot = " << rho_m[mx2][my2][i]  << endl;
+            *gmsg << "Field along z axis Ez = " << eg_m[mx2][my2][i] << " Pot = " << rho_m[mx2][my2][i]  << endl;
 #endif
 
 #ifdef DBG_SCALARFIELD
@@ -1626,92 +1449,9 @@ void PartBunch::computeSelfFields_cycl(int bin) {
     IpplTimings::stopTimer(selfFieldTimer_m);
 }
 
-/*
-void PartBunch::computeSelfFields_cycl(int bin) {
-    IpplTimings::startTimer(selfFieldTimer_m);
-
-    /// set initial charge dentsity to zero.
-    rho_m = 0.0;
-
-    /// set initial E field to zero
-    eg_m = Vector_t(0.0);
-
-    /// get gamma of this bin
-    double gamma = getBinGamma(bin);
-
-    if(fs_m->hasValidSolver()) {
-
-        /// scatter particles charge onto grid.
-        this->Q.scatter(this->rho_m, this->R, IntrplCIC_t());
-
-        /// from charge to charge density.
-        double tmp2 = 1.0 / gamma / (hr_m[0] * hr_m[1] * hr_m[2]);
-        rho_m *= tmp2;
-
-        /// Lorentz transformation
-        /// In particle rest frame, the longitudinal length enlarged
-        Vector_t hr_scaled = hr_m ;
-        hr_scaled[1] *= gamma;
-
-        /// now charge density is in rho_m
-        /// calculate Possion equation (without coefficient: -1/(eps))
-        fs_m->solver_m->computePotential(rho_m, hr_scaled);
-
-        /// additional work of FFT solver
-        /// now the scalar potential is given back in rho_m
-        if(fs_m->getFieldSolverType() == "FFT" || fs_m->getFieldSolverType() == "FFTBOX")
-            rho_m *= hr_scaled[0] * hr_scaled[1] * hr_scaled[2];
-
-        /// retrive coefficient: -1/(eps)
-        rho_m *= getCouplingConstant();
-
-        /// calculate electric field vectors from field potential
-        eg_m = -Grad(rho_m, eg_m);
-
-        /// back Lorentz transformation
-        eg_m *= Vector_t(gamma, 1.0 / gamma, gamma);
-*/
-        /*
-        //debug
-        // output field on the grid points
-
-        int m1 = (int)nr_m[0]-1;
-        int m2 = (int)nr_m[0]/2;
-
-        for (int i=0; i<m1; i++ )
-         *gmsg << "Field along x axis E = " << eg_m[i][m2][m2] << " Pot = " << rho_m[i][m2][m2]  << endl;
-
-        for (int i=0; i<m1; i++ )
-         *gmsg << "Field along y axis E = " << eg_m[m2][i][m2] << " Pot = " << rho_m[m2][i][m2]  << endl;
-
-        for (int i=0; i<m1; i++ )
-         *gmsg << "Field along z axis E = " << eg_m[m2][m2][i] << " Pot = " << rho_m[m2][m2][i]  << endl;
-        // end debug
-         */
-/*
-        /// interpolate electric field at particle positions.
-        Eftmp.gather(eg_m, this->R,  IntrplCIC_t());
-
-        /// calculate coefficient
-        double betaC = sqrt(gamma * gamma - 1.0) / gamma / Physics::c;
-
-        /// calculate B_bin field from E_bin field accumulate B and E field
-        Bf(0) = Bf(0) + betaC * Eftmp(2);
-        Bf(2) = Bf(2) - betaC * Eftmp(0);
-
-        Ef += Eftmp;
-    }
-    // *gmsg<<"gamma ="<<gamma<<endl;
-    // *gmsg<<"dx,dy,dz =("<<hr_m[0]<<", "<<hr_m[1]<<", "<<hr_m[2]<<") [m] "<<endl;
-    // *gmsg<<"max of bunch is ("<<rmax_m(0)<<", "<<rmax_m(1)<<", "<<rmax_m(2)<<") [m] "<<endl;
-    // *gmsg<<"min of bunch is ("<<rmin_m(0)<<", "<<rmin_m(1)<<", "<<rmin_m(2)<<") [m] "<<endl;
-    IpplTimings::stopTimer(selfFieldTimer_m);
-}
-*/
-
 void PartBunch::setBCAllPeriodic() {
     for(int i = 0; i < 2 * 3; ++i) {
-        
+
         if (Ippl::getNodes()>1) {
             bc_m[i] = new ParallelInterpolationFace<double, Dim, Mesh_t, Center_t>(i);
             //std periodic boundary conditions for gradient computations etc.
@@ -1728,7 +1468,6 @@ void PartBunch::setBCAllPeriodic() {
     INFOMSG(level3 << "BC set P3M, all periodic" << endl);
 }
 
-
 void PartBunch::setBCAllOpen() {
     for(int i = 0; i < 2 * 3; ++i) {
         bc_m[i] = new ZeroFace<double, 3, Mesh_t, Center_t>(i);
@@ -1759,7 +1498,6 @@ void PartBunch::boundp() {
     /*
       Assume rmin_m < 0.0
      */
-    // Inform m("boundp ", INFORM_ALL_NODES);
 
     IpplTimings::startTimer(boundpTimer_m);
     //if(!R.isDirty() && stateOfLastBoundP_ == unit_state_) return;
@@ -1770,57 +1508,77 @@ void PartBunch::boundp() {
     if(!isGridFixed()) {
         const int dimIdx = 3;
 
-        /**
-           In case of dcBeam_m && hr_m < 0
-           this is the first call to boundp and we
-           have to set hr completely i.e. x,y and z.
-        */
+	/**
+	   In case of dcBeam_m && hr_m < 0
+	   this is the first call to boundp and we
+	   have to set hr completely i.e. x,y and z.
 
-        const bool fullUpdate = (dcBeam_m && (hr_m[2] < 0.0)) || !dcBeam_m;
-        double hzSave;
+	 */
 
-        NDIndex<3> domain = getFieldLayout().getDomain();
-        for(int i = 0; i < Dim; i++)
+	const bool fullUpdate = (dcBeam_m && (hr_m[2] < 0.0)) || !dcBeam_m;
+	double hzSave;
+
+	NDIndex<3> domain = getFieldLayout().getDomain();
+	for(int i = 0; i < Dim; i++)
             nr_m[i] = domain[i].length();
 
-        get_bounds(rmin_m, rmax_m);
-        Vector_t len = rmax_m - rmin_m;
+	get_bounds(rmin_m, rmax_m);
+	Vector_t len = rmax_m - rmin_m;
 
-        if (!fullUpdate) {
+	if (!fullUpdate) {
             hzSave = hr_m[2];
-        }
-        else {
+	}
+	else {
+            double volume = 1.0;
             for(int i = 0; i < dimIdx; i++) {
-                double length = std::abs(rmax_m[i] - rmin_m[i]);
+                double length = std::max(1e-10, std::abs(rmax_m[i] - rmin_m[i]));
                 rmax_m[i] += dh_m * length;
                 rmin_m[i] -= dh_m * length;
-                if (length > 0)
-                    hr_m[i]    = (rmax_m[i] - rmin_m[i]) / (nr_m[i] - 1);
+                hr_m[i]    = (rmax_m[i] - rmin_m[i]) / (nr_m[i] - 1);
+                volume *= length;
             }
-            // m << "It is a full boundp hz= " << hr_m << " rmax= " << rmax_m << " rmin= " << rmin_m << endl;
-        }
-        if (!fullUpdate) {
-            hr_m[2] = hzSave;
-            //INFOMSG("It is not a full boundp hz= " << hr_m << " rmax= " << rmax_m << " rmin= " << rmin_m << endl);
-        }
 
-        if (((hr_m[0] <= 0.0) || (hr_m[1] <= 0.0) || (hr_m[2] <= 0.0)) && (this->getTotalNum()>10))
-            throw GeneralClassicException("boundp() ", "h<0, can not build a mesh");
+            if (getIfBeamEmitting() && dist_m != NULL) {
+                // keep particles per cell ratio high, don't spread a hand full particles across the whole grid
+                double percent = std::max((1.0 + (3 - nr_m[2]) * dh_m) / (nr_m[2] - 1), dist_m->getPercentageEmitted());
+                double length   = std::abs(rmax_m[2] - rmin_m[2]);
+                if (percent < 1.0 && percent > 0.0) {
+                    length /= (1.0 + 2 * dh_m);
+                    rmax_m[2] -= dh_m * length;
+                    rmin_m[2] = rmax_m[2] * (1.0 - 1.0 / percent);
+
+                    length = std::abs(rmax_m[2] - rmin_m[2]);
+                    rmax_m[2] += dh_m * length;
+                    rmin_m[2] -= dh_m * length;
+                    hr_m[2] = length * (1.0 + 2 * dh_m) / (nr_m[2] - 1);
+                }
+            }
 
-   // if (getTotalNum() < 200) m << "before set fields Nl= " << getLocalNum() << endl;
+            if (volume < 1e-21 && getTotalNum() > 1 && std::abs(sum(Q)) > 0.0) {
+                WARNMSG(level1 << "!!! Extremly high particle density detected !!!" << endl);
+            }
+            //INFOMSG("It is a full boundp hz= " << hr_m << " rmax= " << rmax_m << " rmin= " << rmin_m << endl);
+	}
 
-	if(hr_m[0] * hr_m[1] * hr_m[2] > 0) {
-	  getMesh().set_meshSpacing(&(hr_m[0]));
-	  getMesh().set_origin(rmin_m - Vector_t(hr_m[0] / 2.0, hr_m[1] / 2.0, hr_m[2] / 2.0));
-	  rho_m.initialize(getMesh(),
-			   getFieldLayout(),
-			   GuardCellSizes<Dim>(1),
-			   bc_m);
-	  eg_m.initialize(getMesh(),
-			  getFieldLayout(),
-			  GuardCellSizes<Dim>(1),
-			  vbc_m);
+	if (!fullUpdate) {
+            hr_m[2] = hzSave;
+            //INFOMSG("It is not a full boundp hz= " << hr_m << " rmax= " << rmax_m << " rmin= " << rmin_m << endl);
 	}
+
+	if(hr_m[0] * hr_m[1] * hr_m[2] > 0) {
+            getMesh().set_meshSpacing(&(hr_m[0]));
+            getMesh().set_origin(rmin_m - Vector_t(hr_m[0] / 2.0, hr_m[1] / 2.0, hr_m[2] / 2.0));
+            rho_m.initialize(getMesh(),
+                             getFieldLayout(),
+                             GuardCellSizes<Dim>(1),
+                             bc_m);
+            eg_m.initialize(getMesh(),
+                            getFieldLayout(),
+                            GuardCellSizes<Dim>(1),
+                            vbc_m);
+	} else {
+            throw GeneralClassicException("boundp() ", "h<0, can not build a mesh");
+        }
     }
     update();
     R.resetDirtyFlag();
@@ -1828,74 +1586,13 @@ void PartBunch::boundp() {
     IpplTimings::stopTimer(boundpTimer_m);
 }
 
-void PartBunch::rotateAbout(const Vector_t &Center, const Vector_t &Momentum) {
-    double AbsMomentumProj = sqrt(Momentum(0) * Momentum(0) + Momentum(2) * Momentum(2));
-    double AbsMomentum = sqrt(dot(Momentum, Momentum));
-    double cos0 = AbsMomentumProj / AbsMomentum;
-    double sin0 = -Momentum(1) / AbsMomentum;
-    double cos1 = Momentum(2) / AbsMomentumProj;
-    double sin1 = -Momentum(0) / AbsMomentumProj;
-    double sin2 = 0.0;
-    double cos2 = sqrt(1.0 - sin2 * sin2);
-
-
-    Tenzor<double, 3> T1(1.0,   0.0,  0.0,
-                         0.0,  cos0, sin0,
-                         0.0, -sin0, cos0);
-    Tenzor<double, 3> T2(cos1, 0.0, sin1,
-                         0.0, 1.0,  0.0,
-                         -sin1, 0.0, cos1);
-    Tenzor<double, 3> T3(cos2, 0.0, sin2,
-                         0.0, 1.0,  0.0,
-                         -sin2, 0.0, cos2);
-    Tenzor<double, 3> TM = dot(T1, dot(T2, T3));
-    for(unsigned int i = 0; i < this->getLocalNum(); i++) {
-        R[i] = dot(TM, R[i] - Center) + Center;
-        P[i] = dot(TM, P[i]);
-    }
-}
-
-void PartBunch::moveBy(const Vector_t &Center) {
-    for(unsigned int i = 0; i < this->getLocalNum(); i++) {
-        R[i] += Center;
-    }
-}
-
-void PartBunch::ResetLocalCoordinateSystem(const int &i, const Vector_t &Orientation, const double &origin) {
-
-    Vector_t temp(R[i](0), R[i](1), R[i](2) - origin);
-
-    if(fabs(Orientation(0)) > 1e-6 || fabs(Orientation(1)) > 1e-6 || fabs(Orientation(2)) > 1e-6) {
-
-        // Rotate to the the element's local coordinate system.
-        //
-        // 1) Rotate about the z axis by angle negative Orientation(2).
-        // 2) Rotate about the y axis by angle negative Orientation(0).
-        // 3) Rotate about the x axis by angle Orientation(1).
-
-        double cosa = cos(Orientation(0));
-        double sina = sin(Orientation(0));
-        double cosb = cos(Orientation(1));
-        double sinb = sin(Orientation(1));
-        double cosc = cos(Orientation(2));
-        double sinc = sin(Orientation(2));
-
-        X[i](0) = (cosa * cosc) * temp(0) + (cosa * sinc) * temp(1) - sina *        temp(2);
-        X[i](1) = (-cosb * sinc - sina * sinb * cosc) * temp(0) + (cosb * cosc - sina * sinb * sinc) * temp(1) - cosa * sinb * temp(2);
-        X[i](2) = (-sinb * sinc + sina * cosb * cosc) * temp(0) + (sinb * cosc + sina * cosb * sinc) * temp(1) + cosa * cosb * temp(2);
-
-    } else
-        X[i] = temp;
-}
-
-
 void PartBunch::gatherLoadBalanceStatistics() {
-   minLocNum_m =  std::numeric_limits<size_t>::max();
+    minLocNum_m =  std::numeric_limits<size_t>::max();
 
-   for(int i = 0; i < Ippl::getNodes(); i++)
+    for(int i = 0; i < Ippl::getNodes(); i++)
         partPerNode_m[i] = globalPartPerNode_m[i] = 0;
 
-    partPerNode_m[Ippl::myNode()] = this->getLocalNum();
+    partPerNode_m[Ippl::myNode()] = getLocalNum();
 
     reduce(partPerNode_m.get(), partPerNode_m.get() + Ippl::getNodes(), globalPartPerNode_m.get(), OpAddAssign());
 
@@ -1920,29 +1617,14 @@ void PartBunch::calcMoments() {
         }
     }
 
-    /*
-      find particle with ID==0
-      and save index in zID
-     */
-
-    unsigned long zID = 0;
-    bool found = false;
-    for(unsigned long k = 0; k < this->getLocalNum(); ++k) {
-        if (this->ID[k] == 0) {
-            found  = true;
-            zID = k;
-            break;
-        }
-    }
-    
-    for(unsigned long k = 0; k < this->getLocalNum(); ++k) {
+    for(unsigned long k = 0; k < getLocalNum(); ++k) {
         part[1] = this->P[k](0);
         part[3] = this->P[k](1);
         part[5] = this->P[k](2);
         part[0] = this->R[k](0);
         part[2] = this->R[k](1);
         part[4] = this->R[k](2);
-        
+
         for(int i = 0; i < 2 * Dim; i++) {
             loc_centroid[i]   += part[i];
             for(int j = 0; j <= i; j++) {
@@ -1950,23 +1632,6 @@ void PartBunch::calcMoments() {
             }
         }
     }
-    
-    if (found) {
-        part[1] = this->P[zID](0);
-        part[3] = this->P[zID](1);
-        part[5] = this->P[zID](2);
-        part[0] = this->R[zID](0);
-        part[2] = this->R[zID](1);
-        part[4] = this->R[zID](2);
-        
-        for(int i = 0; i < 2 * Dim; i++) {
-            loc_centroid[i]   -= part[i];
-            for(int j = 0; j <= i; j++) {
-                loc_moment[i][j]   -= part[i] * part[j];
-            }
-        }
-    } 
-
 
     for(int i = 0; i < 2 * Dim; i++) {
         for(int j = 0; j < i; j++) {
@@ -2038,10 +1703,12 @@ void PartBunch::calcBeamParameters() {
 
     IpplTimings::startTimer(statParamTimer_m);
 
-    const size_t locNp = this->getLocalNum();
-    const double N =  static_cast<double>(this->getTotalNum());
+    const size_t locNp = getLocalNum();
+    const double N =  static_cast<double>(getTotalNum());
     const double zero = 0.0;
 
+    get_bounds(rmin_m, rmax_m);
+
     if(N == 0) {
         for(unsigned int i = 0 ; i < Dim; i++) {
             rmean_m(i) = 0.0;
@@ -2081,44 +1748,11 @@ void PartBunch::calcBeamParameters() {
 
     rprms_m = rpsum * fac;
 
-    if (nodes_m > 1) {
-        Dx_m = moments_m(0, 5) / N;
-        DDx_m = moments_m(1, 5) / N;
-      
-        Dy_m = moments_m(2, 5) / N;
-        DDy_m = moments_m(3, 5) / N;
+    Dx_m = moments_m(0, 5) / N;
+    DDx_m = moments_m(1, 5) / N;
 
-    }
-    else {
-      /** 
-	  This is a easy way to follow the linear dispersion
-
-	  The position of the first 4 particles when read from file
-	  can be set to zero and a dp/p0 can be set, hence the dispersion
-	  orbit can be followed.
-      */
-      
-        for(size_t i = 0; i < locNp; i++) {
-          if (ID[i] == 1) {
-              Dx_m = R[i](0);
-          }
-          else if (ID[i] == 2) {
-              DDx_m = R[i](0);
-          }
-          else if (ID[i] == 3) {
-              Dy_m = R[i](0);
-          }
-          else if (ID[i] == 4) {
-              DDy_m = R[i](0);
-          }
-        }
-    }
-
-    /*
-      double rmax = sqrt(dot(rmax_m,rmax_m));
-      fplasma_m = sqrt(2.0*get_perverance())*get_beta()*c/rmax;
-      budkerp_m = (get_perverance()/2.0)*pow(get_gamma(),3.0)*pow(get_beta(),2.0);
-     */
+    Dy_m = moments_m(2, 5) / N;
+    DDy_m = moments_m(3, 5) / N;
 
     // Find unnormalized emittance.
     double gamma = 0.0;
@@ -2137,11 +1771,10 @@ void PartBunch::calcBeamParameters() {
     IpplTimings::stopTimer(statParamTimer_m);
 }
 
-
 void PartBunch::calcBeamParametersInitial() {
     using Physics::c;
 
-    const double N =  static_cast<double>(this->getTotalNum());
+    const double N =  static_cast<double>(getTotalNum());
 
     if(N == 0) {
         rmean_m = Vector_t(0.0);
@@ -2253,71 +1886,73 @@ void PartBunch::maximumAmplitudes(const FMatrix<double, 6, 6> &D,
  \f$\Delta t_{full-timestep}\f$.
   */
 
-
-double PartBunch::GetEmissionDeltaT() {
-    return dist_m->GetEmissionDeltaT();
+double PartBunch::getEmissionDeltaT() {
+    return dist_m->getEmissionDeltaT();
 }
 
-size_t PartBunch::EmitParticles(double eZ) {
+size_t PartBunch::emitParticles(double eZ) {
 
-    return dist_m->EmitParticles(*this, eZ);
+    return dist_m->emitParticles(*this, eZ);
 
 }
 
-
+void PartBunch::updateNumTotal() {
+    size_t numParticles = getLocalNum();
+    reduce(numParticles, numParticles, OpAddAssign());
+    setTotalNum(numParticles);
+}
 
 Inform &PartBunch::print(Inform &os) {
-    if(this->getTotalNum() != 0) {  // to suppress Nan's
+    if(getTotalNum() != 0) {  // to suppress Nan's
         Inform::FmtFlags_t ff = os.flags();
         os << std::scientific;
         os << level1 << "\n";
         os << "* ************** B U N C H ********************************************************* \n";
-        os << "* NP              =   " << this->getTotalNum() << "\n";
-        os << "* Qtot            =   " << std::setw(12) << std::setprecision(5) << abs(sum(Q)) * 1.0e9 << " [nC]       "
-           << "Qi    = " << std::setw(12) << std::abs(qi_m) * 1e9 << " [nC]" << "\n";
-        os << "* Ekin            =   " << std::setw(12) << std::setprecision(5) << eKin_m << " [MeV]      "
-           << "dEkin = " << std::setw(12) << dE_m << " [MeV]\n";
-        os << "* rmax            = " << std::setw(12) << std::setprecision(5) << rmax_m << " [m]\n";
-        os << "* rmin            = " << std::setw(12) << std::setprecision(5) << rmin_m << " [m]\n";
-        os << "* rms beam size   = " << std::setw(12) << std::setprecision(5) << rrms_m << " [m]\n";
+        os << "* NP              = " << getTotalNum() << "\n";
+        os << "* Qtot            = " << std::setw(17) << Util::getChargeString(abs(sum(Q))) << "         "
+           << "Qi    = "             << std::setw(17) << Util::getChargeString(std::abs(qi_m)) << "\n";
+        os << "* Ekin            = " << std::setw(17) << Util::getEnergyString(eKin_m) << "         "
+           << "dEkin = "             << std::setw(17) << Util::getEnergyString(dE_m) << "\n";
+        os << "* rmax            = " << Util::getLengthString(rmax_m, 5) << "\n";
+        os << "* rmin            = " << Util::getLengthString(rmin_m, 5) << "\n";
+        os << "* rms beam size   = " << Util::getLengthString(rrms_m, 5) << "\n";
         os << "* rms momenta     = " << std::setw(12) << std::setprecision(5) << prms_m << " [beta gamma]\n";
-        os << "* mean position   = " << std::setw(12) << std::setprecision(5) << rmean_m << " [m]\n";
+        os << "* mean position   = " << Util::getLengthString(rmean_m, 5) << "\n";
         os << "* mean momenta    = " << std::setw(12) << std::setprecision(5) << pmean_m << " [beta gamma]\n";
         os << "* rms emittance   = " << std::setw(12) << std::setprecision(5) << eps_m << " (not normalized)\n";
         os << "* rms correlation = " << std::setw(12) << std::setprecision(5) << rprms_m << "\n";
-        os << "* hr              = " << std::setw(12) << std::setprecision(5) << hr_m << " [m]\n";
-        os << "* dh              =   " << std::setw(12) << std::setprecision(5) << dh_m * 100 << " [%]\n";
-        os << "* t               =   " << std::setw(12) << std::setprecision(5) << getT() << " [s]        "
-           << "dT    = " << std::setw(12) << getdT() << " [s]\n";
-        os << "* spos            =   " << std::setw(12) << std::setprecision(5) << get_sPos() << " [m]\n";
+        os << "* hr              = " << Util::getLengthString(hr_m, 5) << "\n";
+        os << "* dh              = " << std::setw(13) << std::setprecision(5) << dh_m * 100 << " [%]\n";
+        os << "* t               = " << std::setw(17) << Util::getTimeString(getT()) << "         "
+           << "dT    = "             << std::setw(17) << Util::getTimeString(getdT()) << "\n";
+        os << "* spos            = " << std::setw(17) << Util::getLengthString(get_sPos()) << "\n";
         os << "* ********************************************************************************** " << endl;
         os.flags(ff);
     }
     return os;
 }
 
-
 void PartBunch::correctEnergy(double avrgp_m) {
 
-  const double totalNp = static_cast<double>(this->getTotalNum());
-  const double locNp = static_cast<double>(this->getLocalNum());
+    const double totalNp = static_cast<double>(getTotalNum());
+    const double locNp = static_cast<double>(getLocalNum());
 
-  double avrgp = 0.0;
-  for(unsigned int k = 0; k < locNp; k++)
-    avrgp += sqrt(dot(P[k], P[k]));
+    double avrgp = 0.0;
+    for(unsigned int k = 0; k < locNp; k++)
+        avrgp += sqrt(dot(P[k], P[k]));
 
-  reduce(avrgp, avrgp, OpAddAssign());
-  avrgp /= totalNp;
+    reduce(avrgp, avrgp, OpAddAssign());
+    avrgp /= totalNp;
 
-  for(unsigned int k = 0; k < locNp; k++)
-    P[k](2) =  P[k](2) - avrgp + avrgp_m;
+    for(unsigned int k = 0; k < locNp; k++)
+        P[k](2) =  P[k](2) - avrgp + avrgp_m;
 }
 
 
 void PartBunch::calcEMean() {
 
-    const double totalNp = static_cast<double>(this->getTotalNum());
-    const double locNp = static_cast<double>(this->getLocalNum());
+    const double totalNp = static_cast<double>(getTotalNum());
+    const double locNp = static_cast<double>(getLocalNum());
 
     //Vector_t meanP_temp = Vector_t(0.0);
 
@@ -2342,11 +1977,7 @@ void PartBunch::calcEMean() {
 
 size_t PartBunch::boundp_destroyT() {
 
-    /*
-     (ne < nL)
-
-     */
-    const unsigned int minNumOfParticlesPerCore = this->getMinimumNumberOfParticlesPerCore();
+    const unsigned int minNumParticlesPerCore = getMinimumNumberOfParticlesPerCore();
 
     NDIndex<Dim> domain = getFieldLayout().getDomain();
     for(int i = 0; i < Dim; i++)
@@ -2354,47 +1985,45 @@ size_t PartBunch::boundp_destroyT() {
 
     std::unique_ptr<size_t[]> tmpbinemitted;
 
-
-    update();
+    boundp();
 
     size_t ne = 0;
-    const size_t nL = this->getLocalNum();
+    const size_t localNum = getLocalNum();
 
-    if(WeHaveEnergyBins()) {
-        tmpbinemitted = std::unique_ptr<size_t[]>(new size_t[GetNumberOfEnergyBins()]);
-        for(int i = 0; i < GetNumberOfEnergyBins(); i++) {
+    if(weHaveEnergyBins()) {
+        tmpbinemitted = std::unique_ptr<size_t[]>(new size_t[getNumberOfEnergyBins()]);
+        for(int i = 0; i < getNumberOfEnergyBins(); i++) {
             tmpbinemitted[i] = 0;
         }
-        for(unsigned int i = 0; i < nL; i++) {
-            if ((Bin[i] < 0) && (i < nL)) {
+        for(unsigned int i = 0; i < localNum; i++) {
+            if (Bin[i] < 0) {
                 ne++;
-                this->destroy(1, i);
+                destroy(1, i);
             } else
                 tmpbinemitted[Bin[i]]++;
         }
     } else {
-        for(unsigned int i = 0; i < this->getLocalNum(); i++) {
-            if((Bin[i] < 0) && ((nL - ne) > minNumOfParticlesPerCore)) {   // need in minimum 2 particle per node
+        for(unsigned int i = 0; i < localNum; i++) {
+            if((Bin[i] < 0) && ((localNum - ne) > minNumParticlesPerCore)) {   // need in minimum x particles per node
                 ne++;
-                this->destroy(1, i);
+                destroy(1, i);
             }
         }
-        lowParticleCount_m = ((nL - ne) <= minNumOfParticlesPerCore);
+        lowParticleCount_m = ((localNum - ne) <= minNumParticlesPerCore);
         reduce(lowParticleCount_m, lowParticleCount_m, OpOr());
     }
 
-    update();
-
     if (lowParticleCount_m) {
         Inform m ("boundp_destroyT a) ", INFORM_ALL_NODES);
-        m << level3 << "Warning low number of particles on some cores nL= " << nL << " ne= " << ne << " NLocal= " << this->getLocalNum() << endl;
+        m << level3 << "Warning low number of particles on some cores localNum= " << localNum << " ne= " << ne << " NLocal= " << getLocalNum() << endl;
     } else {
         boundp();
     }
     calcBeamParameters();
     gatherLoadBalanceStatistics();
-    if(WeHaveEnergyBins()) {
-        const int lastBin = dist_m->GetLastEmittedEnergyBin();
+
+    if(weHaveEnergyBins()) {
+        const int lastBin = dist_m->getLastEmittedEnergyBin();
         for(int i = 0; i < lastBin; i++) {
             binemitted_m[i] = tmpbinemitted[i];
         }
@@ -2403,6 +2032,65 @@ size_t PartBunch::boundp_destroyT() {
     return ne;
 }
 
+size_t PartBunch::destroyT() {
+
+    const unsigned int minNumParticlesPerCore = getMinimumNumberOfParticlesPerCore();
+    std::unique_ptr<size_t[]> tmpbinemitted;
+
+    const size_t localNum = getLocalNum();
+    const size_t totalNum = getTotalNum();
+
+    if(weHaveEnergyBins()) {
+        tmpbinemitted = std::unique_ptr<size_t[]>(new size_t[getNumberOfEnergyBins()]);
+        for(int i = 0; i < getNumberOfEnergyBins(); i++) {
+            tmpbinemitted[i] = 0;
+        }
+        for(unsigned int i = 0; i < localNum; i++) {
+            if (Bin[i] < 0) {
+                destroy(1, i);
+            } else
+                tmpbinemitted[Bin[i]]++;
+        }
+    } else {
+        Inform dmsg("destroy: ", INFORM_ALL_NODES);
+        unsigned int i = 0, j = localNum;
+        while (j > 0 && Bin[j - 1] < 0) -- j;
+
+        while (i + 1 < j) {
+            if (Bin[i] < 0) {
+                this->swap(i,j - 1);
+                -- j;
+
+                while (i + 1 < j && Bin[j - 1] < 0) -- j;
+            }
+            ++ i;
+        }
+
+        j = std::max(j, minNumParticlesPerCore);
+        for(unsigned int i = localNum; i > j; -- i) {
+            destroy(1, i-1, true);
+        }
+        lowParticleCount_m = (j == minNumParticlesPerCore);
+        reduce(lowParticleCount_m, lowParticleCount_m, OpOr());
+    }
+
+    calcBeamParameters();
+    gatherLoadBalanceStatistics();
+
+    if(weHaveEnergyBins()) {
+        const int lastBin = dist_m->getLastEmittedEnergyBin();
+        for(int i = 0; i < lastBin; i++) {
+            binemitted_m[i] = tmpbinemitted[i];
+        }
+    }
+    size_t newTotalNum = getLocalNum();
+    reduce(newTotalNum, newTotalNum, OpAddAssign());
+
+    setTotalNum(newTotalNum);
+
+    return totalNum - newTotalNum;
+}
+
 
 void PartBunch::boundp_destroy() {
 
@@ -2428,41 +2116,39 @@ void PartBunch::boundp_destroy() {
 
     calcBeamParameters();
 
-    double checkfactor = Options::remotePartDel;
-
-    if (checkfactor != 0.0) {
-        // yes we do remote particle delete (why remote ?)
-        if (checkfactor < 0) { // cut in 3D
-            checkfactor *= -1.0;
-            // check the bunch if its full size is larger than checkfactor times of its rms size
-            if(len[0] > checkfactor * rrms_m[0] || len[1] > checkfactor * rrms_m[1] || len[2] > checkfactor * rrms_m[2]) {
-                for(unsigned int ii = 0; ii < this->getLocalNum(); ii++) {
-                    // delete the particle if the ditance to the beam center is larger than 8 times of beam's rms size
-                    if(abs(R[ii](0) - rmean_m(0)) > checkfactor * rrms_m[0] || abs(R[ii](1) - rmean_m(1)) > checkfactor * rrms_m[1] || abs(R[ii](2) - rmean_m(2)) > checkfactor * rrms_m[2]) {
-                        // put particle onto deletion list
-                        destroy(1, ii);
-                        //update bin parameter
-                        if(weHaveBins()) countLost[Bin[ii]] += 1 ;
-                    }
-                }
-            }
-        }
-        else { // cut in 2D only 
-            // Caveats: only make sense for OPAL-cycl
-            // Caveats caveats: need to make OPAL-cycl compatible with OPAL-t w.r.t. the meaning of x,y,z! 
-            // check the bunch if its full size is larger than checkfactor times of its rms size
-            if(len[0] > checkfactor * rrms_m[0] || len[2] > checkfactor * rrms_m[2]) {
-                for(unsigned int ii = 0; ii < this->getLocalNum(); ii++) {
-                    // delete the particle if the ditance to the beam center is larger than 8 times of beam's rms size
-                    if(abs(R[ii](0) - rmean_m(0)) > checkfactor * rrms_m[0] || abs(R[ii](2) - rmean_m(2)) > checkfactor * rrms_m[2]) {
-                        // put particle onto deletion list
-                        destroy(1, ii);
-                        //update bin parameter
-                        if(weHaveBins()) countLost[Bin[ii]] += 1 ;
-                    }
-                }
-            }
-        }
+    int checkfactor = Options::remotePartDel;
+    if (checkfactor != 0) {
+      //INFOMSG("checkfactor= " << checkfactor << endl);
+	// check the bunch if its full size is larger than checkfactor times of its rms size
+	if(checkfactor < 0) {
+	  checkfactor *= -1;
+	  if(len[0] > checkfactor * rrms_m[0] || len[1] > checkfactor * rrms_m[1] || len[2] > checkfactor * rrms_m[2]) {
+	    for(unsigned int ii = 0; ii < this->getLocalNum(); ii++) {
+	      // delete the particle if the ditance to the beam center is larger than 8 times of beam's rms size
+	      if(abs(R[ii](0) - rmean_m(0)) > checkfactor * rrms_m[0] || abs(R[ii](1) - rmean_m(1)) > checkfactor * rrms_m[1] || abs(R[ii](2) - rmean_m(2)) > checkfactor * rrms_m[2]) {
+		// put particle onto deletion list
+		destroy(1, ii);
+		//update bin parameter
+		if(weHaveBins()) countLost[Bin[ii]] += 1 ;
+		// INFOMSG("REMOTE PARTICLE DELETION: ID = " << ID[ii] << ", R = " << R[ii] << ", beam rms = " << rrms_m << endl;);
+	      }
+	    }
+	  }
+	}
+	else {
+	  if(len[0] > checkfactor * rrms_m[0] || len[2] > checkfactor * rrms_m[2]) {
+	    for(unsigned int ii = 0; ii < this->getLocalNum(); ii++) {
+	      // delete the particle if the ditance to the beam center is larger than 8 times of beam's rms size
+	      if(abs(R[ii](0) - rmean_m(0)) > checkfactor * rrms_m[0] || abs(R[ii](2) - rmean_m(2)) > checkfactor * rrms_m[2]) {
+		// put particle onto deletion list
+		destroy(1, ii);
+		//update bin parameter
+		if(weHaveBins()) countLost[Bin[ii]] += 1 ;
+		// INFOMSG("REMOTE PARTICLE DELETION: ID = " << ID[ii] << ", R = " << R[ii] << ", beam rms = " << rrms_m << endl;);
+	      }
+	    }
+	  }
+	}
     }
 
     for(int i = 0; i < dimIdx; i++) {
@@ -2544,10 +2230,9 @@ double PartBunch::calcMeanPhi() {
         py[Bin[ii]] += P[ii](1);
     }
 
+    reduce(px, px + emittedBins, px, OpAddAssign());
+    reduce(py, py + emittedBins, py, OpAddAssign());
     for(int ii = 0; ii < emittedBins; ii++) {
-        reduce(px[ii], px[ii], OpAddAssign());
-        reduce(py[ii], py[ii], OpAddAssign());
-
         phi[ii] = calculateAngle(px[ii], py[ii]);
         meanPhi += phi[ii];
         INFOMSG("Bin " << ii  << "  mean phi = " << phi[ii] * 180.0 / pi - 90.0 << "[degree]" << endl);
@@ -2577,7 +2262,7 @@ bool PartBunch::resetPartBinID2(const double eta) {
     double pMin = 0.0;
     double maxbinIndex = 0;
 
-    for(unsigned long int n = 0; n < this->getLocalNum(); n++) {
+    for(unsigned long int n = 0; n < getLocalNum(); n++) {
         double temp_betagamma = sqrt(pow(P[n](0), 2) + pow(P[n](1), 2));
         if(pMin0 > temp_betagamma)
             pMin0 = temp_betagamma;
@@ -2586,7 +2271,7 @@ bool PartBunch::resetPartBinID2(const double eta) {
     INFOMSG("minimal beta*gamma = " << pMin << endl);
 
     double asinh0 = asinh(pMin);
-    for(unsigned long int n = 0; n < this->getLocalNum(); n++) {
+    for(unsigned long int n = 0; n < getLocalNum(); n++) {
 
         double temp_betagamma = sqrt(pow(P[n](0), 2) + pow(P[n](1), 2));
 
@@ -2618,32 +2303,31 @@ bool PartBunch::resetPartBinID2(const double eta) {
 void PartBunch::setPBins(PartBins *pbin) {
     pbin_m = pbin;
     *gmsg << *pbin_m << endl;
-    SetEnergyBins(pbin_m->getNBins());
+    setEnergyBins(pbin_m->getNBins());
 }
 
 
 void PartBunch::setPBins(PartBinsCyc *pbin) {
 
     pbin_m = pbin;
-    SetEnergyBins(pbin_m->getNBins());
+    setEnergyBins(pbin_m->getNBins());
 }
 
-
 void PartBunch::iterateEmittedBin(int binNumber) {
     binemitted_m[binNumber]++;
 }
 
 bool PartBunch::doEmission() {
     if (dist_m != NULL)
-        return dist_m->GetIfDistEmitting();
+        return dist_m->getIfDistEmitting();
     else
         return false;
 }
 
-bool PartBunch::GetIfBeamEmitting() {
+bool PartBunch::getIfBeamEmitting() {
 
     if (dist_m != NULL) {
-        size_t isBeamEmitted = dist_m->GetIfDistEmitting();
+        size_t isBeamEmitted = dist_m->getIfDistEmitting();
         reduce(isBeamEmitted, isBeamEmitted, OpAddAssign());
         if (isBeamEmitted > 0)
             return true;
@@ -2654,17 +2338,17 @@ bool PartBunch::GetIfBeamEmitting() {
 
 }
 
-int PartBunch::GetLastEmittedEnergyBin() {
+int PartBunch::getLastEmittedEnergyBin() {
     /*
      * Get maximum last emitted energy bin.
      */
-    int lastEmittedBin = dist_m->GetLastEmittedEnergyBin();
+    int lastEmittedBin = dist_m->getLastEmittedEnergyBin();
     reduce(lastEmittedBin, lastEmittedBin, OpMaxAssign());
     return lastEmittedBin;
 }
 
-size_t PartBunch::GetNumberOfEmissionSteps() {
-    return dist_m->GetNumberOfEmissionSteps();
+size_t PartBunch::getNumberOfEmissionSteps() {
+    return dist_m->getNumberOfEmissionSteps();
 }
 
 bool PartBunch::weHaveBins() const {
@@ -2675,13 +2359,13 @@ bool PartBunch::weHaveBins() const {
         return false;
 }
 
-int PartBunch::GetNumberOfEnergyBins() {
-    return dist_m->GetNumberOfEnergyBins();
+int PartBunch::getNumberOfEnergyBins() {
+    return dist_m->getNumberOfEnergyBins();
 }
 
 void PartBunch::Rebin() {
 
-    size_t isBeamEmitting = dist_m->GetIfDistEmitting();
+    size_t isBeamEmitting = dist_m->getIfDistEmitting();
     reduce(isBeamEmitting, isBeamEmitting, OpAddAssign());
     if (isBeamEmitting > 0) {
         *gmsg << "*****************************************************" << endl
@@ -2695,21 +2379,45 @@ void PartBunch::Rebin() {
 
 }
 
-void PartBunch::SetEnergyBins(int numberOfEnergyBins) {
+void PartBunch::setEnergyBins(int numberOfEnergyBins) {
     bingamma_m = std::unique_ptr<double[]>(new double[numberOfEnergyBins]);
     binemitted_m = std::unique_ptr<size_t[]>(new size_t[numberOfEnergyBins]);
     for(int i = 0; i < numberOfEnergyBins; i++)
         binemitted_m[i] = 0;
 }
 
-bool PartBunch::WeHaveEnergyBins() {
+bool PartBunch::weHaveEnergyBins() {
 
     if (dist_m != NULL)
-        return dist_m->GetNumberOfEnergyBins() > 0;
+        return dist_m->getNumberOfEnergyBins() > 0;
     else
         return false;
 }
 
 Vector_t PartBunch::get_pmean_Distribution() const {
-    return dist_m->get_pmean();
-}
+    if (dist_m && dist_m->getType() != DistrTypeT::FROMFILE)
+        return dist_m->get_pmean();
+
+    double gamma = 0.1 / getM() + 1; // set default 0.1 eV
+    return Vector_t(0, 0, sqrt(std::pow(gamma, 2) - 1));
+}
+
+void PartBunch::swap(unsigned int i, unsigned int j) {
+    if (i >= getLocalNum() || j >= getLocalNum() || i == j) return;
+
+    std::swap(R[i], R[j]);
+    std::swap(P[i], P[j]);
+    std::swap(Q[i], Q[j]);
+    std::swap(M[i], M[j]);
+    std::swap(Phi[i], Phi[j]);
+    std::swap(Ef[i], Ef[j]);
+    std::swap(Eftmp[i], Eftmp[j]);
+    std::swap(Bf[i], Bf[j]);
+    std::swap(Bin[i], Bin[j]);
+    std::swap(dt[i], dt[j]);
+    std::swap(PType[i], PType[j]);
+    std::swap(TriID[i], TriID[j]);
+
+    if (interpolationCacheSet_m)
+        std::swap(interpolationCache_m[i], interpolationCache_m[j]);
+}
\ No newline at end of file
diff --git a/src/Classic/Algorithms/PartBunch.h b/src/Classic/Algorithms/PartBunch.h
index e93b122568710926127633b94a3e8fd126594c66..bd839585e0b000ca841853ae676a3b4c120f2b75 100644
--- a/src/Classic/Algorithms/PartBunch.h
+++ b/src/Classic/Algorithms/PartBunch.h
@@ -23,17 +23,19 @@
 #include "Ippl.h"
 #include "Algorithms/PBunchDefs.h"
 #include "Algorithms/Particle.h"
+#include "Algorithms/CoordinateSystemTrafo.h"
 #include "FixedAlgebra/FMatrix.h"
 #include "FixedAlgebra/FVector.h"
 #include "Algorithms/PartBins.h"
 #include "Algorithms/PartBinsCyc.h"
 #include "Algorithms/PartData.h"
+#include "Algorithms/Quaternion.h"
 #include "Utilities/SwitcherError.h"
 #include "Physics/Physics.h"
 
 #include <iosfwd>
 #include <vector>
-#include <memory>
+
 
 class Distribution;
 class LossDataSink;
@@ -63,14 +65,14 @@ public:
     ~PartBunch();
 
     void runTests();
-    
-    bool GetIfBeamEmitting();
-    int GetLastEmittedEnergyBin();
-    size_t GetNumberOfEmissionSteps();
-    int GetNumberOfEnergyBins();
+
+    bool getIfBeamEmitting();
+    int getLastEmittedEnergyBin();
+    size_t getNumberOfEmissionSteps();
+    int getNumberOfEnergyBins();
     void Rebin();
-    void SetEnergyBins(int numberOfEnergyBins);
-    bool WeHaveEnergyBins();
+    void setEnergyBins(int numberOfEnergyBins);
+    bool weHaveEnergyBins();
 
     enum UnitState_t { units = 0, unitless = 1 };
 
@@ -92,9 +94,7 @@ public:
 
     void do_binaryRepart();
 
-    void calcLineDensity();
-    void fillArray(double *lineDensity, const std::list<ListElem> &l);
-    void getLineDensity(std::vector<double> &lineDensity);
+    void calcLineDensity(unsigned int nBins, std::vector<double> &lineDensity, std::pair<double, double> &meshInfo);
 
     void setDistribution(Distribution *d,
                          std::vector<Distribution *> addedDistributions,
@@ -122,7 +122,9 @@ public:
         i.e. copy the particles from the bin structure into the
         particle container
     */
-    size_t EmitParticles(double eZ);
+    size_t emitParticles(double eZ);
+
+    void updateNumTotal();
 
     void rebin();
 
@@ -162,12 +164,11 @@ public:
 
     FieldLayout_t &getFieldLayout();
 
+    void setBCAllPeriodic();
     void setBCAllOpen();
 
     void setBCForDCBeam();
 
-    void setBCAllPeriodic();
-    
     void boundp();
 
     /** delete particles which are too far away from the center of beam*/
@@ -175,6 +176,7 @@ public:
 
     /** This is only temporary in order to get the collimator and pepperpot workinh */
     size_t boundp_destroyT();
+    size_t destroyT();
 
     /* Definiere virtuelle Funktionen, um die Koordinaten auszulesen
      *     */
@@ -235,15 +237,6 @@ public:
 
     void resetInterpolationCache(bool clearCache = false);
 
-    /** EulerAngle[0] = rotation about the y-axis, EulerAngle[1] = rotation about x-axis
-     *  EulerAngle[2] = rotation about the y'-axis */
-
-    void rotateAbout(const Vector_t &Center, const Vector_t &EulerAngles);
-
-    void moveBy(const Vector_t &Center);
-
-    void ResetLocalCoordinateSystem(const int &i, const Vector_t &Orientation, const double &origin);
-
     /**
      * get the spos of the primary beam
      *
@@ -251,24 +244,24 @@ public:
      *
      */
     double get_sPos();
+    void set_sPos(double s);
 
     double   get_gamma() const;
 
-    double get_meanEnergy() const;
+    double get_meanKineticEnergy() const;
     Vector_t get_origin() const;
-    Vector_t get_maxExtend() const;
+    Vector_t get_maxExtent() const;
     Vector_t get_centroid() const;
     Vector_t get_rrms() const;
     Vector_t get_rmean() const;
     Vector_t get_prms() const;
-    Vector_t get_rprrms() const;
+    Vector_t get_rprms() const;
     Vector_t get_pmean() const;
     Vector_t get_pmean_Distribution() const;
     Vector_t get_emit() const;
     Vector_t get_norm_emit() const;
-    
     Vector_t get_hr() const;
-    
+
     double get_Dx() const;
     double get_Dy() const;
 
@@ -326,29 +319,28 @@ public:
     int getStepsPerTurn() const;
 
     /// step in multiple TRACK commands
-    inline void setGlobalTrackStep(long long n) {globalTrackStep_m = n;}
-    inline long long getGlobalTrackStep() const {return globalTrackStep_m;}
+    void setGlobalTrackStep(long long n);
+    long long getGlobalTrackStep() const;
 
     /// step in a TRACK command
-    inline void setLocalTrackStep(long long n) {localTrackStep_m = n;}
-    inline void incTrackSteps() {globalTrackStep_m++; localTrackStep_m++;}
-    inline long long getLocalTrackStep() const {return localTrackStep_m;}
+    void setLocalTrackStep(long long n);
+    void incTrackSteps();
+    long long getLocalTrackStep() const;
 
-    inline void setNumBunch(int n);
-    inline int getNumBunch() const;
+    void setNumBunch(int n);
+    int getNumBunch() const;
 
-    inline void setGlobalMeanR(Vector_t globalMeanR) {globalMeanR_m = globalMeanR;}
-    inline Vector_t getGlobalMeanR() {return globalMeanR_m;}
-    inline void setGlobalToLocalQuaternion(Quaternion_t globalToLocalQuaternion) {
-        globalToLocalQuaternion_m = globalToLocalQuaternion;}
-    inline Quaternion_t getGlobalToLocalQuaternion() {return globalToLocalQuaternion_m;}
+    void setGlobalMeanR(Vector_t globalMeanR);
+    Vector_t getGlobalMeanR();
+    void setGlobalToLocalQuaternion(Quaternion_t globalToLocalQuaternion);
+    Quaternion_t getGlobalToLocalQuaternion();
 
     void setSteptoLastInj(int n);
     int getSteptoLastInj();
 
     /// calculate average angle of longitudinal direction of bins
     double calcMeanPhi();
-    
+
     /// reset Bin[] for each particle according to the method given in paper PAST-AB(064402) by  G. Fubiani et al.
     bool resetPartBinID2(const double eta);
 
@@ -362,37 +354,47 @@ public:
     void resetM(double m);
 
     double getdE();
-    double getBeta() const;
-    double getGamma() const;
+    double getInitialBeta() const;
+    double getInitialGamma() const;
     virtual double getGamma(int i);
     virtual double getBeta(int i);
     virtual void actT();
     const PartData *getReference() const;
 
-    double GetEmissionDeltaT();
+    double getEmissionDeltaT();
+
+    Quaternion_t getQKs3D();
+    void         setQKs3D(Quaternion_t q);
+    Vector_t     getKs3DRefr();
+    void         setKs3DRefr(Vector_t r);
+    Vector_t     getKs3DRefp();
+    void         setKs3DRefp(Vector_t p);
 
     void iterateEmittedBin(int binNumber);
 
+    void calcEMean();
+    void correctEnergy(double avrgp);
+
+    void swap(unsigned int i, unsigned int j);
+
     // Particle container attributes
-    ParticleAttrib< Vector_t > X;      // local 'lab frame' coordinates;
     ParticleAttrib< Vector_t > P;      // particle momentum //  ParticleSpatialLayout<double, 3>::ParticlePos_t P;
     ParticleAttrib< double >   Q;      // charge per simulation particle, unit: C.
     ParticleAttrib< double >   M;      // mass per simulation particle, for multi-species particle tracking, unit:GeV/c^2.
-    ParticleAttrib< double >   Phi;
+    ParticleAttrib< double >   Phi;    // the electric potential
     ParticleAttrib< Vector_t > Ef;     // e field vector
     ParticleAttrib< Vector_t > Eftmp;  // e field vector for gun simulations
 
     ParticleAttrib< Vector_t > Bf;   // b field vector
     ParticleAttrib< int >      Bin;   // holds the bin in which the particle is in, if zero particle is marked for deletion
     ParticleAttrib< double >   dt;   // holds the dt timestep for particle
-    ParticleAttrib< long >     LastSection; // last em-field section
-
 
     ParticleAttrib< short >    PType; // we can distinguish dark current particles from primary particle
     ParticleAttrib< int >      TriID; // holds the ID of triangle that the particle hit. Only for BoundaryGeometry case.
 
-    Vector_t RefPart_R;
-    Vector_t RefPart_P;
+    Vector_t RefPartR_m;
+    Vector_t RefPartP_m;
+    CoordinateSystemTrafo toLabTrafo_m;
 
     /// scalar potential
     Field_t rho_m;
@@ -446,11 +448,6 @@ private:
     double calculateAngle(double x, double y);
     double calculateAngle2(double x, double y);
 
-public:
-    void calcEMean(); // update eKin_m;
-    void correctEnergy(double avrgp);
-private:
-
     /*
       Member variables starts here
     */
@@ -459,11 +456,6 @@ private:
     UnitState_t unit_state_;
     UnitState_t stateOfLastBoundP_;
 
-    /// hold the line-density
-    std::unique_ptr<double[]> lineDensity_m;
-    /// how many bins the line-density has
-    unsigned int nBinsLineDensity_m;
-
     /// holds the centroid of the beam
     double centroid_m[2 * Dim];
 
@@ -479,10 +471,10 @@ private:
     double t_m;
     /// mean energy of the bunch (MeV)
     double eKin_m;
-    /// energy of the bunch
-    double *energy_m;
     /// energy spread of the beam in keV
     double dE_m;
+    /// the position along design trajectory
+    double spos_m;
 
     /// Initialize the translation vector and rotation quaternion
     /// here. Cyclotron tracker will reset these values each timestep
@@ -492,6 +484,13 @@ private:
     Vector_t globalMeanR_m;
     Quaternion_t globalToLocalQuaternion_m;
 
+    /// for coordinate transformation to Ks
+    /// Ks is the coordinate system to calculate statistics
+    Quaternion_t QKs3D_m;
+    /// holds the referernce particle
+    Vector_t     Ks3DRefr_m;
+    Vector_t     Ks3DRefp_m;
+
     /// maximal extend of particles
     Vector_t rmax_m;
     /// minimal extend of particles
@@ -545,22 +544,6 @@ private:
     /// counter to store the distributin dump
     int distDump_m;
 
-    /*
-      For saving particles on a collimator or
-      dead particles (absobed)
-    */
-
-    // variables for stashing a bunch
-    unsigned int stash_Nloc_m;
-    Vector_t stash_iniR_m;
-    PID_t stash_id_m;
-    Ppos_t stash_r_m, stash_p_m, stash_x_m;
-    ParticleAttrib<double> stash_q_m, stash_dt_m;
-    ParticleAttrib<int> stash_bin_m;
-    ParticleAttrib<long> stash_ls_m;
-    ParticleAttrib<short> stash_ptype_m;
-    bool bunchStashed_m;
-
     PartBunch &operator=(const PartBunch &) = delete;
 
     ///
@@ -618,6 +601,30 @@ private:
 };
 
 
+inline Quaternion_t PartBunch::getQKs3D() {
+    return QKs3D_m;
+}
+
+inline void PartBunch::setQKs3D(Quaternion_t q) {
+    QKs3D_m=q;
+}
+
+inline Vector_t PartBunch::getKs3DRefr() {
+    return Ks3DRefr_m;
+}
+
+inline void PartBunch::setKs3DRefr(Vector_t r) {
+    Ks3DRefr_m=r;
+}
+
+inline Vector_t PartBunch::getKs3DRefp() {
+    return Ks3DRefp_m;
+}
+
+inline void PartBunch::setKs3DRefp(Vector_t p) {
+    Ks3DRefp_m=p;
+}
+
 inline
 void PartBunch::switchToUnitlessPositions(bool use_dt_per_particle) {
 
@@ -634,7 +641,6 @@ void PartBunch::switchToUnitlessPositions(bool use_dt_per_particle) {
             dt = this->dt[i];
 
         R[i] /= Vector_t(Physics::c * dt);
-        X[i] /= Vector_t(Physics::c * dt);
     }
 
     unit_state_ = unitless;
@@ -659,7 +665,6 @@ void PartBunch::switchOffUnitlessPositions(bool use_dt_per_particle) {
             dt = this->dt[i];
 
         R[i] *= Vector_t(Physics::c * dt);
-        X[i] *= Vector_t(Physics::c * dt);
     }
 
     unit_state_ = units;
@@ -876,22 +881,24 @@ double PartBunch::get_sPos() {
             z = z / numPrimBeamParts;
         return z;
     } else {
-        const size_t n = getTotalNum();
-        if(n > 0)
-            return sum(R(2)) / getTotalNum();
-        else
-            return 0.0;
+        return spos_m;
     }
 }
 
+inline
+void PartBunch::set_sPos(double s) {
+    spos_m = s;
+}
+
+
 inline
 double   PartBunch::get_gamma() const {
-    return 1.0;
+    return eKin_m / (getM()*1e-6) + 1.0;
 }
 
 
 inline
-double PartBunch::get_meanEnergy() const {
+double PartBunch::get_meanKineticEnergy() const {
     return eKin_m;
 }
 
@@ -901,7 +908,7 @@ Vector_t PartBunch::get_origin() const {
 }
 
 inline
-Vector_t PartBunch::get_maxExtend() const {
+Vector_t PartBunch::get_maxExtent() const {
     return rmax_m;
 }
 
@@ -916,7 +923,7 @@ Vector_t PartBunch::get_rrms() const {
 }
 
 inline
-Vector_t PartBunch::get_rprrms() const {
+Vector_t PartBunch::get_rprms() const {
     return rprms_m;
 }
 
@@ -1044,6 +1051,31 @@ int PartBunch::getStepsPerTurn() const {
     return stepsPerTurn_m;
 }
 
+inline
+void PartBunch::setGlobalTrackStep(long long n) {
+    globalTrackStep_m = n;
+}
+
+inline
+long long PartBunch::getGlobalTrackStep() const {
+    return globalTrackStep_m;
+}
+
+inline
+void PartBunch::setLocalTrackStep(long long n) {
+    localTrackStep_m = n;
+}
+
+inline
+void PartBunch::incTrackSteps() {
+    globalTrackStep_m++; localTrackStep_m++;
+}
+
+inline
+long long PartBunch::getLocalTrackStep() const {
+    return localTrackStep_m;
+}
+
 inline
 void PartBunch::setNumBunch(int n) {
     numBunch_m = n;
@@ -1054,6 +1086,27 @@ int PartBunch::getNumBunch() const {
     return numBunch_m;
 }
 
+inline
+void PartBunch::setGlobalMeanR(Vector_t globalMeanR) {
+    globalMeanR_m = globalMeanR;
+}
+
+inline
+Vector_t PartBunch::getGlobalMeanR() {
+    return globalMeanR_m;
+}
+
+inline
+void PartBunch::setGlobalToLocalQuaternion(Quaternion_t globalToLocalQuaternion) {
+
+    globalToLocalQuaternion_m = globalToLocalQuaternion;
+}
+
+inline
+Quaternion_t PartBunch::getGlobalToLocalQuaternion() {
+    return globalToLocalQuaternion_m;
+}
+
 inline
 void PartBunch::setSteptoLastInj(int n) {
     SteptoLastInj_m = n;
@@ -1100,12 +1153,12 @@ double PartBunch::getdE() {
 }
 
 inline
-double PartBunch::getBeta() const {
+double PartBunch::getInitialBeta() const {
     return reference->getBeta();
 }
 
 inline
-double PartBunch::getGamma() const {
+double PartBunch::getInitialGamma() const {
     return reference->getGamma();
 }
 
@@ -1133,4 +1186,4 @@ Inform &operator<<(Inform &os, PartBunch &p) {
 }
 
 
-#endif // OPAL_PartBunch_HH
+#endif // OPAL_PartBunch_HH
\ No newline at end of file
diff --git a/src/Classic/Algorithms/PartPusher.h b/src/Classic/Algorithms/PartPusher.h
index c66c2e56bb2423af4830bbfea63cb3002d38eb48..4ece9048368e5e43ffdf8aab8927086635d69b38 100644
--- a/src/Classic/Algorithms/PartPusher.h
+++ b/src/Classic/Algorithms/PartPusher.h
@@ -17,7 +17,7 @@ public:
     void initialise(const PartData *ref);
     void kick(const Vector_t &R, Vector_t &P, const Vector_t &Ef, const Vector_t &Bf, const double &dt) const;
     void kick(const Vector_t &R, Vector_t &P, const Vector_t &Ef, const Vector_t &Bf, const double &dt, const double &mass, const double &charge) const;
-    void push(Vector_t &R, const Vector_t &P, const double &dt);
+    void push(Vector_t &R, const Vector_t &P, const double &dt) const;
 private:
     const PartData *itsReference;
 };
@@ -93,7 +93,7 @@ inline void BorisPusher::kick(const Vector_t &R, Vector_t &P, const Vector_t &Ef
 }
 
 
-inline void BorisPusher::push(Vector_t &R, const Vector_t &P, const double &dt) {
+inline void BorisPusher::push(Vector_t &R, const Vector_t &P, const double &dt) const {
     /** \f[ \vec{x}_{n+1/2} = \vec{x}_{n} + \frac{1}{2}\vec{v}_{n-1/2}\quad (= \vec{x}_{n} + \frac{\Delta t}{2} \frac{\vec{\beta}_{n-1/2}\gamma_{n-1/2}}{\gamma_{n-1/2}}) \f]
      *
      * \code
@@ -103,4 +103,4 @@ inline void BorisPusher::push(Vector_t &R, const Vector_t &P, const double &dt)
     R += 0.5 * P / sqrt(1.0 + dot(P, P));
 }
 
-#endif
+#endif
\ No newline at end of file
diff --git a/src/Classic/Algorithms/Vektor.h b/src/Classic/Algorithms/Vektor.h
index 7b05057eef5beebdd0e3838eafd27817b08d23de..21842d8d951fda53e5e7b1be7ea3589071fc617f 100644
--- a/src/Classic/Algorithms/Vektor.h
+++ b/src/Classic/Algorithms/Vektor.h
@@ -5,127 +5,11 @@
 
 #include "AppTypes/Vektor.h"
 
-template <class, unsigned>
-class Tenzor;
-
 typedef Vektor<double, 3> Vector_t;
 
-void normalize(Vector_t & vec);
-
-class Quaternion: public Vektor<double, 4> {
-public:
-    Quaternion();
-    Quaternion(const Quaternion &);
-    Quaternion(const double &, const double &, const double &, const double &);
-    Quaternion(const Vector_t &);
-    Quaternion(const double &, const Vector_t &);
-
-    const Quaternion operator*(const double &) const;
-    const Quaternion operator*(const Quaternion &) const;
-    Quaternion& operator*=(const Quaternion &);
-    const Quaternion operator/(const double &) const;
-
-    double Norm() const;
-    double length() const;
-    Quaternion & normalize();
-
-    bool isUnit() const;
-    bool isPure() const;
-    bool isPureUnit() const;
-
-    const Quaternion inverse() const;
-    const Quaternion conjugate() const;
-
-    double real() const;
-    const Vector_t imag() const;
-
-    const Vector_t rotate(const Vector_t &) const;
-
-    const Tenzor<double, 3> getRotationMatrix() const;
-};
-
-typedef Quaternion Quaternion_t;
-//typedef Vektor<double, 4> Quaternion_t;  // used in ParallelCyclotron.{cpp,h}
-
-Quaternion getQuaternion(Vector_t u, Vector_t v);
-
-
-inline
-Quaternion::Quaternion():
-    Vektor<double, 4>(0.0)
-{}
-
-inline
-Quaternion::Quaternion(const Quaternion & quat):
-    Vektor<double, 4>(quat)
-{}
-
-inline
-Quaternion::Quaternion(const double & x0, const double & x1, const double & x2, const double & x3):
-    Vektor<double, 4>(x0, x1, x2, x3)
-{}
-
-inline
-Quaternion::Quaternion(const Vector_t & vec):
-    Quaternion(0.0, vec(0), vec(1), vec(2))
-{}
-
 inline
-Quaternion::Quaternion(const double & realPart, const Vector_t & vec):
-    Quaternion(realPart, vec(0), vec(1), vec(2))
-{}
-
-inline
-double Quaternion::Norm() const
-{
-    return dot(*this, *this);
+double euclidian_norm(Vector_t a) {
+    return sqrt(dot(a,a));
 }
 
-inline
-double Quaternion::length() const
-{
-    return sqrt(this->Norm());
-}
-
-inline
-bool Quaternion::isUnit() const
-{
-    return (std::abs(this->Norm() - 1.0) < 1e-12);
-}
-
-inline
-bool Quaternion::isPure() const
-{
-    return (std::abs((*this)(0)) < 1e-12);
-}
-
-inline
-bool Quaternion::isPureUnit() const
-{
-    return (this->isPure() && this->isUnit());
-}
-
-inline
-const Quaternion Quaternion::conjugate() const
-{
-    Quaternion quat(this->real(), -this->imag());
-
-    return quat;
-}
-
-inline
-double Quaternion::real() const
-{
-    return (*this)(0);
-}
-
-inline
-const Vector_t Quaternion::imag() const
-{
-    Vector_t vec((*this)(1), (*this)(2), (*this)(3));
-
-    return vec;
-}
-
-
-#endif
+#endif
\ No newline at end of file
diff --git a/src/Classic/BeamlineCore/CMakeLists.txt b/src/Classic/BeamlineCore/CMakeLists.txt
index 82c20c42f33fe083bfccc18fbb716ccd1f13c198..3990d7d87f53c6d593f09f6f10483e6ec6145582 100644
--- a/src/Classic/BeamlineCore/CMakeLists.txt
+++ b/src/Classic/BeamlineCore/CMakeLists.txt
@@ -3,18 +3,19 @@ set (_SRCS
   CollimatorRep.cpp
   CorrectorRep.cpp
   CyclotronRep.cpp
+  CyclotronValleyRep.cpp
   DegraderRep.cpp
   DriftRep.cpp
   MarkerRep.cpp
   MonitorRep.cpp
   MultipoleRep.cpp
   Octupole.cpp
+  ParallelPlateRep.cpp
   PatchRep.cpp
   ProbeRep.cpp
   Quadrupole.cpp
   RBendRep.cpp
   RFCavityRep.cpp
-  TravelingWaveRep.cpp
   SBendRep.cpp
   SeparatorRep.cpp
   SeptumRep.cpp
@@ -23,17 +24,55 @@ set (_SRCS
   SkewQuadrupole.cpp
   SkewSextupole.cpp
   SolenoidRep.cpp
+  SourceRep.cpp
+  StripperRep.cpp
+  TravelingWaveRep.cpp
   XCorrectorRep.cpp
   XMonitorRep.cpp
   YCorrectorRep.cpp
   YMonitorRep.cpp
-  ParallelPlateRep.cpp
-  CyclotronValleyRep.cpp
-  StripperRep.cpp
   )
 
 include_directories (
   ${CMAKE_CURRENT_SOURCE_DIR}
   )
 
-add_sources(${_SRCS})
+ADD_OPAL_SOURCES(${_SRCS})
+
+set (HDRS
+    BeamBeamRep.h
+    CollimatorRep.h
+    CorrectorRep.h
+    CyclotronRep.h
+    CyclotronValleyRep.h
+    DegraderRep.h
+    DriftRep.h
+    MarkerRep.h
+    MonitorRep.h
+    MultipoleRep.h
+    Octupole.h
+    ParallelPlateRep.h
+    PatchRep.h
+    ProbeRep.h
+    Quadrupole.h
+    RBendRep.h
+    RFCavityRep.h
+    SBendRep.h
+    SeparatorRep.h
+    SeptumRep.h
+    Sextupole.h
+    SingleMultipole.h
+    SkewOctupole.h
+    SkewQuadrupole.h
+    SkewSextupole.h
+    SolenoidRep.h
+    SourceRep.h
+    StripperRep.h
+    TravelingWaveRep.h
+    XCorrectorRep.h
+    XMonitorRep.h
+    YCorrectorRep.h
+    YMonitorRep.h
+)
+
+install (FILES ${HDRS} DESTINATION "${CMAKE_INSTALL_PREFIX}/include/BeamlineCore")
\ No newline at end of file
diff --git a/src/Classic/BeamlineCore/RBendRep.cpp b/src/Classic/BeamlineCore/RBendRep.cpp
index c916ea618b8de9984d686f9dfbaae52b0468761b..76ea92f9f1fdb8a560ca60c75f589c7b3d074d6b 100644
--- a/src/Classic/BeamlineCore/RBendRep.cpp
+++ b/src/Classic/BeamlineCore/RBendRep.cpp
@@ -41,31 +41,6 @@ namespace {
             &RBendRep::getElementLength,
             &RBendRep::setElementLength
         },
-        {
-            "BY",
-            &RBendRep::getB,
-            &RBendRep::setB
-        },
-        {
-            "E1",
-            &RBendRep::getEntryFaceRotation,
-            &RBendRep::setEntryFaceRotation
-        },
-        {
-            "E2",
-            &RBendRep::getExitFaceRotation,
-            &RBendRep::setExitFaceRotation
-        },
-        {
-            "H1",
-            &RBendRep::getEntryFaceCurvature,
-            &RBendRep::setEntryFaceCurvature
-        },
-        {
-            "H2",
-            &RBendRep::getExitFaceCurvature,
-            &RBendRep::setExitFaceCurvature
-        },
         { 0, 0, 0 }
     };
 }
@@ -111,35 +86,7 @@ ElementBase *RBendRep::clone() const {
 
 
 Channel *RBendRep::getChannel(const std::string &aKey, bool create) {
-    if(aKey[0] == 'a'  ||  aKey[0] == 'b') {
-        int n = 0;
-
-        for(std::string::size_type k = 1; k < aKey.length(); k++) {
-            if(isdigit(aKey[k])) {
-                n = 10 * n + aKey[k] - '0';
-            } else {
-                return 0;
-            }
-        }
-
-        if(aKey[0] == 'b') {
-            return new IndexedChannel<RBendRep>
-                   (*this, &RBendRep::getNormalComponent,
-                    &RBendRep::setNormalComponent, n);
-        } else {
-            return new IndexedChannel<RBendRep>
-                   (*this, &RBendRep::getSkewComponent,
-                    &RBendRep::setSkewComponent, n);
-        }
-    } else {
-        for(const Entry *entry = entries; entry->name != 0; ++entry) {
-            if(aKey == entry->name) {
-                return new IndirectChannel<RBendRep>(*this, entry->get, entry->set);
-            }
-        }
-
-        return ElementBase::getChannel(aKey, create);
-    }
+    return ElementBase::getChannel(aKey, create);
 }
 
 
@@ -168,32 +115,6 @@ ElementImage *RBendRep::getImage() const {
         image->setAttribute(entry->name, (this->*(entry->get))());
     }
 
-    for(int n = 1; n <= field.order(); n++) {
-        char buffer[20];
-        char *p = buffer;
-        int k = n;
-
-        while(k != 0) {
-            *p++ = k % 10 + '0';
-            k /= 10;
-        }
-
-        std::string name(" ");
-        while(p > buffer) name += *--p;
-
-        double b = field.getNormalComponent(n);
-        if(b != 0.0) {
-            name[0] = 'b';
-            image->setAttribute(name, b);
-        }
-
-        double a = field.getSkewComponent(n);
-        if(a != 0.0) {
-            name[0] = 'a';
-            image->setAttribute(name, a);
-        }
-    }
-
     return image;
 }
 
@@ -267,4 +188,4 @@ ElementBase *RBendRep::makeFieldWrapper() {
     ElementBase *wrap = new RBendWrapper(this);
     wrap->setName(getName());
     return wrap;
-}
+}
\ No newline at end of file
diff --git a/src/Classic/BeamlineCore/RFCavityRep.cpp b/src/Classic/BeamlineCore/RFCavityRep.cpp
index 7da50d6bba99e7abb6acf6571089594d32e08e8c..5e67daecdf8e2d8455bf906865f0349122d69c48 100644
--- a/src/Classic/BeamlineCore/RFCavityRep.cpp
+++ b/src/Classic/BeamlineCore/RFCavityRep.cpp
@@ -70,7 +70,8 @@ RFCavityRep::RFCavityRep():
 
 
 RFCavityRep::RFCavityRep(const RFCavityRep &right):
-    RFCavity(right)
+    RFCavity(right),
+    geometry(right.geometry)
 {}
 
 
@@ -159,4 +160,4 @@ void RFCavityRep::setPhase(double phase) {
 
 void RFCavityRep::setIgnore(bool ignore) {
     ignoreCavities = ignore;
-}
+}
\ No newline at end of file
diff --git a/src/Classic/BeamlineGeometry/CMakeLists.txt b/src/Classic/BeamlineGeometry/CMakeLists.txt
index 5978d1afda744f48716d37ebefa7b886d2206f2c..520c5b47931486b0352a1af508899a8781d0a68a 100644
--- a/src/Classic/BeamlineGeometry/CMakeLists.txt
+++ b/src/Classic/BeamlineGeometry/CMakeLists.txt
@@ -17,4 +17,21 @@ include_directories (
   ${CMAKE_CURRENT_SOURCE_DIR}
   )
 
-add_sources(${_SRCS})
+ADD_OPAL_SOURCES(${_SRCS})
+
+set (HDRS
+    Euclid3DGeometry.h
+    Euclid3D.h
+    Geometry.h
+    Matrix3D.h
+    NullGeometry.h
+    OffsetGeometry.h
+    PlanarArcGeometry.h
+    RBendGeometry.h
+    Rotation3D.h
+    SRotatedGeometry.h
+    StraightGeometry.h
+    Vector3D.h
+)
+
+install (FILES ${HDRS} DESTINATION "${CMAKE_INSTALL_PREFIX}/include/BeamlineGeometry")
\ No newline at end of file
diff --git a/src/Classic/Beamlines/Beamline.cpp b/src/Classic/Beamlines/Beamline.cpp
index 507c333a3182e04a196f3a0c865b9205a3e97860..aac259dfe7fdae498bea49a6a885deb45aeacd13 100644
--- a/src/Classic/Beamlines/Beamline.cpp
+++ b/src/Classic/Beamlines/Beamline.cpp
@@ -45,3 +45,15 @@ Beamline::Beamline(const std::string &name):
 
 Beamline::~Beamline()
 {}
+
+Vector_t Beamline::getOrigin3D() const {
+    return Vector_t(0);
+}
+
+Quaternion Beamline::getCoordTransformationTo() const {
+    return Quaternion(1, 0, 0, 0);
+}
+
+bool Beamline::getRelativeFlag() const {
+    return false;
+}
\ No newline at end of file
diff --git a/src/Classic/Beamlines/Beamline.h b/src/Classic/Beamlines/Beamline.h
index ad29a67263696962b1b22139a44a76d754dea170..ae005b14cd2682458234fde5c7fbc770ca39f560 100644
--- a/src/Classic/Beamlines/Beamline.h
+++ b/src/Classic/Beamlines/Beamline.h
@@ -21,6 +21,8 @@
 // ------------------------------------------------------------------------
 
 #include "AbsBeamline/ElementBase.h"
+#include "Algorithms/Vektor.h"
+#include "Algorithms/Quaternion.h"
 
 class CLRangeError;
 
@@ -49,10 +51,13 @@ public:
     //  exception.
     virtual void iterate(BeamlineVisitor &, bool reverse) const = 0;
 
+    virtual Vector_t getOrigin3D() const;
+    virtual Quaternion getCoordTransformationTo() const;
+    virtual bool getRelativeFlag() const;
 private:
 
     // Not implemented.
     void operator=(const Beamline &);
 };
 
-#endif // CLASSIC_Beamline_HH
+#endif // CLASSIC_Beamline_HH
\ No newline at end of file
diff --git a/src/Classic/Beamlines/CMakeLists.txt b/src/Classic/Beamlines/CMakeLists.txt
index ffc229d86ee938141a2e5ce408d9c4dcc46611d4..f6bb5d3271267f470c4a7b18fc52ecc5c2587f9d 100644
--- a/src/Classic/Beamlines/CMakeLists.txt
+++ b/src/Classic/Beamlines/CMakeLists.txt
@@ -1,14 +1,26 @@
 set (_SRCS
-  Beamline.cpp
-  BeamlineGeometry.cpp
-  ElmPtr.cpp
-  FlaggedBeamline.cpp
-  FlaggedElmPtr.cpp
-  SimpleBeamline.cpp
-  )
+    Beamline.cpp
+    BeamlineGeometry.cpp
+    ElmPtr.cpp
+    FlaggedBeamline.cpp
+    FlaggedElmPtr.cpp
+    SimpleBeamline.cpp
+ )
 
 include_directories (
   ${CMAKE_CURRENT_SOURCE_DIR}
   )
 
-add_sources(${_SRCS})
\ No newline at end of file
+ADD_OPAL_SOURCES(${_SRCS})
+
+set (HDRS
+    BeamlineGeometry.h
+    Beamline.h
+    ElmPtr.h
+    FlaggedBeamline.h
+    FlaggedElmPtr.h
+    SimpleBeamline.h
+    TBeamline.h
+)
+
+install (FILES ${HDRS} DESTINATION "${CMAKE_INSTALL_PREFIX}/include/Beamlines")
\ No newline at end of file
diff --git a/src/Classic/Beamlines/TBeamline.h b/src/Classic/Beamlines/TBeamline.h
index 3598a2cb1ff480c4ce46d85e4f70f9ce9c43853c..711b29fd2717e94350b5920db51ed4071733e8dd 100644
--- a/src/Classic/Beamlines/TBeamline.h
+++ b/src/Classic/Beamlines/TBeamline.h
@@ -24,6 +24,8 @@
 #include "AbsBeamline/BeamlineVisitor.h"
 #include "Beamlines/BeamlineGeometry.h"
 #include "Utilities/CLRangeError.h"
+#include "Algorithms/Vektor.h"
+#include "Algorithms/Quaternion.h"
 #include <algorithm>
 #include <list>
 
@@ -143,11 +145,23 @@ public:
     /// Prepend a T object.
     virtual void prepend(const T &);
 
+    void setOrigin3D(const Vector_t& ori);
+    Vector_t getOrigin3D() const;
+
+    void setCoordTransformationTo(const Quaternion& trafoTo);
+    Quaternion getCoordTransformationTo() const;
+
+    void setRelativeFlag(bool flag);
+    bool getRelativeFlag() const;
 protected:
 
     /// The beamline geometry.
     //  Exists to match the interface for ElementBase.
     BeamlineGeometry itsGeometry;
+
+    Vector_t itsOrigin_m;
+    Quaternion itsCoordTrafoTo_m;
+    bool relativePositions_m;
 };
 
 
@@ -156,19 +170,34 @@ protected:
 
 template <class T>
 TBeamline<T>::TBeamline():
-    Beamline(), std::list<T>(), itsGeometry(*this)
+    Beamline(),
+    std::list<T>(),
+    itsGeometry(*this),
+    itsOrigin_m(0),
+    itsCoordTrafoTo_m(1.0, 0.0, 0.0, 0.0),
+    relativePositions_m(false)
 {}
 
 
 template <class T>
 TBeamline<T>::TBeamline(const std::string &name):
-    Beamline(name), std::list<T>(), itsGeometry(*this)
+    Beamline(name),
+    std::list<T>(),
+    itsGeometry(*this),
+    itsOrigin_m(0),
+    itsCoordTrafoTo_m(1.0, 0.0, 0.0, 0.0),
+    relativePositions_m(false)
 {}
 
 
 template <class T>
 TBeamline<T>::TBeamline(const TBeamline<T> &rhs):
-    Beamline(rhs), std::list<T>(rhs), itsGeometry(*this)
+    Beamline(rhs),
+    std::list<T>(rhs),
+    itsGeometry(*this),
+    itsOrigin_m(rhs.itsOrigin_m),
+    itsCoordTrafoTo_m(rhs.itsCoordTrafoTo_m),
+    relativePositions_m(rhs.relativePositions_m)
 {}
 
 
@@ -211,6 +240,10 @@ TBeamline<T> *TBeamline<T>::clone() const {
         line->append(newObj);
     }
 
+    line->itsOrigin_m = itsOrigin_m;
+    line->itsCoordTrafoTo_m = itsCoordTrafoTo_m;
+    line->relativePositions_m = relativePositions_m;
+
     return line;
 }
 
@@ -230,6 +263,10 @@ TBeamline<T> *TBeamline<T>::copyStructure() {
             line->append(newObj);
         }
 
+        line->itsOrigin_m = itsOrigin_m;
+        line->itsCoordTrafoTo_m = itsCoordTrafoTo_m;
+        line->relativePositions_m = relativePositions_m;
+
         return line;
     }
 }
@@ -405,4 +442,33 @@ void TBeamline<T>::prepend(const T &obj) {
     this->push_front(obj);
 }
 
+template <class T> inline
+void TBeamline<T>::setOrigin3D(const Vector_t& ori) {
+    itsOrigin_m = ori;
+}
+
+template <class T> inline
+Vector_t TBeamline<T>::getOrigin3D() const {
+    return itsOrigin_m;
+}
+
+template <class T> inline
+void TBeamline<T>::setCoordTransformationTo(const Quaternion& trafoTo) {
+    itsCoordTrafoTo_m = trafoTo;
+}
+
+template <class T> inline
+Quaternion TBeamline<T>::getCoordTransformationTo() const {
+    return itsCoordTrafoTo_m;
+}
+
+template <class T> inline
+void TBeamline<T>::setRelativeFlag(bool flag) {
+    relativePositions_m = flag;
+}
+
+template <class T> inline
+bool TBeamline<T>::getRelativeFlag() const {
+    return relativePositions_m;
+}
 #endif // CLASSIC_TBeamline_HH
\ No newline at end of file
diff --git a/src/Classic/CMakeLists.txt b/src/Classic/CMakeLists.txt
index db2a5d33ae2c9f12c3803014e6fb2ba972a458a6..ee9d4542e90dde3c5e836fd6a609ff8668807de8 100644
--- a/src/Classic/CMakeLists.txt
+++ b/src/Classic/CMakeLists.txt
@@ -1,25 +1,26 @@
-add_subdirectory (AbsBeamline)
-add_subdirectory (Algebra)
-add_subdirectory (Algorithms)
-add_subdirectory (BeamlineCore)
-add_subdirectory (BeamlineGeometry)
-add_subdirectory (Beamlines)
-add_subdirectory (Channels)
-add_subdirectory (ComponentWrappers)
-add_subdirectory (Construction)
-add_subdirectory (Fields)
-add_subdirectory (Filters)
-add_subdirectory (FixedAlgebra)
-add_subdirectory (MemoryManagement)
-add_subdirectory (Parser)
-add_subdirectory (Physics)
-add_subdirectory (Solvers)
-add_subdirectory (Structure)
-add_subdirectory (Utilities)
+set (CLASSIC_SRC_DIR ${CMAKE_CURRENT_SOURCE_DIR} PARENT_SCOPE)
+
+add_subdirectory(AbsBeamline)
+add_subdirectory(Algebra)
+add_subdirectory(Algorithms)
+add_subdirectory(BeamlineCore)
+add_subdirectory(BeamlineGeometry)
+add_subdirectory(Beamlines)
+add_subdirectory(Channels)
+add_subdirectory(ComponentWrappers)
+add_subdirectory(Construction)
+add_subdirectory(Fields)
+add_subdirectory(Filters)
+add_subdirectory(FixedAlgebra)
+add_subdirectory(MemoryManagement)
+add_subdirectory(Parser)
+add_subdirectory(Physics)
+add_subdirectory(Solvers)
+add_subdirectory(Structure)
+add_subdirectory(Utilities)
 
-install (FILES Utilities/ClassicException.h Utilities/Options.h Utilities/Random.h
+install (FILES Utilities/ClassicException.h Utilities/ClassicRandom.h Utilities/Options.h
     DESTINATION "${CMAKE_INSTALL_PREFIX}/include/Utilities"
-    )
+)
 
-set (CLASSIC_SRC_DIR ${CMAKE_CURRENT_SOURCE_DIR} PARENT_SCOPE)
-set (OPAL_SRCS "${OPAL_SRCS}" PARENT_SCOPE)
\ No newline at end of file
+set(OPAL_SRCS "${OPAL_SRCS}" PARENT_SCOPE)
\ No newline at end of file
diff --git a/src/Classic/Channels/CMakeLists.txt b/src/Classic/Channels/CMakeLists.txt
index f8c37f596c7fd28379752e2a5be9b3ca153d7e94..8d8a3119fc43944d5e5803ef890900606bc15a7c 100644
--- a/src/Classic/Channels/CMakeLists.txt
+++ b/src/Classic/Channels/CMakeLists.txt
@@ -1,10 +1,21 @@
 set (_SRCS
-  Channel.cpp
-  ConstChannel.cpp
-  )
+    Channel.cpp
+    ConstChannel.cpp
+)
 
 include_directories (
   ${CMAKE_CURRENT_SOURCE_DIR}
   )
 
-add_sources(${_SRCS})
\ No newline at end of file
+ADD_OPAL_SOURCES(${_SRCS})
+
+
+set (HDRS
+    Channel.h
+    ConstChannel.h
+    DirectChannel.h
+    IndexedChannel.h
+    IndirectChannel.h
+)
+
+install (FILES ${HDRS} DESTINATION "${CMAKE_INSTALL_PREFIX}/include/Channels")
\ No newline at end of file
diff --git a/src/Classic/ComponentWrappers/CMakeLists.txt b/src/Classic/ComponentWrappers/CMakeLists.txt
index 7ccf265ff9eee94152ccefc9e084027d3da14071..6b76414fdba2a911636e936eab7504aee65e1070 100644
--- a/src/Classic/ComponentWrappers/CMakeLists.txt
+++ b/src/Classic/ComponentWrappers/CMakeLists.txt
@@ -10,4 +10,14 @@ include_directories (
   ${CMAKE_CURRENT_SOURCE_DIR}
   )
 
-add_sources(${_SRCS})
\ No newline at end of file
+ADD_OPAL_SOURCES(${_SRCS})
+
+set (HDRS
+    CorrectorWrapper.h
+    CyclotronWrapper.h
+    MultipoleWrapper.h
+    RBendWrapper.h
+    SBendWrapper.h
+)
+
+install (FILES ${HDRS} DESTINATION "${CMAKE_INSTALL_PREFIX}/include/ComponentWrappers")
\ No newline at end of file
diff --git a/src/Classic/Construction/CMakeLists.txt b/src/Classic/Construction/CMakeLists.txt
index cc25cbf8f62165a080f8980c457ca4411cb963b6..101b2034a584897686bb61494f0bb6d8e56929d1 100644
--- a/src/Classic/Construction/CMakeLists.txt
+++ b/src/Classic/Construction/CMakeLists.txt
@@ -7,4 +7,11 @@ include_directories (
   ${CMAKE_CURRENT_SOURCE_DIR}
   )
 
-add_sources(${_SRCS})
\ No newline at end of file
+ADD_OPAL_SOURCES(${_SRCS})
+
+set (HDRS
+    ElementFactory.h
+    Factory.h
+)
+
+install (FILES ${HDRS} DESTINATION "${CMAKE_INSTALL_PREFIX}/include/Construction")
\ No newline at end of file
diff --git a/src/Classic/Fields/Astra1DDynamic.cpp b/src/Classic/Fields/Astra1DDynamic.cpp
index 10a4aa06b1a46d6f9736c825892892858416c0de..bae21548587c5afe2d73a139d85b3031a21d91c5 100644
--- a/src/Classic/Fields/Astra1DDynamic.cpp
+++ b/src/Classic/Fields/Astra1DDynamic.cpp
@@ -1,6 +1,8 @@
 #include "Fields/Astra1DDynamic.h"
 #include "Fields/Fieldmap.hpp"
 #include "Physics/Physics.h"
+#include "Utilities/GeneralClassicException.h"
+
 #include "gsl/gsl_interp.h"
 #include "gsl/gsl_spline.h"
 #include "gsl/gsl_fft_real.h"
@@ -50,6 +52,8 @@ Astra1DDynamic::Astra1DDynamic(std::string aFilename):
         if(!parsing_passed && !file.eof()) {
             disableFieldmapWarning();
             zend_m = zbegin_m - 1e-3;
+            throw GeneralClassicException("Astra1DDynamic::Astra1DDynamic",
+                                          "An error occured when reading the fieldmap '" + Filename_m + "'");
         } else {
             // conversion from MHz to Hz and from frequency to angular frequency
             frequency_m *= two_pi * 1e6;
@@ -261,4 +265,4 @@ void Astra1DDynamic::getOnaxisEz(vector<pair<double, double> > & F) {
     for(int i = 0; i < num_gridpz_m; ++ i) {
         F[i].second /= Ez_max;
     }
-}
+}
\ No newline at end of file
diff --git a/src/Classic/Fields/Astra1DDynamic.h b/src/Classic/Fields/Astra1DDynamic.h
index f9f5aa9358c7a09dc01dd2fed8ebbf4b20c46a44..58b69da246fb32aeeceac41bb04ee51b36f1006a 100644
--- a/src/Classic/Fields/Astra1DDynamic.h
+++ b/src/Classic/Fields/Astra1DDynamic.h
@@ -16,6 +16,7 @@ public:
     virtual void setFrequency(double freq);
     virtual void getOnaxisEz(std::vector<std::pair<double, double> > & F);
 
+    virtual bool isInside(const Vector_t &r) const;
 private:
     Astra1DDynamic(std::string aFilename);
     ~Astra1DDynamic();
@@ -38,4 +39,9 @@ private:
     friend class Fieldmap;
 };
 
-#endif
+inline bool Astra1DDynamic::isInside(const Vector_t &r) const
+{
+    return r(2) >= zbegin_m && r(2) < zend_m;
+}
+
+#endif
\ No newline at end of file
diff --git a/src/Classic/Fields/Astra1DDynamic_fast.cpp b/src/Classic/Fields/Astra1DDynamic_fast.cpp
index 7a78d530b4c6a689111c976af8b7ddd9a878e936..1f1f62f558e5e85df9ff39f014a58b226e35da4a 100644
--- a/src/Classic/Fields/Astra1DDynamic_fast.cpp
+++ b/src/Classic/Fields/Astra1DDynamic_fast.cpp
@@ -1,4 +1,5 @@
 #include "Fields/Astra1DDynamic_fast.h"
+#include "Utilities/GeneralClassicException.h"
 #include "Physics/Physics.h"
 
 #include <fstream>
@@ -30,6 +31,8 @@ Astra1DDynamic_fast::Astra1DDynamic_fast(std::string aFilename):
     if(!parsing_passed) {
         disableFieldmapWarning();
         zend_m = zbegin_m - 1e-3;
+        throw GeneralClassicException("Astra1DDynamic_fast::Astra1DDynamic_fast",
+                                      "An error occured when reading the fieldmap '" + Filename_m + "'");
         return;
     }
 
@@ -182,4 +185,4 @@ int Astra1DDynamic_fast::stripFileHeader(std::ifstream &file) {
     interpreteLine<double>(file, tmpDouble);
 
     return accuracy;
-}
+}
\ No newline at end of file
diff --git a/src/Classic/Fields/Astra1DElectroStatic.cpp b/src/Classic/Fields/Astra1DElectroStatic.cpp
index c0b445fbb4c13f4b325b42dd6e9bb630188385c9..b3419c0ca6efaac909402e19010b6598c5f60ca4 100644
--- a/src/Classic/Fields/Astra1DElectroStatic.cpp
+++ b/src/Classic/Fields/Astra1DElectroStatic.cpp
@@ -1,6 +1,8 @@
 #include "Fields/Astra1DElectroStatic.h"
 #include "Fields/Fieldmap.hpp"
 #include "Physics/Physics.h"
+#include "Utilities/GeneralClassicException.h"
+
 #include "gsl/gsl_interp.h"
 #include "gsl/gsl_spline.h"
 #include "gsl/gsl_fft_real.h"
@@ -48,6 +50,8 @@ Astra1DElectroStatic::Astra1DElectroStatic(std::string aFilename)
         if(!parsing_passed && !file.eof()) {
             disableFieldmapWarning();
             zend_m = zbegin_m - 1e-3;
+            throw GeneralClassicException("Astra1DElectroStatic::Astra1DElectroStatic",
+                                          "An error occured when reading the fieldmap '" + Filename_m + "'");
         }
         length_m = 2.0 * num_gridpz_m * (zend_m - zbegin_m) / (num_gridpz_m - 1);
         file.close();
@@ -217,4 +221,4 @@ double Astra1DElectroStatic::getFrequency() const {
 }
 
 void Astra1DElectroStatic::setFrequency(double freq)
-{ }
+{ }
\ No newline at end of file
diff --git a/src/Classic/Fields/Astra1DElectroStatic.h b/src/Classic/Fields/Astra1DElectroStatic.h
index b4a9f04c8c716d1f0299c483d80210fea7bf4c80..b3db9c63592d25f3df5f74bc560b109558855cc8 100644
--- a/src/Classic/Fields/Astra1DElectroStatic.h
+++ b/src/Classic/Fields/Astra1DElectroStatic.h
@@ -15,6 +15,7 @@ public:
     virtual double getFrequency() const;
     virtual void setFrequency(double freq);
 
+    virtual bool isInside(const Vector_t &r) const;
 private:
     Astra1DElectroStatic(std::string aFilename);
     ~Astra1DElectroStatic();
@@ -34,4 +35,9 @@ private:
     friend class Fieldmap;
 };
 
-#endif
+inline bool Astra1DElectroStatic::isInside(const Vector_t &r) const
+{
+    return r(2) >= zbegin_m && r(2) < zend_m;
+}
+
+#endif
\ No newline at end of file
diff --git a/src/Classic/Fields/Astra1DElectroStatic_fast.cpp b/src/Classic/Fields/Astra1DElectroStatic_fast.cpp
index 7b4e42ced91710cdc5b3cd4432a67188c5a36c06..3807c3c3162b794b4f8685df265bf202a4dd10aa 100644
--- a/src/Classic/Fields/Astra1DElectroStatic_fast.cpp
+++ b/src/Classic/Fields/Astra1DElectroStatic_fast.cpp
@@ -1,4 +1,5 @@
 #include "Fields/Astra1DElectroStatic_fast.h"
+#include "Utilities/GeneralClassicException.h"
 #include "Physics/Physics.h"
 
 #include <fstream>
@@ -27,6 +28,8 @@ Astra1DElectroStatic_fast::Astra1DElectroStatic_fast(std::string aFilename):
     if(!parsing_passed && !file.eof()) {
         disableFieldmapWarning();
         zend_m = zbegin_m - 1e-3;
+        throw GeneralClassicException("Astra1DElectroStatic_fast::Astra1DElectroStatic_fast",
+                                      "An error occured when reading the fieldmap '" + Filename_m + "'");
     }
     hz_m = (zend_m - zbegin_m) / (num_gridpz_m - 1);
     length_m = 2.0 * num_gridpz_m * hz_m;
@@ -126,4 +129,4 @@ int Astra1DElectroStatic_fast::stripFileHeader(std::ifstream &file) {
     interpreteLine<std::string, int>(file, tmpString, accuracy);
 
     return accuracy;
-}
+}
\ No newline at end of file
diff --git a/src/Classic/Fields/Astra1DMagnetoStatic.cpp b/src/Classic/Fields/Astra1DMagnetoStatic.cpp
index 1d4c422465b0da7aabb9d6ee803f56afc79ebca4..316a8f32a56c6b798767531d0c4a974c66f12b24 100644
--- a/src/Classic/Fields/Astra1DMagnetoStatic.cpp
+++ b/src/Classic/Fields/Astra1DMagnetoStatic.cpp
@@ -1,6 +1,8 @@
 #include "Fields/Astra1DMagnetoStatic.h"
 #include "Fields/Fieldmap.hpp"
 #include "Physics/Physics.h"
+#include "Utilities/GeneralClassicException.h"
+
 #include "gsl/gsl_interp.h"
 #include "gsl/gsl_spline.h"
 #include "gsl/gsl_fft_real.h"
@@ -48,6 +50,8 @@ Astra1DMagnetoStatic::Astra1DMagnetoStatic(std::string aFilename)
         if(!parsing_passed && !file.eof()) {
             disableFieldmapWarning();
             zend_m = zbegin_m - 1e-3;
+            throw GeneralClassicException("Astra1DMagnetoStatic::Astra1DMagnetoStatic",
+                                          "An error occured when reading the fieldmap '" + Filename_m + "'");
         }
         length_m = 2.0 * num_gridpz_m * (zend_m - zbegin_m) / (num_gridpz_m - 1);
     } else {
@@ -211,4 +215,4 @@ double Astra1DMagnetoStatic::getFrequency() const {
 }
 
 void Astra1DMagnetoStatic::setFrequency(double freq)
-{ }
+{ }
\ No newline at end of file
diff --git a/src/Classic/Fields/Astra1DMagnetoStatic.h b/src/Classic/Fields/Astra1DMagnetoStatic.h
index ec6935dfa2e1a4f05cc81ba51d19389b03b316b9..dce81d02ab7573f77068d5ca2afde7f1fc4163ac 100644
--- a/src/Classic/Fields/Astra1DMagnetoStatic.h
+++ b/src/Classic/Fields/Astra1DMagnetoStatic.h
@@ -15,6 +15,7 @@ public:
     virtual double getFrequency() const;
     virtual void setFrequency(double freq);
 
+    virtual bool isInside(const Vector_t &r) const;
 private:
     Astra1DMagnetoStatic(std::string aFilename);
     ~Astra1DMagnetoStatic();
@@ -34,4 +35,9 @@ private:
     friend class Fieldmap;
 };
 
-#endif
+inline bool Astra1DMagnetoStatic::isInside(const Vector_t &r) const
+{
+    return r(2) >= zbegin_m && r(2) < zend_m;
+}
+
+#endif
\ No newline at end of file
diff --git a/src/Classic/Fields/Astra1DMagnetoStatic_fast.cpp b/src/Classic/Fields/Astra1DMagnetoStatic_fast.cpp
index 663c9105aea862a3d635c1d90615aab1e85adbac..0ec2de31ca2d92ad0f51b27536393d27d424477e 100644
--- a/src/Classic/Fields/Astra1DMagnetoStatic_fast.cpp
+++ b/src/Classic/Fields/Astra1DMagnetoStatic_fast.cpp
@@ -1,4 +1,5 @@
 #include "Fields/Astra1DMagnetoStatic_fast.h"
+#include "Utilities/GeneralClassicException.h"
 #include "Physics/Physics.h"
 
 #include <fstream>
@@ -29,6 +30,8 @@ Astra1DMagnetoStatic_fast::Astra1DMagnetoStatic_fast(std::string aFilename):
     if(!parsing_passed) {
         disableFieldmapWarning();
         zend_m = zbegin_m - 1e-3;
+        throw GeneralClassicException("Astra1DMagnetoStatic_fast::Astra1DMagnetoStatic_fast",
+                                      "An error occured when reading the fieldmap '" + Filename_m + "'");
     }
     hz_m = (zend_m - zbegin_m) / (num_gridpz_m - 1);
     length_m = 2.0 * num_gridpz_m * hz_m;
@@ -127,4 +130,4 @@ int Astra1DMagnetoStatic_fast::stripFileHeader(std::ifstream &file) {
     interpreteLine<std::string, int>(file, tmpString, accuracy);
 
     return accuracy;
-}
+}
\ No newline at end of file
diff --git a/src/Classic/Fields/Astra1D_fast.cpp b/src/Classic/Fields/Astra1D_fast.cpp
index 122f790c46c79ca627a6cd554c9fd9744e69f61f..235a0fe26c9b9c2c98b051554de3fc5afad01c1c 100644
--- a/src/Classic/Fields/Astra1D_fast.cpp
+++ b/src/Classic/Fields/Astra1D_fast.cpp
@@ -29,7 +29,7 @@ void Astra1D_fast::freeMap() {
         delete[] zvals_m;
         zvals_m = NULL;
 
-        INFOMSG(typeset_msg("freed fieldmap '" + Filename_m  + "'", "info") << endl);
+        INFOMSG(level3 << typeset_msg("freed fieldmap '" + Filename_m  + "'", "info") << endl);
     }
 }
 
diff --git a/src/Classic/Fields/Astra1D_fast.h b/src/Classic/Fields/Astra1D_fast.h
index 7c3e41967c94da87a64ae3f447c322bbc0fc0d68..5500f56547e858d7add841bfacf3203cc0047841 100644
--- a/src/Classic/Fields/Astra1D_fast.h
+++ b/src/Classic/Fields/Astra1D_fast.h
@@ -16,6 +16,7 @@ public:
     virtual void setFrequency(double freq) = 0;
     virtual void getOnaxisEz(std::vector<std::pair<double, double> > & F);
 
+    virtual bool isInside(const Vector_t &r) const;
 protected:
     Astra1D_fast(std::string aFilename);
     virtual ~Astra1D_fast();
@@ -49,4 +50,9 @@ protected:
     friend class Fieldmap;
 };
 
+inline bool Astra1D_fast::isInside(const Vector_t &r) const
+{
+    return r(2) >= zbegin_m && r(2) < zend_m;
+}
+
 #endif
\ No newline at end of file
diff --git a/src/Classic/Fields/CMakeLists.txt b/src/Classic/Fields/CMakeLists.txt
index bc674d6d445738ad5c27ddcd717e01b9e566e9fe..f7944ece5c39faaedfd418a30e7928dee7594bef 100644
--- a/src/Classic/Fields/CMakeLists.txt
+++ b/src/Classic/Fields/CMakeLists.txt
@@ -14,6 +14,8 @@ set (_SRCS
   FM3DH5Block.cpp
   FM3DH5Block_nonscale.cpp
   FM3DMagnetoStaticH5Block.cpp
+  FM3DMagnetoStatic.cpp
+  FM3DMagnetoStaticExtended.cpp
   FM3DDynamic.cpp
   FM2DElectroStatic.cpp
   FM2DMagnetoStatic.cpp
@@ -45,4 +47,52 @@ include_directories (
 
 add_subdirectory (Interpolation)
 
-add_sources(${_SRCS})
\ No newline at end of file
+ADD_OPAL_SOURCES(${_SRCS})
+
+set (HDRS
+    AcceleratingField.h
+    Astra1DDynamic_fast.h
+    Astra1DDynamic.h
+    Astra1DElectroStatic_fast.h
+    Astra1DElectroStatic.h
+    Astra1D_fast.h
+    Astra1DMagnetoStatic_fast.h
+    Astra1DMagnetoStatic.h
+    BDipoleField.h
+    BMultipoleField.h
+    BSingleMultipoleField.h
+    ConstBField.h
+    ConstBzField.h
+    ConstEField.h
+    ConstEzField.h
+    EDipoleField.h
+    EMField.h
+    Fieldmap.h
+    Fieldmap.hpp
+    FM1DDynamic_fast.h
+    FM1DDynamic.h
+    FM1DElectroStatic_fast.h
+    FM1DElectroStatic.h
+    FM1DMagnetoStatic_fast.h
+    FM1DMagnetoStatic.h
+    FM1DProfile1.h
+    FM1DProfile2.h
+    FM2DDynamic.h
+    FM2DElectroStatic.h
+    FM2DMagnetoStatic.h
+    FM3DDynamic.h
+    FM3DH5Block.h
+    FM3DH5Block_nonscale.h
+    FM3DMagnetoStaticH5Block.h
+    FM3DMagnetoStatic.h
+    FM3DMagnetoStaticExtended.h
+    FMDummy.h
+    NullField.h
+    OscillatingField.h
+    SectorField.h
+    SectorMagneticFieldMap.h
+    StaticElectricField.h
+    StaticMagneticField.h
+)
+
+install (FILES ${HDRS} DESTINATION "${CMAKE_INSTALL_PREFIX}/include/Fields")
\ No newline at end of file
diff --git a/src/Classic/Fields/FM1DDynamic.h b/src/Classic/Fields/FM1DDynamic.h
index 01938263d18757cd445b891978f0ea7f35db2444..ac65dd15aeb643dd119e336121e3914f72704bc2 100644
--- a/src/Classic/Fields/FM1DDynamic.h
+++ b/src/Classic/Fields/FM1DDynamic.h
@@ -20,6 +20,7 @@ public:
     virtual void setFrequency(double freq);
     virtual void getOnaxisEz(std::vector<std::pair<double, double>> &eZ);
 
+    virtual bool isInside(const Vector_t &r) const;
 private:
     FM1DDynamic(std::string aFilename);
     ~FM1DDynamic();
@@ -57,4 +58,9 @@ private:
     friend class Fieldmap;
 };
 
-#endif
+inline bool FM1DDynamic::isInside(const Vector_t &r) const
+{
+    return r(2) >= zBegin_m && r(2) < zEnd_m;
+}
+
+#endif
\ No newline at end of file
diff --git a/src/Classic/Fields/FM1DDynamic_fast.cpp b/src/Classic/Fields/FM1DDynamic_fast.cpp
index 6cab4aed6fa0729d8d1d011d466a0f3cb206ec54..fa0d5b35a2f9831f5c0e092238b4671dc70605c3 100644
--- a/src/Classic/Fields/FM1DDynamic_fast.cpp
+++ b/src/Classic/Fields/FM1DDynamic_fast.cpp
@@ -89,7 +89,7 @@ void FM1DDynamic_fast::freeMap() {
         gsl_interp_accel_free(onAxisFieldPPAccel_m);
         gsl_interp_accel_free(onAxisFieldPPPAccel_m);
 
-        INFOMSG(typeset_msg("freed fieldmap '" + Filename_m  + "'", "info")
+        INFOMSG(level3 << typeset_msg("freed fieldmap '" + Filename_m  + "'", "info")
                 << endl);
     }
 }
@@ -426,4 +426,4 @@ void FM1DDynamic_fast::prepareForMapCheck(unsigned int accuracy, std::vector<dou
              fourierCoefs,
              onAxisFieldInterpolants_m,
              onAxisFieldAccel_m);
-}
\ No newline at end of file
+}
diff --git a/src/Classic/Fields/FM1DDynamic_fast.h b/src/Classic/Fields/FM1DDynamic_fast.h
index 5e11a17984c4d9a5194361090f857583f8e965a6..adefae42eae38499ab5958da5e8a748f2f3bcc04 100644
--- a/src/Classic/Fields/FM1DDynamic_fast.h
+++ b/src/Classic/Fields/FM1DDynamic_fast.h
@@ -20,6 +20,7 @@ public:
     virtual void setFrequency(double freq);
     virtual void getOnaxisEz(std::vector<std::pair<double, double>> &eZ);
 
+    virtual bool isInside(const Vector_t &r) const;
 private:
     FM1DDynamic_fast(std::string aFilename);
     ~FM1DDynamic_fast();
@@ -76,4 +77,9 @@ private:
     friend class Fieldmap;
 };
 
+inline bool FM1DDynamic_fast::isInside(const Vector_t &r) const
+{
+    return r(2) >= zBegin_m && r(2) < zEnd_m;
+}
+
 #endif
\ No newline at end of file
diff --git a/src/Classic/Fields/FM1DElectroStatic.h b/src/Classic/Fields/FM1DElectroStatic.h
index 5a1b3183666608b6837e9132f042aecb1a7105de..b790566a2b3fbd43e3e2994ad79533e74a957da4 100644
--- a/src/Classic/Fields/FM1DElectroStatic.h
+++ b/src/Classic/Fields/FM1DElectroStatic.h
@@ -19,6 +19,7 @@ public:
     virtual double getFrequency() const;
     virtual void setFrequency(double freq);
 
+    virtual bool isInside(const Vector_t &r) const;
 private:
     FM1DElectroStatic(std::string aFilename);
     ~FM1DElectroStatic();
@@ -50,4 +51,9 @@ private:
     friend class Fieldmap;
 };
 
-#endif
+inline bool FM1DElectroStatic::isInside(const Vector_t &r) const
+{
+    return r(2) >= zBegin_m && r(2) < zEnd_m;
+}
+
+#endif
\ No newline at end of file
diff --git a/src/Classic/Fields/FM1DElectroStatic_fast.h b/src/Classic/Fields/FM1DElectroStatic_fast.h
index 548d18b6e8ec7fa1b9eb5524fce2b610cb6e548f..aba86a8179d650300738435519e459c3ea1758e9 100644
--- a/src/Classic/Fields/FM1DElectroStatic_fast.h
+++ b/src/Classic/Fields/FM1DElectroStatic_fast.h
@@ -19,6 +19,7 @@ public:
     virtual double getFrequency() const;
     virtual void setFrequency(double freq);
 
+    virtual bool isInside(const Vector_t &r) const;
 private:
     FM1DElectroStatic_fast(std::string aFilename);
     ~FM1DElectroStatic_fast();
@@ -69,4 +70,9 @@ private:
     friend class Fieldmap;
 };
 
+inline bool FM1DElectroStatic_fast::isInside(const Vector_t &r) const
+{
+    return r(2) >= zBegin_m && r(2) < zEnd_m;
+}
+
 #endif
\ No newline at end of file
diff --git a/src/Classic/Fields/FM1DMagnetoStatic.h b/src/Classic/Fields/FM1DMagnetoStatic.h
index c95480ef0d2dbfe6dcca806c0b798cd8b247dc15..9b1aa2bf81750b4bd2c6e0275f722e18474997bf 100644
--- a/src/Classic/Fields/FM1DMagnetoStatic.h
+++ b/src/Classic/Fields/FM1DMagnetoStatic.h
@@ -19,6 +19,7 @@ public:
     virtual double getFrequency() const;
     virtual void setFrequency(double freq);
 
+    virtual bool isInside(const Vector_t &r) const;
 private:
     FM1DMagnetoStatic(std::string aFilename);
     ~FM1DMagnetoStatic();
@@ -50,4 +51,9 @@ private:
     friend class Fieldmap;
 };
 
-#endif
+inline bool FM1DMagnetoStatic::isInside(const Vector_t &r) const
+{
+    return r(2) >= zBegin_m && r(2) < zEnd_m;
+}
+
+#endif
\ No newline at end of file
diff --git a/src/Classic/Fields/FM1DMagnetoStatic_fast.h b/src/Classic/Fields/FM1DMagnetoStatic_fast.h
index 7e7a14b97c610d2a991bb0cab2054089eb9b78a6..856a602ecfc43379de5360025943e5cb39f0ad04 100644
--- a/src/Classic/Fields/FM1DMagnetoStatic_fast.h
+++ b/src/Classic/Fields/FM1DMagnetoStatic_fast.h
@@ -19,6 +19,7 @@ public:
     virtual double getFrequency() const;
     virtual void setFrequency(double freq);
 
+    virtual bool isInside(const Vector_t &r) const;
 private:
     FM1DMagnetoStatic_fast(std::string aFilename);
     ~FM1DMagnetoStatic_fast();
@@ -71,4 +72,9 @@ private:
     friend class Fieldmap;
 };
 
+inline bool FM1DMagnetoStatic_fast::isInside(const Vector_t &r) const
+{
+    return r(2) >= zBegin_m && r(2) < zEnd_m;
+}
+
 #endif
\ No newline at end of file
diff --git a/src/Classic/Fields/FM1DProfile1.cpp b/src/Classic/Fields/FM1DProfile1.cpp
index b0c0bf89f761a776fdb2ce3b13e6cc0e156f5d72..a3ea74e84302667ee3dd95080fc5ae14d8d8062c 100644
--- a/src/Classic/Fields/FM1DProfile1.cpp
+++ b/src/Classic/Fields/FM1DProfile1.cpp
@@ -243,14 +243,14 @@ double FM1DProfile1::getFrequency() const {
 void FM1DProfile1::setFrequency(double freq)
 {}
 
-void FM1DProfile1::Get1DProfile1EngeCoeffs(std::vector<double> &engeCoeffsEntry,
+void FM1DProfile1::get1DProfile1EngeCoeffs(std::vector<double> &engeCoeffsEntry,
         std::vector<double> &engeCoeffsExit) {
     engeCoeffsEntry = engeCoeffsEntry_m;
     engeCoeffsExit = engeCoeffsExit_m;
 
 }
 
-void FM1DProfile1::Get1DProfile1EntranceParam(double &entranceParameter1,
+void FM1DProfile1::get1DProfile1EntranceParam(double &entranceParameter1,
         double &entranceParameter2,
         double &entranceParameter3) {
     entranceParameter1 = entranceParameter1_m;
@@ -258,7 +258,7 @@ void FM1DProfile1::Get1DProfile1EntranceParam(double &entranceParameter1,
     entranceParameter3 = entranceParameter3_m;
 }
 
-void FM1DProfile1::Get1DProfile1ExitParam(double &exitParameter1,
+void FM1DProfile1::get1DProfile1ExitParam(double &exitParameter1,
         double &exitParameter2,
         double &exitParameter3) {
     exitParameter1 = exitParameter1_m;
@@ -266,10 +266,10 @@ void FM1DProfile1::Get1DProfile1ExitParam(double &exitParameter1,
     exitParameter3 = exitParameter3_m;
 }
 
-double FM1DProfile1::GetFieldGap() {
+double FM1DProfile1::getFieldGap() {
     return gapHeight_m;
 }
-void FM1DProfile1::SetFieldGap(double gap) {
+void FM1DProfile1::setFieldGap(double gap) {
 
     gapHeight_m = gap;
 
diff --git a/src/Classic/Fields/FM1DProfile1.h b/src/Classic/Fields/FM1DProfile1.h
index ee8f9f82afe8190d78b459503ecdc41d10486b42..1ae74f5242a83f1414770a19c9b9a4510771e256 100644
--- a/src/Classic/Fields/FM1DProfile1.h
+++ b/src/Classic/Fields/FM1DProfile1.h
@@ -19,13 +19,13 @@ public:
                                     Vector_t &E,
                                     Vector_t &B,
                                     const DiffDirection &dir) const;
-    virtual void Get1DProfile1EntranceParam(double &entranceParameter1,
+    virtual void get1DProfile1EntranceParam(double &entranceParameter1,
                                            double &entranceParameter2,
                                            double &entranceParameter3);
-    virtual void Get1DProfile1ExitParam(double &exitParameter1,
+    virtual void get1DProfile1ExitParam(double &exitParameter1,
                                        double &exitParameter2,
                                        double &exitParameter3);
-    virtual double GetFieldGap();
+    virtual double getFieldGap();
     virtual void getFieldDimensions(double &zBegin,
                                     double &zEnd,
                                     double &rBegin,
@@ -42,11 +42,11 @@ public:
     virtual double getFrequency() const;
     virtual void getInfo(Inform *);
     virtual void setFrequency(double freq);
-    virtual void Get1DProfile1EngeCoeffs(std::vector<double> &engeCoeffsEntry,
+    virtual void get1DProfile1EngeCoeffs(std::vector<double> &engeCoeffsEntry,
                                          std::vector<double> &engeCoeffsExit);
     virtual void swap();
 
-    virtual void SetFieldGap(double gap);
+    virtual void setFieldGap(double gap);
 
 private:
 
diff --git a/src/Classic/Fields/FM2DDynamic.cpp b/src/Classic/Fields/FM2DDynamic.cpp
index 6ac8cc5a19fdb6bd6792cc93e5072571f1bb0a35..fb734f3ebe1d0451e0c404750e6967c52578121b 100644
--- a/src/Classic/Fields/FM2DDynamic.cpp
+++ b/src/Classic/Fields/FM2DDynamic.cpp
@@ -1,6 +1,7 @@
 #include "Fields/FM2DDynamic.h"
 #include "Fields/Fieldmap.hpp"
 #include "Physics/Physics.h"
+#include "Utilities/GeneralClassicException.h"
 
 #include <fstream>
 #include <ios>
@@ -61,6 +62,8 @@ FM2DDynamic::FM2DDynamic(std::string aFilename)
         if(!parsing_passed) {
             disableFieldmapWarning();
             zend_m = zbegin_m - 1e-3;
+            throw GeneralClassicException("FM2DDynamic::FM2DDynamic",
+                                          "An error occured when reading the fieldmap '" + Filename_m + "'");
         } else {
             // convert MHz to Hz and frequency to angular frequency
             frequency_m *= Physics::two_pi * 1e6;
diff --git a/src/Classic/Fields/FM2DDynamic.h b/src/Classic/Fields/FM2DDynamic.h
index 9767ac7bb7f3cd3b722333e4366b5a3e3c0de3e5..dd417ccd3228458da8508ebbd12f727e4ac3530e 100644
--- a/src/Classic/Fields/FM2DDynamic.h
+++ b/src/Classic/Fields/FM2DDynamic.h
@@ -18,6 +18,7 @@ public:
     virtual void setFrequency(double freq);
     virtual void getOnaxisEz(std::vector<std::pair<double, double> > & F);
 
+    virtual bool isInside(const Vector_t &r) const;
 private:
     FM2DDynamic(std::string aFilename);
     ~FM2DDynamic();
@@ -44,4 +45,9 @@ private:
     friend class Fieldmap;
 };
 
+inline bool FM2DDynamic::isInside(const Vector_t &r) const
+{
+    return r(2) >= zbegin_m && r(2) < zend_m && sqrt(r(0)*r(0) + r(1)*r(1)) < rend_m;
+}
+
 #endif
\ No newline at end of file
diff --git a/src/Classic/Fields/FM2DElectroStatic.cpp b/src/Classic/Fields/FM2DElectroStatic.cpp
index 6d50cad983dbdc12a8526152fab93f2cc21b59f1..2ca6e637f2b301fb5677025bcfe2733442cfa300 100644
--- a/src/Classic/Fields/FM2DElectroStatic.cpp
+++ b/src/Classic/Fields/FM2DElectroStatic.cpp
@@ -1,5 +1,6 @@
 #include "Fields/FM2DElectroStatic.h"
 #include "Fields/Fieldmap.hpp"
+#include "Utilities/GeneralClassicException.h"
 
 #include <fstream>
 #include <ios>
@@ -50,6 +51,8 @@ FM2DElectroStatic::FM2DElectroStatic(std::string aFilename)
         if(!parsing_passed) {
             disableFieldmapWarning();
             zend_m = zbegin_m - 1e-3;
+            throw GeneralClassicException("FM2DElectroStatic::FM2DElectroStatic",
+                                          "An error occured when reading the fieldmap '" + Filename_m + "'");
         } else {
             // conversion from cm to m
             rbegin_m /= 100.;
diff --git a/src/Classic/Fields/FM2DElectroStatic.h b/src/Classic/Fields/FM2DElectroStatic.h
index 3a44b34a29ee2b16115e28d0b39eb732d4298fee..3868fcee3260115f24ef35390f6aae427222174e 100644
--- a/src/Classic/Fields/FM2DElectroStatic.h
+++ b/src/Classic/Fields/FM2DElectroStatic.h
@@ -15,6 +15,7 @@ public:
     virtual double getFrequency() const;
     virtual void setFrequency(double freq);
 
+    virtual bool isInside(const Vector_t &r) const;
 private:
     FM2DElectroStatic(std::string aFilename);
     ~FM2DElectroStatic();
@@ -38,4 +39,9 @@ private:
     friend class Fieldmap;
 };
 
-#endif
+inline bool FM2DElectroStatic::isInside(const Vector_t &r) const
+{
+    return r(2) >= zbegin_m && r(2) < zend_m && sqrt(r(0)*r(0) + r(1)*r(1)) < rend_m;
+}
+
+#endif
\ No newline at end of file
diff --git a/src/Classic/Fields/FM2DMagnetoStatic.cpp b/src/Classic/Fields/FM2DMagnetoStatic.cpp
index a26bbbedefc29b69ba6b60e7a4acc2ccd8cfdba8..5828d26880c1259738b401f9bdc7f00c60731da0 100644
--- a/src/Classic/Fields/FM2DMagnetoStatic.cpp
+++ b/src/Classic/Fields/FM2DMagnetoStatic.cpp
@@ -1,5 +1,6 @@
 #include "Fields/FM2DMagnetoStatic.h"
 #include "Fields/Fieldmap.hpp"
+#include "Utilities/GeneralClassicException.h"
 
 #include <fstream>
 #include <ios>
@@ -50,6 +51,8 @@ FM2DMagnetoStatic::FM2DMagnetoStatic(std::string aFilename):
         if(!parsing_passed) {
             disableFieldmapWarning();
             zend_m = zbegin_m - 1e-3;
+            throw GeneralClassicException("FM2DMagnetoStatic::FM2DMagnetoStatic",
+                                          "An error occured when reading the fieldmap '" + Filename_m + "'");
         } else {
             // conversion from cm to m
             rbegin_m /= 100.;
diff --git a/src/Classic/Fields/FM2DMagnetoStatic.h b/src/Classic/Fields/FM2DMagnetoStatic.h
index 4b5655eaee5b154d43667fe8c8f7882d8e28e3f4..f1c192e0524ac9e06cf1662a2456adae0c72930c 100644
--- a/src/Classic/Fields/FM2DMagnetoStatic.h
+++ b/src/Classic/Fields/FM2DMagnetoStatic.h
@@ -15,6 +15,7 @@ public:
     virtual double getFrequency() const;
     virtual void setFrequency(double freq);
 
+    virtual bool isInside(const Vector_t &r) const;
 private:
     FM2DMagnetoStatic(std::string aFilename);
     ~FM2DMagnetoStatic();
@@ -38,4 +39,9 @@ private:
     friend class Fieldmap;
 };
 
-#endif
+inline bool FM2DMagnetoStatic::isInside(const Vector_t &r) const
+{
+    return r(2) >= zbegin_m && r(2) < zend_m && sqrt(r(0)*r(0) + r(1)*r(1)) < rend_m;
+}
+
+#endif
\ No newline at end of file
diff --git a/src/Classic/Fields/FM3DDynamic.cpp b/src/Classic/Fields/FM3DDynamic.cpp
index bf5f58eaa0ac378e02a322dff78a01a0a5e925f6..2a3b38cf1991532cc30ef12cc1281a952898ea0e 100644
--- a/src/Classic/Fields/FM3DDynamic.cpp
+++ b/src/Classic/Fields/FM3DDynamic.cpp
@@ -1,5 +1,6 @@
 #include "Fields/FM3DDynamic.h"
 #include "Fields/Fieldmap.hpp"
+#include "Utilities/GeneralClassicException.h"
 
 #include "Physics/Physics.h"
 
@@ -27,22 +28,16 @@ FM3DDynamic::FM3DDynamic(std::string aFilename):
     ifstream file(Filename_m.c_str());
 
     if(file.good()) {
-        bool parsing_passed = interpreteLine<std::string, std::string>(file, tmpString, tmpString);
-        if(tmpString == "XYZ") {
-            swap_m = false;
-            parsing_passed = parsing_passed &&
-                             interpreteLine<double>(file, frequency_m);
-            parsing_passed = parsing_passed &&
-                             interpreteLine<double, double, unsigned int>(file, xbegin_m, xend_m, num_gridpx_m);
-            parsing_passed = parsing_passed &&
-                             interpreteLine<double, double, unsigned int>(file, ybegin_m, yend_m, num_gridpy_m);
-            parsing_passed = parsing_passed &&
-                             interpreteLine<double, double, unsigned int>(file, zbegin_m, zend_m, num_gridpz_m);
-        } else {
-            cerr << "at the moment only the XYZ orientation is supported!\n"
-                 << "unknown orientation of 3D dynamic fieldmap" << endl;
-            parsing_passed = false;
-        }
+        bool parsing_passed = interpreteLine<std::string>(file, tmpString);
+        parsing_passed = parsing_passed &&
+                         interpreteLine<double>(file, frequency_m);
+        parsing_passed = parsing_passed &&
+                         interpreteLine<double, double, unsigned int>(file, xbegin_m, xend_m, num_gridpx_m);
+        parsing_passed = parsing_passed &&
+                         interpreteLine<double, double, unsigned int>(file, ybegin_m, yend_m, num_gridpy_m);
+        parsing_passed = parsing_passed &&
+                         interpreteLine<double, double, unsigned int>(file, zbegin_m, zend_m, num_gridpz_m);
+
         for(unsigned long i = 0; (i < (num_gridpz_m + 1) * (num_gridpx_m + 1) * (num_gridpy_m + 1)) && parsing_passed; ++ i) {
             parsing_passed = parsing_passed &&
                              interpreteLine<double>(file,
@@ -62,6 +57,8 @@ FM3DDynamic::FM3DDynamic(std::string aFilename):
         if(!parsing_passed) {
             disableFieldmapWarning();
             zend_m = zbegin_m - 1e-3;
+            throw GeneralClassicException("FM3DDynamic::FM3DDynamic",
+                                          "An error occured when reading the fieldmap '" + Filename_m + "'");
         } else {
             frequency_m *= Physics::two_pi * 1e6;
 
@@ -101,7 +98,7 @@ void FM3DDynamic::readMap() {
         std::string tmpString;
         double tmpDouble, Ezmax = 0.0;
 
-        interpreteLine<std::string, std::string>(in, tmpString, tmpString);
+        interpreteLine<std::string>(in, tmpString);
         interpreteLine<double>(in, tmpDouble);
         interpreteLine<double, double, int>(in, tmpDouble, tmpDouble, tmpInt);
         interpreteLine<double, double, int>(in, tmpDouble, tmpDouble, tmpInt);
diff --git a/src/Classic/Fields/FM3DDynamic.h b/src/Classic/Fields/FM3DDynamic.h
index a7551e93e527101d90cd1e5807eaad4388480ace..71b9ce1084e72bc8782a3294150540a3f576594a 100644
--- a/src/Classic/Fields/FM3DDynamic.h
+++ b/src/Classic/Fields/FM3DDynamic.h
@@ -16,6 +16,7 @@ public:
     virtual void setFrequency(double freq);
     virtual void getOnaxisEz(std::vector<std::pair<double, double> > & F);
 
+    virtual bool isInside(const Vector_t &r) const;
 private:
     FM3DDynamic(std::string aFilename);
     ~FM3DDynamic();
@@ -52,4 +53,11 @@ private:
     friend class Fieldmap;
 };
 
+inline bool FM3DDynamic::isInside(const Vector_t &r) const
+{
+    return ((r(0) >= xbegin_m && r(0) < xend_m) &&
+            (r(1) >= ybegin_m && r(1) < yend_m) &&
+            (r(2) >= zbegin_m && r(2) < zend_m));
+}
+
 #endif
\ No newline at end of file
diff --git a/src/Classic/Fields/FM3DH5Block.cpp b/src/Classic/Fields/FM3DH5Block.cpp
index 5ceb4fe371b2e9c39b751403c3ad87ef396c70d0..2e09d0381b8dd921bffe42c2bd274ae95ecdf5df 100644
--- a/src/Classic/Fields/FM3DH5Block.cpp
+++ b/src/Classic/Fields/FM3DH5Block.cpp
@@ -61,15 +61,15 @@ FM3DH5Block::FM3DH5Block(std::string aFilename):Fieldmap(aFilename) {
     xend_m = xbegin_m + (num_gridpx_m - 1) * hx_m;
     yend_m = ybegin_m + (num_gridpy_m - 1) * hy_m;
     zend_m = zbegin_m + (num_gridpz_m - 1) * hz_m;
-    
+
     //         xcentral_idx_m = static_cast<int>(fabs(xbegin_m) / hx_m);
     //         ycentral_idx_m = static_cast<int>(fabs(ybegin_m) / hy_m);
-    
-    
+
+
     h5err = H5ReadFileAttribFloat64(file, "Resonance Frequency(Hz)", &frequency_m);
     assert (h5err != H5_ERR);
     frequency_m *= Physics::two_pi;
-    
+
     h5err = H5CloseFile(file);
     assert (h5err != H5_ERR);
 }
@@ -116,7 +116,7 @@ void FM3DH5Block::readMap() {
     //double lever_x;
     //double lever_y;
     //double Ezmax = 1.0 ;
-    
+
     h5_int64_t last_step = H5GetNumSteps(file) - 1;
     h5err = H5SetStep(file, last_step);
     assert (h5err != H5_ERR);
@@ -135,18 +135,18 @@ void FM3DH5Block::readMap() {
         Nz_read_start[i] = start;
     }
     Nz_read_start[Ippl::getNodes()] = start;
-    
+
     N_read_start = Nz_read_start[Ippl::myNode()] * num_gridpx_m * num_gridpy_m;
-    
+
     // rbuf_size = max(Nz_avrg, Nz_avrg - signNz);
     // std::unique_ptr<double> rbuf(new double[Ippl::getNodes() * rbuf_size]);
-    
+
     h5err = H5Block3dSetView(file,
                              0, num_gridpx_m - 1,
                              0, num_gridpy_m - 1,
                              Nz_read_start[Ippl::myNode()], Nz_read_start[Ippl::myNode() + 1] - 1);
     assert (h5err != H5_ERR);
-    
+
     field_size = (num_gridpx_m * num_gridpy_m * num_gridpz_m);
     FieldstrengthEx_m.resize(field_size);
     FieldstrengthEy_m.resize(field_size);
@@ -168,7 +168,7 @@ void FM3DH5Block::readMap() {
         &(FieldstrengthHy_m[N_read_start]),
         &(FieldstrengthHz_m[N_read_start]));
     assert (h5err != H5_ERR);
-    
+
     for(int i = 0; i < Nnodes; ++ i) {
         int N_read_start = Nz_read_start[i] * num_gridpx_m * num_gridpy_m;
         int N_read_length = Nz_read_length[i] * num_gridpx_m * num_gridpy_m;
@@ -179,10 +179,10 @@ void FM3DH5Block::readMap() {
         MPI_Bcast(&(FieldstrengthHy_m[N_read_start]), N_read_length, MPI_DOUBLE, i, Ippl::getComm());
         MPI_Bcast(&(FieldstrengthHz_m[N_read_start]), N_read_length, MPI_DOUBLE, i, Ippl::getComm());
     }
-    
+
     h5err = H5CloseFile(file);
     assert (h5err != H5_ERR);
-    
+
     delete[] Nz_read_start;
     delete[] Nz_read_length;
 
diff --git a/src/Classic/Fields/FM3DH5Block.h b/src/Classic/Fields/FM3DH5Block.h
index 892b2e7ea2939682164af6ebc2fee3df89c984fb..bac9b00f0ad581f5ca1014f466a7b1091ff30422 100644
--- a/src/Classic/Fields/FM3DH5Block.h
+++ b/src/Classic/Fields/FM3DH5Block.h
@@ -19,6 +19,7 @@ public:
     virtual void setFrequency(double freq);
     virtual void getOnaxisEz(std::vector<std::pair<double, double> > & F);
 
+    virtual bool isInside(const Vector_t &r) const;
 private:
     FM3DH5Block(std::string aFilename);
     ~FM3DH5Block();
@@ -57,4 +58,11 @@ private:
     friend class Fieldmap;
 };
 
-#endif
+inline bool FM3DH5Block::isInside(const Vector_t &r) const
+{
+    return ((r(0) >= xbegin_m && r(0) < xend_m) &&
+            (r(1) >= ybegin_m && r(1) < yend_m) &&
+            (r(2) >= zbegin_m && r(2) < zend_m));
+}
+
+#endif
\ No newline at end of file
diff --git a/src/Classic/Fields/FM3DH5Block_nonscale.h b/src/Classic/Fields/FM3DH5Block_nonscale.h
index 55ff215ddb3dc54b37440c8719f50e7cadd7c98e..8b29a954b76bfba0c8e416b9b35c85cb5f495b0b 100644
--- a/src/Classic/Fields/FM3DH5Block_nonscale.h
+++ b/src/Classic/Fields/FM3DH5Block_nonscale.h
@@ -18,6 +18,7 @@ public:
     virtual void setFrequency(double freq);
     virtual void getOnaxisEz(std::vector<std::pair<double, double> > & F);
 
+    virtual bool isInside(const Vector_t &r) const;
 private:
     FM3DH5Block_nonscale(std::string aFilename);
     ~FM3DH5Block_nonscale();
@@ -56,4 +57,11 @@ private:
     friend class Fieldmap;
 };
 
-#endif
+inline bool FM3DH5Block_nonscale::isInside(const Vector_t &r) const
+{
+    return ((r(0) >= xbegin_m && r(0) < xend_m) &&
+            (r(1) >= ybegin_m && r(1) < yend_m) &&
+            (r(2) >= zbegin_m && r(2) < zend_m));
+}
+
+#endif
\ No newline at end of file
diff --git a/src/Classic/Fields/FM3DMagnetoStaticH5Block.cpp b/src/Classic/Fields/FM3DMagnetoStaticH5Block.cpp
index 0b710261c99ba60b979b8a2b6ac6499565957571..97bfde946d223e9125d99d3ae1cc49af2bc7238a 100644
--- a/src/Classic/Fields/FM3DMagnetoStaticH5Block.cpp
+++ b/src/Classic/Fields/FM3DMagnetoStaticH5Block.cpp
@@ -39,7 +39,7 @@ FM3DMagnetoStaticH5Block::FM3DMagnetoStaticH5Block(string aFilename):
 
     h5_int64_t last_step = H5GetNumSteps(file) - 1;
     assert (last_step >= 0);
-    
+
     h5err = H5SetStep(file, last_step);
     assert (h5err != H5_ERR);
 
diff --git a/src/Classic/Fields/FM3DMagnetoStaticH5Block.h b/src/Classic/Fields/FM3DMagnetoStaticH5Block.h
index 936b7f16826b18d6b3fbc73b5075c535238b06fe..92b1f1cb278778cceb14e93c5b7ca4eaf05b8ccb 100644
--- a/src/Classic/Fields/FM3DMagnetoStaticH5Block.h
+++ b/src/Classic/Fields/FM3DMagnetoStaticH5Block.h
@@ -16,6 +16,8 @@ public:
     virtual void getInfo(Inform *msg);
     virtual double getFrequency() const;
     virtual void setFrequency(double freq);
+
+    virtual bool isInside(const Vector_t &r) const;
 private:
     FM3DMagnetoStaticH5Block(std::string aFilename);
     ~FM3DMagnetoStaticH5Block();
@@ -54,4 +56,11 @@ private:
     friend class Fieldmap;
 };
 
-#endif
+inline bool FM3DMagnetoStaticH5Block::isInside(const Vector_t &r) const
+{
+    return ((r(0) >= xbegin_m && r(0) < xend_m) &&
+            (r(1) >= ybegin_m && r(1) < yend_m) &&
+            (r(2) >= zbegin_m && r(2) < zend_m));
+}
+
+#endif
\ No newline at end of file
diff --git a/src/Classic/Fields/Fieldmap.cpp b/src/Classic/Fields/Fieldmap.cpp
index 5718dac897a333caddcce544ea0b8b2c07ec69aa..e041c343a4170f15f9add486e84977f7f33bb515 100644
--- a/src/Classic/Fields/Fieldmap.cpp
+++ b/src/Classic/Fields/Fieldmap.cpp
@@ -3,6 +3,8 @@
 #include "Fields/FM3DH5Block.h"
 #include "Fields/FM3DH5Block_nonscale.h"
 #include "Fields/FM3DMagnetoStaticH5Block.h"
+#include "Fields/FM3DMagnetoStatic.h"
+#include "Fields/FM3DMagnetoStaticExtended.h"
 #include "Fields/FM2DDynamic.h"
 #include "Fields/FM2DElectroStatic.h"
 #include "Fields/FM2DMagnetoStatic.h"
@@ -209,6 +211,22 @@ Fieldmap *Fieldmap::getFieldmap(std::string Filename, bool fast) {
             return (*position.first).second.Map;
             break;
 
+        case T3DMagnetoStatic:
+            position = FieldmapDictionary.insert(
+                std::make_pair(
+                    Filename, FieldmapDescription(
+                        T3DMagnetoStatic, new FM3DMagnetoStatic(Filename))));
+            return (*position.first).second.Map;
+            break;
+
+        case T3DMagnetoStatic_Extended:
+            position = FieldmapDictionary.insert(
+                std::make_pair(
+                    Filename, FieldmapDescription(
+                        T3DMagnetoStatic_Extended, new FM3DMagnetoStaticExtended(Filename))));
+            return (*position.first).second.Map;
+            break;
+
         case T3DDynamicH5Block:
             if(fast) {
                 position = FieldmapDictionary.insert(
@@ -279,27 +297,34 @@ MapType Fieldmap::readHeader(std::string Filename) {
     if(strcmp(magicnumber, "3DDy") == 0)
         return T3DDynamic;
 
-    if(strcmp(magicnumber, "3DMa") == 0)
-        return T3DMagnetoStatic;
+    if(strcmp(magicnumber, "3DMa") == 0) {
+        char tmpString[21] = "                    ";
+        interpreter.read(tmpString, 20);
+
+        if(strcmp(tmpString, "gnetoStatic_Extended") == 0)
+            return T3DMagnetoStatic_Extended;
+        else
+            return T3DMagnetoStatic;
+    }
 
     if(strcmp(magicnumber, "3DEl") == 0)
         return T3DElectroStatic;
 
     if(strcmp(magicnumber, "2DDy") == 0) {
-        char tmpString[14] = "             ";
-        interpreter.read(tmpString, 13);
+        // char tmpString[14] = "             ";
+        // interpreter.read(tmpString, 13);
         return T2DDynamic;
     }
 
     if(strcmp(magicnumber, "2DMa") == 0) {
-        char tmpString[20] = "                   ";
-        interpreter.read(tmpString, 19);
+        // char tmpString[20] = "                   ";
+        // interpreter.read(tmpString, 19);
         return T2DMagnetoStatic;
     }
 
     if(strcmp(magicnumber, "2DEl") == 0) {
-        char tmpString[20] = "                   ";
-        interpreter.read(tmpString, 19);
+        // char tmpString[20] = "                   ";
+        // interpreter.read(tmpString, 19);
         return T2DElectroStatic;
     }
 
@@ -310,12 +335,12 @@ MapType Fieldmap::readHeader(std::string Filename) {
         return T1DMagnetoStatic;
 
     if(strcmp(magicnumber, "1DPr") == 0) {
-        char tmpString[7] = "      ";
-        interpreter.read(tmpString, 6);
-        if(strcmp(tmpString, "ofile1") == 0)
-            return T1DProfile1;
-        if(strcmp(tmpString, "ofile2") == 0)
-            return T1DProfile2;
+        // char tmpString[7] = "      ";
+        // interpreter.read(tmpString, 6);
+        // if(strcmp(tmpString, "ofile1") == 0)
+        return T1DProfile1;
+        // if(strcmp(tmpString, "ofile2") == 0)
+        //     return T1DProfile2;
     }
 
     if(strcmp(magicnumber, "1DEl") == 0)
@@ -340,7 +365,7 @@ MapType Fieldmap::readHeader(std::string Filename) {
 	h5_file_t *file = H5OpenFile (Filename.c_str(), H5_O_RDONLY, Ippl::getComm());
 	assert (file != (void*)H5_ERR);
 #endif
-	
+
 	h5err = H5SetStep(file, 0);
         assert (h5err != H5_ERR);
 
@@ -388,8 +413,10 @@ MapType Fieldmap::readHeader(std::string Filename) {
 void Fieldmap::readMap(std::string Filename) {
     std::map<std::string, FieldmapDescription>::iterator position = FieldmapDictionary.find(Filename);
     if(position != FieldmapDictionary.end())
-        if(!(*position).second.read)
+        if(!(*position).second.read) {
             (*position).second.Map->readMap();
+            (*position).second.read = true;
+        }
 }
 
 void Fieldmap::freeMap(std::string Filename) {
@@ -437,9 +464,12 @@ void Fieldmap::checkMap(unsigned int accuracy,
     double ezMax = 0.0;
     double ezSquare = 0.0;
     size_t lastDot = Filename_m.find_last_of(".");
+    size_t lastSlash = Filename_m.find_last_of("/");
+    lastSlash = (lastSlash == std::string::npos)? 0: lastSlash + 1;
+
     std::ofstream out;
     if (Ippl::myNode() == 0) {
-        out.open("data/" + Filename_m.substr(0, lastDot) + ".check");
+        out.open("data/" + Filename_m.substr(lastSlash, lastDot) + ".check");
         out << "# z  original reproduced\n";
     }
     auto it = zSampling.begin();
@@ -701,28 +731,28 @@ std::string Fieldmap::typeset_msg(const std::string &msg, const std::string &tit
 void Fieldmap::getOnaxisEz(std::vector<std::pair<double, double> > &onaxis)
 { }
 
-void Fieldmap::Get1DProfile1EngeCoeffs(std::vector<double> &engeCoeffsEntry,
+void Fieldmap::get1DProfile1EngeCoeffs(std::vector<double> &engeCoeffsEntry,
                                        std::vector<double> &engeCoeffsExit) {
 
 }
 
-void Fieldmap::Get1DProfile1EntranceParam(double &entranceParameter1,
+void Fieldmap::get1DProfile1EntranceParam(double &entranceParameter1,
         double &entranceParameter2,
         double &entranceParameter3) {
 
 }
 
-void Fieldmap::Get1DProfile1ExitParam(double &exitParameter1,
+void Fieldmap::get1DProfile1ExitParam(double &exitParameter1,
                                       double &exitParameter2,
                                       double &exitParameter3) {
 
 }
 
-double Fieldmap::GetFieldGap() {
+double Fieldmap::getFieldGap() {
     return 0.0;
 }
 
-void Fieldmap::SetFieldGap(double gap) {
+void Fieldmap::setFieldGap(double gap) {
 
 }
 
@@ -733,11 +763,4 @@ REGISTER_PARSE_TYPE(std::string);
 
 std::string Fieldmap::alpha_numeric("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789.-+\211");
 std::map<std::string, Fieldmap::FieldmapDescription> Fieldmap::FieldmapDictionary = std::map<std::string, Fieldmap::FieldmapDescription>();
-char Fieldmap::buffer_m[READ_BUFFER_LENGTH];
-
-// vi: set et ts=4 sw=4 sts=4:
-// Local Variables:
-// mode:c
-// c-basic-offset: 4
-// indent-tabs-mode:nil
-// End:
+char Fieldmap::buffer_m[READ_BUFFER_LENGTH];
\ No newline at end of file
diff --git a/src/Classic/Fields/Fieldmap.h b/src/Classic/Fields/Fieldmap.h
index fdb272ab0e9d650e2e32a3a67fe3211bfaefa179..9ed814a07108bdd213e5905e1be6342889e288eb 100644
--- a/src/Classic/Fields/Fieldmap.h
+++ b/src/Classic/Fields/Fieldmap.h
@@ -30,6 +30,7 @@ enum MapType {
     T3DDynamic,
     T3DElectroStatic,
     T3DMagnetoStatic,
+    T3DMagnetoStatic_Extended,
     T3DMagnetoStaticH5Block,
     T3DDynamicH5Block
 };
@@ -81,21 +82,22 @@ public:
     virtual void setEdgeConstants(const double &bendAngle, const double &entranceAngle, const double &exitAngle);
     virtual void setFieldLength(const double &);
 
-    virtual void Get1DProfile1EngeCoeffs(std::vector<double> &engeCoeffsEntry,
+    virtual void get1DProfile1EngeCoeffs(std::vector<double> &engeCoeffsEntry,
                                          std::vector<double> &engeCoeffsExit);
-    virtual void Get1DProfile1EntranceParam(double &entranceParameter1,
+    virtual void get1DProfile1EntranceParam(double &entranceParameter1,
                                            double &entranceParameter2,
                                            double &entranceParameter3);
-    virtual void Get1DProfile1ExitParam(double &exitParameter1,
+    virtual void get1DProfile1ExitParam(double &exitParameter1,
                                        double &exitParameter2,
                                        double &exitParameter3);
-    virtual double GetFieldGap();
-    virtual void SetFieldGap(double gap);
+    virtual double getFieldGap();
+    virtual void setFieldGap(double gap);
 
     MapType getType() { return Type;}
 
     virtual void getOnaxisEz(std::vector<std::pair<double, double> > & onaxis);
 
+    virtual bool isInside(const Vector_t &r) const;
 protected:
     Fieldmap(const std::string &aFilename);
     virtual ~Fieldmap() { ;};
@@ -175,4 +177,9 @@ private:
 
 };
 
+inline bool Fieldmap::isInside(const Vector_t &r) const
+{
+    return true;
+}
+
 #endif
\ No newline at end of file
diff --git a/src/Classic/Fields/Interpolation/CMakeLists.txt b/src/Classic/Fields/Interpolation/CMakeLists.txt
index 5b857b501d8b337113c705aac8dc4b4f04039fd5..7cf76fb82ced6b9ee7e317b2f84fc5d546c9259d 100644
--- a/src/Classic/Fields/Interpolation/CMakeLists.txt
+++ b/src/Classic/Fields/Interpolation/CMakeLists.txt
@@ -17,4 +17,22 @@ include_directories (
   ${CMAKE_CURRENT_SOURCE_DIR}
 )
 
-add_sources(${_SRCS})
+ADD_OPAL_SOURCES(${_SRCS})
+
+set (HDRS
+    Interpolator3dGridTo1d.h
+    Interpolator3dGridTo3d.h
+    Mesh.h
+    MMatrix.h
+    MVector.h
+    PolynomialCoefficient.h
+    PolynomialPatch.h
+    PPSolveFactory.h
+    SolveFactory.h
+    SquarePolynomialVector.h
+    ThreeDGrid.h
+    TriLinearInterpolator.h
+    VectorMap.h
+)
+
+install (FILES ${HDRS} DESTINATION "${CMAKE_INSTALL_PREFIX}/include/Interpolation")
\ No newline at end of file
diff --git a/src/Classic/Filters/CMakeLists.txt b/src/Classic/Filters/CMakeLists.txt
index 4ad595908e08fec04cc4bca4f658bdfc4ad34341..3eaec6033d16a098f2540f57c32a96abe9c86755 100644
--- a/src/Classic/Filters/CMakeLists.txt
+++ b/src/Classic/Filters/CMakeLists.txt
@@ -9,4 +9,15 @@ include_directories (
   ${CMAKE_CURRENT_SOURCE_DIR}
   )
 
-add_sources(${_SRCS})
\ No newline at end of file
+ADD_OPAL_SOURCES(${_SRCS})
+
+set (HDRS
+    Filter.h
+    Filters.h
+    FixedFFTLowPass.h
+    RelativeFFTLowPass.h
+    SavitzkyGolay.h
+    Stencil.h
+)
+
+install (FILES ${HDRS} DESTINATION "${CMAKE_INSTALL_PREFIX}/include/Filters")
\ No newline at end of file
diff --git a/src/Classic/FixedAlgebra/CMakeLists.txt b/src/Classic/FixedAlgebra/CMakeLists.txt
index 7101432672dc12610a5af3fb3de65df0065e4053..dde31def09ae2fe9cd7c002034cfe8e62a3bebaa 100644
--- a/src/Classic/FixedAlgebra/CMakeLists.txt
+++ b/src/Classic/FixedAlgebra/CMakeLists.txt
@@ -6,4 +6,43 @@ include_directories (
   ${CMAKE_CURRENT_SOURCE_DIR}
   )
 
-add_sources(${_SRCS})
\ No newline at end of file
+ADD_OPAL_SOURCES(${_SRCS})
+
+set (HDRS
+    DragtFinnMap.h
+    DragtFinnNormalForm.h
+    FArray1D.h
+    FArray2D.h
+    FComplexEigen.h
+    FDoubleEigen.h
+    FDynamicFP.h
+    FLieGenerator.h
+    FLieGenerator.hpp
+    FLUMatrix.h
+    FMatrix.h
+    FMonomial.h
+    FNormalForm.h
+    FSlice.h
+    FStaticFP.h
+    FTpsData.h
+    FTps.h
+    FTps.hpp
+    FTpsMath.h
+    FVector.h
+    FVps.h
+    FVps.hpp
+    LinearFun.h
+    LinearFun.hpp
+    LinearMap.h
+    LinearMap.hpp
+    LinearMath.h
+    Taylor.h
+    Taylor.hpp
+    TransportFun.h
+    TransportFun.hpp
+    TransportMap.h
+    TransportMap.hpp
+    TransportMath.h
+)
+
+install (FILES ${HDRS} DESTINATION "${CMAKE_INSTALL_PREFIX}/include/FixedAlgebra")
\ No newline at end of file
diff --git a/src/Classic/FixedAlgebra/FTps.h b/src/Classic/FixedAlgebra/FTps.h
index bd88f517c153d9a25f3ea3494ffb27cf39e3018f..c0e886ab44dff5540c7ba090c824a5be8a5e3558 100644
--- a/src/Classic/FixedAlgebra/FTps.h
+++ b/src/Classic/FixedAlgebra/FTps.h
@@ -360,15 +360,15 @@ public:
 
     /// Make representation unique.
     inline void unique();
-    
+
     /// Get a list containing the indexes of non-zero coefficients of a FTps
     // Returns a STL list containing the indexes
     std::list<int> getListOfNonzeroCoefficients() const;
-    
+
     /// Extract exponents of coefficient
     // Retuns a 1D Array containing the exponents to index [b]index[/b].
     FArray1D<int, N> extractExponents(int index) const;
-    
+
     /// Multiply FTps with itself
     // Return the power of the truncated power series
     FTps<T, N> makePower(int power) const;
diff --git a/src/Classic/FixedAlgebra/FTps.hpp b/src/Classic/FixedAlgebra/FTps.hpp
index e7c38688e82e35f233334e565c4f2e6ec838cda7..3a720ba1f1d0b1053fa5341581d510f04c6e1718 100644
--- a/src/Classic/FixedAlgebra/FTps.hpp
+++ b/src/Classic/FixedAlgebra/FTps.hpp
@@ -1489,13 +1489,13 @@ FTps<T, N> FTps<T, N>::taylor(const Array1D<T> &series, int order) const {
     for(int m = 1; m <= order; ++m) {
         if(result.itsRep->trcOrd < m) result.setTruncOrder(m);
         result = x.multiply(result, m);
-        
+
         /*
          * has to be set, otherwise if coefficient is zero --> next coefficient doesn't get
          * counted, e.g. with cos(x)
          */
         result.setMinOrder(0);
-        
+
         result.itsRep->data[0] = series[order-m];
     }
 
@@ -1515,13 +1515,13 @@ void FTps<T, N>::unique() {
 
 template <class T, int N>
 std::list<int> FTps<T, N>::getListOfNonzeroCoefficients() const {
-    
+
     // get total number of coefficients
     int size = getSize();
-    
+
     // initialize list
     std::list<int> coeffs;
-    
+
     // loop over all coefficients
     for (int i = 0; i < size; ++i) {
         // get index of non-zero coefficients
@@ -1529,38 +1529,38 @@ std::list<int> FTps<T, N>::getListOfNonzeroCoefficients() const {
             coeffs.push_back(i);
         }
     }
-    
+
     return coeffs;
 }
 
 template <class T, int N>
 FArray1D<int, N> FTps<T, N>::extractExponents(int index) const {
-    
+
     // check index
     if ( index < 0 || getSize() - 1 < index)
         throw LogicalError("FVps<T,N>::extractExponents(var)","Index out of range.");
-    
+
     // get exponents of monomial
     FMonomial<N> mono = FTps<T, N>::getExponents(index);
-    
+
     // array of exponents
     FArray1D<int, N> expons;
-    
-    // copy monomials to array 
+
+    // copy monomials to array
     for (int i = 0; i < N; ++i)
         expons[i] = mono[i];
-    
+
     return expons;
 }
 
 template <class T, int N>
 FTps<T, N> FTps<T, N>::makePower(int power) const {
-    
+
     if (power < 0)
         throw LogicalError("FTps<T,N>::makePower(power)","Power is negative.");
-    
+
     FTps<T, N> result = *this;
-    
+
     // gets truncated in case of being bigger than global truncation order
     for (int i = 1; i < power; ++i) {
         //result *= *this;
diff --git a/src/Classic/FixedAlgebra/FTpsMath.h b/src/Classic/FixedAlgebra/FTpsMath.h
index 1e0240e0be2fbeb52a584b42e5c8d5a3f980fe11..07b8a0aab86d1242b20a6f5587db86b86fcd2dac 100644
--- a/src/Classic/FixedAlgebra/FTpsMath.h
+++ b/src/Classic/FixedAlgebra/FTpsMath.h
@@ -380,15 +380,15 @@ FTps<T, N> erf(const FTps<T, N> &x, int trunc) {
 
     T aZero = x[0];
     if(x.getMinOrder() != 0) aZero = T(0);
-    
+
     Array1D<T> series(trcOrder + 1);
     series[0] = std::erf(aZero);
     series[1] = 2.0 / std::sqrt(M_PI) * std::exp(-aZero*aZero);
-    
+
     for(int i = 2; i <= trcOrder; ++i) {
         series[i] = - 2.0 / double(i-1) * double((i-2)) * series[i-2] / double(i);
     }
-    
+
     return x.taylor(series, trcOrder);
 }
 
@@ -396,7 +396,7 @@ FTps<T, N> erf(const FTps<T, N> &x, int trunc) {
 template <class T, int N>
 FTps<T, N> erfc(const FTps<T, N> &x, int trunc) {
     // Default: trunc = EXACT
-    
+
     return T(1) - erf(x, trunc);
 }
 
diff --git a/src/Classic/FixedAlgebra/FVps.h b/src/Classic/FixedAlgebra/FVps.h
index f329382fab32f60a5b6d655a6cfcd3a8f7ffac98..7f9cd5013e8b08450d6e85703f89cea8d4a18b5b 100644
--- a/src/Classic/FixedAlgebra/FVps.h
+++ b/src/Classic/FixedAlgebra/FVps.h
@@ -231,8 +231,8 @@ public:
     /// Substitute map into matrix.
     FVps substituteInto(const FMatrix<T, N, N> &lhs) const;
 
-    // Get a FTps that is a combination of the polynomials of FVps.                                                                 
-    // Computes a FTps by multiplying the FTps of FVps using the powers specified by [b]power[/b].                                   
+    // Get a FTps that is a combination of the polynomials of FVps.
+    // Computes a FTps by multiplying the FTps of FVps using the powers specified by [b]power[/b].
     FTps<T, N> getFTps(const FArray1D<int, N>& power) const;
 
     /// Get a FVps from stream [b]is[/b].
diff --git a/src/Classic/FixedAlgebra/FVps.hpp b/src/Classic/FixedAlgebra/FVps.hpp
index fcca4d484fe38a791ea83164ec5bc06e04b23174..c7d6c2635921d9f4d9bdde94a451c0c313f248c9 100644
--- a/src/Classic/FixedAlgebra/FVps.hpp
+++ b/src/Classic/FixedAlgebra/FVps.hpp
@@ -291,26 +291,26 @@ FVps<T, N> FVps<T, N>::operator*(const FVps<T, N>& rhs) const {
     for(int i = 0; i < N; ++i) {
         // get truncated power series for variable i
         FTps<T, N> tps = this->getComponent(i);
-        
+
         // initialize tps of result
         FTps<T, N> r = 0.0;
         // fake order --> gets updated inside this function
         r.setMinOrder(1);
-        
+
         /* get coefficients and exponents of their monomials and multiply
          * truncated power series of rhs with appropriate power and coefficient
          */
         std::list<int> coeffs = tps.getListOfNonzeroCoefficients();
-        
+
         for(std::list<int>::iterator it = coeffs.begin(); it != coeffs.end(); ++it) {
-            
+
             FArray1D<int, N> expons = tps.extractExponents(*it);
-            
+
             // represents the monomial --> is polynomial due to multiplication of each variable's polynomial
             FTps<T, N> mono = 1.0;
-            
+
             for(int j = 0; j < N; ++j) {
-                
+
                 if (expons[j] != 0) {
                     // multiply each variable of the monomial of appropriate power, i.e. build monomial
                     FTps<T, N> tmp = rhs.getComponent(j);
@@ -319,17 +319,17 @@ FVps<T, N> FVps<T, N>::operator*(const FVps<T, N>& rhs) const {
             }
             // multiply truncated power series with appropriate coefficient
             mono *= tps.getCoefficient(*it);
-            
+
             /* sum up all polynomials that build the FTps of the result map for that variable,
              * make sure that the minimum order is correct.
              */
             r.setMinOrder(std::min(r.getMinOrder(), mono.getMinOrder()));
             r += mono;
-        }        
+        }
         // computation of Tps of variable i finished
         result.setComponent(i,r);
     }
-    
+
     return result;
 }
 
@@ -1032,24 +1032,24 @@ FVps<T, N> FVps<T, N>::substituteInto(const FMatrix<T, N, N> &lhs) const {
 
 template <class T, int N>
 FTps<T, N> FVps<T, N>::getFTps(const FArray1D<int, N>& power) const {
-    
-    // function does not handle negative powers   
+
+    // function does not handle negative powers
     if ( std::any_of(power.begin(), power.end(), [&](int p) { return p < 0; }) )
         throw LogicalError("FVps<T,N>::getFTps(power)", "Negative power.");
-    
+
     // initial Tps
     FTps<T, N> result = 1.0;
-    
+
     // go through variables and multiply its power to "result"
     for (int i = 0; i < N; ++i) {
         // get polynomial
         FTps<T, N> rhs = getComponent(i);
-        
+
         // multiply polynomials
         for (int j = 0; j < power[i]; ++j)
             result = result.multiply(rhs, FTps<T, N>::getGlobalTruncOrder()); // make sure that no global trunc exceeding
     }
-    
+
     return result;/*.truncate(FTps<T, N>::getGlobalTruncOrder());*/
 }
 
diff --git a/src/Classic/MemoryManagement/CMakeLists.txt b/src/Classic/MemoryManagement/CMakeLists.txt
index 476255adebce2782a937048dbe517eb06ae70188..2c8de143593b5860e3536052e71813dfdd717d46 100644
--- a/src/Classic/MemoryManagement/CMakeLists.txt
+++ b/src/Classic/MemoryManagement/CMakeLists.txt
@@ -5,4 +5,12 @@ include_directories (
   ${CMAKE_CURRENT_SOURCE_DIR}
   )
 
-add_sources(${_SRCS})
\ No newline at end of file
+ADD_OPAL_SOURCES(${_SRCS})
+
+set (HDRS
+    OwnPtr.h
+    Pointer.h
+    RCObject.h
+)
+
+install (FILES ${HDRS} DESTINATION "${CMAKE_INSTALL_PREFIX}/include/MemoryManagement")
\ No newline at end of file
diff --git a/src/Classic/Parser/CMakeLists.txt b/src/Classic/Parser/CMakeLists.txt
index 069c208ac70f17db7198317ef0a819c6e6a5450f..3816dac245bcc22a1d1c9477e8bdef050bfe9c92 100644
--- a/src/Classic/Parser/CMakeLists.txt
+++ b/src/Classic/Parser/CMakeLists.txt
@@ -15,4 +15,19 @@ include_directories (
   ${CMAKE_CURRENT_SOURCE_DIR}
   )
 
-add_sources(${_SRCS})
\ No newline at end of file
+ADD_OPAL_SOURCES(${_SRCS})
+
+set (HDRS
+    AbsFileStream.h
+    ClassicParser.h
+    FileStream.h
+    Parser.h
+    SimpleStatement.h
+    Statement.h
+    StringStream.h
+    TerminalStream.h
+    Token.h
+    TokenStream.h
+)
+
+install (FILES ${HDRS} DESTINATION "${CMAKE_INSTALL_PREFIX}/include/Parser")
\ No newline at end of file
diff --git a/src/Classic/Parser/ClassicParser.cpp b/src/Classic/Parser/ClassicParser.cpp
index 0a4ea207c93ff119ac6a321c5db5cfe45f077a17..47a3d93216e23bc3cf9193d10539a76ba46c7131 100644
--- a/src/Classic/Parser/ClassicParser.cpp
+++ b/src/Classic/Parser/ClassicParser.cpp
@@ -208,31 +208,31 @@ void ClassicParser::parse(Statement &statement) const {
     } catch(ParseError &ex) {
         *gmsg << endl << "*** Parse error detected by method \"" << ex.where()
               << "\"" << endl;
-        statement.printWhere(true);
-        statement.print();
-        *gmsg << ex.what() << endl << endl;
+        statement.printWhere(*IpplInfo::Error, true);
+        *gmsg << statement << "\n"
+              << ex.what() << endl << endl;
 	exit(1);
     } catch(ClassicException &ex) {
         *gmsg << endl << "*** Error detected by method \"" << ex.where()
               << "\"" << endl;
-        statement.printWhere(false);
-        statement.print();
-        *gmsg << ex.what() << endl << endl;
+        statement.printWhere(*IpplInfo::Error, false);
+        *gmsg << statement << "\n"
+              << ex.what() << endl << endl;
     } catch(std::bad_alloc &) {
         *gmsg << endl << "*** Error:" << endl;
-        statement.printWhere(false);
-        statement.print();
-        *gmsg << "Sorry, virtual memory exhausted." << endl << endl;
+        statement.printWhere(*IpplInfo::Error, false);
+        *gmsg << statement << "\n"
+              << "Sorry, virtual memory exhausted." << endl << endl;
     } catch(std::exception &ex) {
         *gmsg << endl << "*** Error:" << endl;
-        statement.printWhere(false);
-        statement.print();
-        *gmsg << "Internal CLASSIC error " << ex.what() << endl << endl;
+        statement.printWhere(*IpplInfo::Error, false);
+        *gmsg << statement << "\n"
+              << "Internal CLASSIC error " << ex.what() << endl << endl;
     } catch(...) {
         *gmsg << endl << "*** Error:" << endl;
-        statement.printWhere(false);
-        statement.print();
-        *gmsg << "Unexpected exception caught." << endl << endl;
+        statement.printWhere(*IpplInfo::Error, false);
+        *gmsg << statement << "\n"
+              << "Unexpected exception caught." << endl << endl;
 
 	// send problem to main where this will be propperly catched
 	throw std::runtime_error("Parser error");
@@ -512,4 +512,4 @@ void ClassicParser::run(TokenStream *is) const {
         parse(*statement);
         delete statement;
     }
-}
+}
\ No newline at end of file
diff --git a/src/Classic/Parser/FileStream.cpp b/src/Classic/Parser/FileStream.cpp
index 4ed14eaba55e4b8e74a78071727589a1a79e7e87..2a2fa4998710f1d7ec3d3d5b2bc2d1831d8defd1 100644
--- a/src/Classic/Parser/FileStream.cpp
+++ b/src/Classic/Parser/FileStream.cpp
@@ -20,6 +20,7 @@
 
 #include "Parser/FileStream.h"
 #include "Utilities/ParseError.h"
+#include "Utility/IpplInfo.h"
 #include <iomanip>
 #include <iostream>
 
@@ -67,7 +68,7 @@ bool FileStream::fillLine() {
         std::getline(is, line, '\n');
         line += "\n";
         curr_line++;
-        if(echoFlag) {
+        if(echoFlag && Ippl::myNode() == 0) {
             std::cerr.width(5);
             std::cerr << curr_line << " " << line;
         }
diff --git a/src/Classic/Parser/Statement.cpp b/src/Classic/Parser/Statement.cpp
index 2b7df03a9e35b44b1fb5ab3a91b10e9208a0e34b..fcacbec2615a69bf2a4c4bde2827c85786f4cfa4 100644
--- a/src/Classic/Parser/Statement.cpp
+++ b/src/Classic/Parser/Statement.cpp
@@ -190,30 +190,30 @@ void Statement::skip() {
 }
 
 
-void Statement::print() const {
+void Statement::print(std::ostream &msg) const {
     bool white = false;
 
     for(TokenList::const_iterator c = tokens.begin(); c != tokens.end(); c++) {
-        if(white && !c->isDel()) *gmsg << ' ';
+        if(white && !c->isDel()) msg << ' ';
         white = !c->isDel();
-        *gmsg << *c;
+        msg << *c;
     }
 
-    *gmsg << ';' << endl;
+    msg << ';' << std::endl;
 }
 
 
-void Statement::printWhere(bool withToken) const {
+void Statement::printWhere(Inform &msg, bool withToken) const {
 
-    *gmsg << "*** in line " << stat_line << " of file \"" << buffer_name << "\"";
+    msg << "*** in line " << stat_line << " of file \"" << buffer_name << "\"";
 
     if(withToken) {
         if(TokenList::const_iterator(curr) == tokens.end()) {
-            *gmsg << " at end of statement:" << endl;
+            msg << " at end of statement:" << endl;
         } else {
-            *gmsg << " before token \"" << *curr << "\":" << endl;
+            msg << " before token \"" << *curr << "\":" << endl;
         }
     } else {
-        *gmsg << ":\n";
+        msg << ":\n";
     }
-}
+}
\ No newline at end of file
diff --git a/src/Classic/Parser/Statement.h b/src/Classic/Parser/Statement.h
index d2b923e2d3ebf14f52b9804aaf00dc03cfb12f2f..bf6f5665f38356977dbac692df2e4b83e978be31 100644
--- a/src/Classic/Parser/Statement.h
+++ b/src/Classic/Parser/Statement.h
@@ -156,12 +156,12 @@ public:
 
     /// Print statement.
     //  Print the statement on [b]os[/b].
-    virtual void print() const;
+    virtual void print(std::ostream &os) const;
 
     /// Print position.
     //  Print a message, containing the stream name and its line in the input
     //  stream.  If [b]withToken[/b] is true, print also the last token parsed.
-    virtual void printWhere(bool withToken) const;
+    virtual void printWhere(Inform &msg, bool withToken) const;
 
 protected:
 
@@ -180,8 +180,16 @@ protected:
 
 // Output operator.
 inline std::ostream &operator<<(std::ostream &os, const Statement &statement) {
-    statement.print();
+    statement.print(os);
     return os;
 }
 
-#endif // MAD_Statement_HH
+inline Inform &operator<<(Inform &os, const Statement &statement) {
+    std::ostringstream msg;
+    statement.print(msg);
+    os << msg.str();
+
+    return os;
+}
+
+#endif // MAD_Statement_HH
\ No newline at end of file
diff --git a/src/Classic/Physics/CMakeLists.txt b/src/Classic/Physics/CMakeLists.txt
index 4ff6f4cecc0468e0968fa5363e2224f9236bebbd..9c58940daf4255e1d978f123702e7ecb0c8e5a8c 100644
--- a/src/Classic/Physics/CMakeLists.txt
+++ b/src/Classic/Physics/CMakeLists.txt
@@ -6,4 +6,10 @@ include_directories (
   ${CMAKE_CURRENT_SOURCE_DIR}
   )
 
-add_sources(${_SRCS})
\ No newline at end of file
+ADD_OPAL_SOURCES(${_SRCS})
+
+set (HDRS
+    Physics.h
+)
+
+install (FILES ${HDRS} DESTINATION "${CMAKE_INSTALL_PREFIX}/include/Physics")
\ No newline at end of file
diff --git a/src/Classic/Solvers/CMakeLists.txt b/src/Classic/Solvers/CMakeLists.txt
index 4ffecf9bd3d0db9ddc0076606a027937619b0632..ba32475f46986f33c1dd607163501996b0492c0e 100644
--- a/src/Classic/Solvers/CMakeLists.txt
+++ b/src/Classic/Solvers/CMakeLists.txt
@@ -9,4 +9,15 @@ include_directories (
   ${CMAKE_CURRENT_SOURCE_DIR}
   )
 
-add_sources(${_SRCS})
+ADD_OPAL_SOURCES(${_SRCS})
+
+set (HDRS
+    GreenWakeFunction.hh
+    CollimatorPhysics.hh
+    CSRWakeFunction.hh
+    SurfacePhysicsHandler.hh
+    WakeFunction.hh
+    CSRIGFWakeFunction.hh
+)
+
+install (FILES ${HDRS} DESTINATION "${CMAKE_INSTALL_PREFIX}/include/Solvers")
\ No newline at end of file
diff --git a/src/Classic/Solvers/CSRIGFWakeFunction.cpp b/src/Classic/Solvers/CSRIGFWakeFunction.cpp
index 46afbb7ce913ee02ce1360693758005c617183e5..47b617a5933347108f35210005fcff333920ff66 100644
--- a/src/Classic/Solvers/CSRIGFWakeFunction.cpp
+++ b/src/Classic/Solvers/CSRIGFWakeFunction.cpp
@@ -5,12 +5,15 @@
 #include "AbsBeamline/RBend.h"
 #include "AbsBeamline/SBend.h"
 #include "Utilities/Options.h"
+#include "Utilities/Util.h"
 
 #include <iostream>
 #include <fstream>
 
+extern Inform *gmsg;
+
 CSRIGFWakeFunction::CSRIGFWakeFunction(const std::string &name, ElementBase *element, std::vector<Filter *> filters, const unsigned int &N):
-    WakeFunction(name, element),
+    WakeFunction(name, element, N),
     filters_m(filters.begin(), filters.end()),
     lineDensity_m(),
     dlineDensitydz_m(),
@@ -21,11 +24,11 @@ CSRIGFWakeFunction::CSRIGFWakeFunction(const std::string &name, ElementBase *ele
 void CSRIGFWakeFunction::apply(PartBunch &bunch) {
     Inform msg("CSRWake ");
 
-    const double &meshSpacing = bunch.getMesh().get_meshSpacing(2);
-    const Vector_t &meshOrigin = bunch.getMesh().get_origin();
-
-    calculateLineDensity(bunch, meshSpacing);
-    unsigned int numOfSlices = lineDensity_m.size();
+    std::pair<double, double> meshInfo;
+    calculateLineDensity(bunch, meshInfo);
+    const double &meshOrigin = meshInfo.first;
+    const double &meshSpacing = meshInfo.second;
+    const unsigned int numOfSlices = lineDensity_m.size();
 
     if(Ez_m.size() < numOfSlices) {
         Ez_m.resize(numOfSlices, 0.0);
@@ -35,34 +38,33 @@ void CSRIGFWakeFunction::apply(PartBunch &bunch) {
     }
 
     for(unsigned int i = 0; i < numOfSlices; ++i) {
-      Ez_m[i] = 0.0;
+        Ez_m[i] = 0.0;
     }
 
     Vector_t smin, smax;
     bunch.get_bounds(smin, smax);
-    double minPathLength = smin(2) - FieldBegin_m;
+    double minPathLength = smin(2) + bunch.get_sPos() - FieldBegin_m;
     for(unsigned int i = 1; i < numOfSlices; i++) {
-      double pathLengthOfSlice = minPathLength + i * meshSpacing;
-      double angleOfSlice = 0.0;
-      angleOfSlice = pathLengthOfSlice/bendRadius_m;
-      if (angleOfSlice > 0.0 && angleOfSlice <= totalBendAngle_m){
-        calculateGreenFunction(bunch, meshSpacing);
-      }
-      // convolute with line density
-      calculateContributionInside(i, angleOfSlice, meshSpacing);
-      calculateContributionAfter(i, angleOfSlice, meshSpacing);
-      Ez_m[i] /= 4 * Physics::pi * Physics::epsilon_0;
+        double pathLengthOfSlice = minPathLength + i * meshSpacing;
+        double angleOfSlice = 0.0;
+        angleOfSlice = pathLengthOfSlice/bendRadius_m;
+        if (angleOfSlice > 0.0 && angleOfSlice <= totalBendAngle_m){
+            calculateGreenFunction(bunch, meshSpacing);
+        }
+        // convolute with line density
+        calculateContributionInside(i, angleOfSlice, meshSpacing);
+        calculateContributionAfter(i, angleOfSlice, meshSpacing);
+        Ez_m[i] /= 4 * Physics::pi * Physics::epsilon_0;
     }
 
     // calculate the wake field seen by the particles
     for(unsigned int i = 0; i < bunch.getLocalNum(); ++i) {
         const Vector_t &R = bunch.R[i];
-        unsigned int indexz = (unsigned int)floor((R(2) - meshOrigin(2)) / meshSpacing);
-        double leverz = (R(2) - meshOrigin(2)) / meshSpacing - indexz;
-        if(indexz < numOfSlices - 1)
-          bunch.Ef[i](2) += (1. - leverz) * Ez_m[indexz] + leverz * Ez_m[indexz + 1];
-        else
-          bunch.Ef[i](2) += Ez_m[numOfSlices-1];
+        unsigned int indexz = (unsigned int)floor((R(2) - meshOrigin) / meshSpacing);
+        double leverz = (R(2) - meshOrigin) / meshSpacing - indexz;
+        PAssert(indexz < numOfSlices - 1);
+
+        bunch.Ef[i](2) += (1. - leverz) * Ez_m[indexz] + leverz * Ez_m[indexz + 1];
     }
 
     if(Options::csrDump) {
@@ -78,17 +80,17 @@ void CSRIGFWakeFunction::apply(PartBunch &bunch) {
             if(counter == 0) file_number = 0;
 	    double spos = bunch.get_sPos();
 	    if (Ippl::myNode() == 0) {
-	      std::stringstream filename_str;
-	      filename_str << "data/" << bendName_m << "-CSRWake" << file_number << ".txt";
-	      std::ofstream csr(filename_str.str().c_str());
-	      csr << spos << ", " << FieldBegin_m << ", " << smin(2) << ", " << smax(2) << ", " << meshSpacing*64 << std::endl;
-	      for(unsigned int i = 0; i < lineDensity_m.size(); ++ i) {
-                csr << i *meshSpacing << "\t"
-                    << Ez_m[i] << "\t"
-                    << lineDensity_m[i] << std::endl;
-	      }
-	      csr.close();
-	      msg << "** wrote " << filename_str.str() << endl;
+                std::stringstream filename_str;
+                filename_str << "data/" << bendName_m << "-CSRWake" << file_number << ".txt";
+                std::ofstream csr(filename_str.str().c_str());
+                csr << spos << ", " << FieldBegin_m << ", " << smin(2) << ", " << smax(2) << ", " << meshSpacing*64 << std::endl;
+                for(unsigned int i = 0; i < lineDensity_m.size(); ++ i) {
+                    csr << i *meshSpacing << "\t"
+                        << Ez_m[i] << "\t"
+                        << lineDensity_m[i] << std::endl;
+                }
+                csr.close();
+                msg << "** wrote " << filename_str.str() << endl;
 	    }
             ++ file_number;
         }
@@ -99,43 +101,47 @@ void CSRIGFWakeFunction::apply(PartBunch &bunch) {
 
 void CSRIGFWakeFunction::initialize(const ElementBase *ref) {
     double End;
-    if(dynamic_cast<const RBend *>(ref)) {
-        const RBend *bend = dynamic_cast<const RBend *>(ref);
-        bendRadius_m = bend->GetBendRadius();
-        bend->getDimensions(Begin_m, End);
-        Length_m = bend->GetEffectiveLength();
-        FieldBegin_m = bend->GetEffectiveCenter() - Length_m / 2.0;
-        totalBendAngle_m = std::abs(bend->GetBendAngle());
-        bendName_m = bend->getName();
-    } else if(dynamic_cast<const SBend *>(ref)) {
-        const SBend *bend = dynamic_cast<const SBend *>(ref);
-        bendRadius_m = bend->GetBendRadius();
+    if(ref->getType() == ElementBase::RBEND ||
+       ref->getType() == ElementBase::SBEND) {
+
+        const Bend *bend = static_cast<const Bend *>(ref);
+        // const RBend *bend = dynamic_cast<const RBend *>(ref);
+        bendRadius_m = bend->getBendRadius();
         bend->getDimensions(Begin_m, End);
-        Length_m = bend->GetEffectiveLength();
-        FieldBegin_m = bend->GetEffectiveCenter() - Length_m / 2.0;
-        totalBendAngle_m = bend->GetBendAngle();
+        Length_m = bend->getEffectiveLength();
+        FieldBegin_m = bend->getEffectiveCenter() - Length_m / 2.0;
+        totalBendAngle_m = std::abs(bend->getBendAngle());
         bendName_m = bend->getName();
+
+    // } else if(dynamic_cast<const SBend *>(ref)) {
+    //     const SBend *bend = dynamic_cast<const SBend *>(ref);
+    //     bendRadius_m = bend->getBendRadius();
+    //     bend->getDimensions(Begin_m, End);
+    //     Length_m = bend->getEffectiveLength();
+    //     FieldBegin_m = bend->getEffectiveCenter() - Length_m / 2.0;
+    //     totalBendAngle_m = bend->getBendAngle();
+    //     bendName_m = bend->getName();
     }
+
+    *gmsg << level1 << __DBGMSG__ << "\t" << getName() << "\t" << bendName_m << endl;
 }
 
-void CSRIGFWakeFunction::calculateLineDensity(PartBunch &bunch, double meshSpacing) {
-    bunch.calcLineDensity();
-    bunch.getLineDensity(lineDensity_m);
+void CSRIGFWakeFunction::calculateLineDensity(PartBunch &bunch, std::pair<double, double> &meshInfo) {
+    bunch.calcLineDensity(nBins_m, lineDensity_m, meshInfo);
 
-// the following is only needed for after dipole
+    // the following is only needed for after dipole
     std::vector<Filter *>::const_iterator fit;
     for(fit = filters_m.begin(); fit != filters_m.end(); ++ fit) {
         (*fit)->apply(lineDensity_m);
     }
     dlineDensitydz_m.assign(lineDensity_m.begin(), lineDensity_m.end());
-    filters_m.back()->calc_derivative(dlineDensitydz_m, meshSpacing);
-
+    filters_m.back()->calc_derivative(dlineDensitydz_m, meshInfo.second);
 }
 
 void CSRIGFWakeFunction::calculateGreenFunction(PartBunch &bunch, double meshSpacing)
 {
     unsigned int numOfSlices = lineDensity_m.size();
-    double gamma = bunch.get_meanEnergy()/(bunch.getM()*1e-6)+1.0;
+    double gamma = bunch.get_meanKineticEnergy()/(bunch.getM()*1e-6)+1.0;
     double xmu_const = 3.0 * gamma * gamma * gamma / (2.0 * bendRadius_m);
     double chi_const = 9.0 / 16.0 * (6.0 - log(27.0 / 4.0));
 
@@ -145,16 +151,16 @@ void CSRIGFWakeFunction::calculateGreenFunction(PartBunch &bunch, double meshSpa
         double xmu = xmu_const * z;
         double b = sqrt(xmu * xmu + 1.0) + xmu;
         if(xmu < 1e-3)
-          Chi_m[i] = chi_const + 0.5 * pow(xmu, 2) - 7.0 / 54.0 * pow(xmu, 4) + 140.0 / 2187.0 * pow(xmu, 6);
+            Chi_m[i] = chi_const + 0.5 * pow(xmu, 2) - 7.0 / 54.0 * pow(xmu, 4) + 140.0 / 2187.0 * pow(xmu, 6);
         else
-          Chi_m[i] = 9.0 / 16.0 * (3.0 * (-2.0 * xmu * pow(b, 1.0/3.0) + pow(b, 2.0/3.0) + pow(b, 4.0/3.0)) +
-                     log(pow((1 - pow(b, 2.0 / 3.0)) / xmu, 2) / (1 + pow(b, 2.0 / 3.0) + pow(b, 4.0 / 3.0))));
+            Chi_m[i] = 9.0 / 16.0 * (3.0 * (-2.0 * xmu * pow(b, 1.0/3.0) + pow(b, 2.0/3.0) + pow(b, 4.0/3.0)) +
+                                     log(pow((1 - pow(b, 2.0 / 3.0)) / xmu, 2) / (1 + pow(b, 2.0 / 3.0) + pow(b, 4.0 / 3.0))));
     }
     double grn_const = -16.0/(27.0 * gamma * gamma * meshSpacing);
     Grn_m[0] = grn_const * (Chi_m[1] - Chi_m[0]);
     Grn_m[numOfSlices - 1] = 0.0;
     for(unsigned int i = 1; i < numOfSlices - 1; ++i) {
-      Grn_m[i] = grn_const * (Chi_m[i + 1] - 2.0 * Chi_m[i] + Chi_m[i - 1]);
+        Grn_m[i] = grn_const * (Chi_m[i + 1] - 2.0 * Chi_m[i] + Chi_m[i - 1]);
     }
 }
 
@@ -163,7 +169,7 @@ void CSRIGFWakeFunction::calculateContributionInside(size_t sliceNumber, double
     if(angleOfSlice > totalBendAngle_m || angleOfSlice < 0.0) return;
     int startSliceNum = 0;
     for(int j = sliceNumber; j >= startSliceNum; j--)
-      Ez_m[sliceNumber] += lineDensity_m[j] * Grn_m[sliceNumber - j];
+        Ez_m[sliceNumber] += lineDensity_m[j] * Grn_m[sliceNumber - j];
 }
 
 void CSRIGFWakeFunction::calculateContributionAfter(size_t sliceNumber, double angleOfSlice, double meshSpacing) {
diff --git a/src/Classic/Solvers/CSRIGFWakeFunction.hh b/src/Classic/Solvers/CSRIGFWakeFunction.hh
index d060c8fe322b537ca52de328b5f25faf81c7ccc4..65e8023b134ac5dc94490cd4f1e86639ffcef90c 100644
--- a/src/Classic/Solvers/CSRIGFWakeFunction.hh
+++ b/src/Classic/Solvers/CSRIGFWakeFunction.hh
@@ -19,7 +19,8 @@ public:
     virtual const std::string getType() const;
 
 private:
-    void calculateLineDensity(PartBunch & bunch, double meshSpacing);
+    void calculateLineDensity(PartBunch & bunch, std::pair<double, double> &meshInfo);
+
     void calculateContributionInside(size_t sliceNumber, double angleOfSlice, double meshSpacing);
     void calculateContributionAfter(size_t sliceNumber, double angleOfSlice, double meshSpacing);
     void calculateGreenFunction(PartBunch &bunch, double meshSpacing);
diff --git a/src/Classic/Solvers/CSRWakeFunction.cpp b/src/Classic/Solvers/CSRWakeFunction.cpp
index 2cafd21b816001f756a74cbfe93183d7aee4b990..29d5f89d2e80b097fe9617db1a5aa2b7c41e554d 100644
--- a/src/Classic/Solvers/CSRWakeFunction.cpp
+++ b/src/Classic/Solvers/CSRWakeFunction.cpp
@@ -5,12 +5,15 @@
 #include "AbsBeamline/RBend.h"
 #include "AbsBeamline/SBend.h"
 #include "Utilities/Options.h"
+#include "Utilities/Util.h"
 
 #include <iostream>
 #include <fstream>
 
+extern Inform *gmsg;
+
 CSRWakeFunction::CSRWakeFunction(const std::string &name, ElementBase *element, std::vector<Filter *> filters, const unsigned int &N):
-    WakeFunction(name, element),
+    WakeFunction(name, element, N),
     filters_m(filters.begin(), filters.end()),
     lineDensity_m(),
     dlineDensitydz_m(),
@@ -22,10 +25,11 @@ CSRWakeFunction::CSRWakeFunction(const std::string &name, ElementBase *element,
 void CSRWakeFunction::apply(PartBunch &bunch) {
     Inform msg("CSRWake ");
 
-    const double &meshSpacing = bunch.getMesh().get_meshSpacing(2);
-    const double centerFirstCell = bunch.getMesh().get_origin()[2] + 0.5 * meshSpacing;
-
-    calculateLineDensity(bunch, meshSpacing);
+    const double sPos = bunch.get_sPos();
+    std::pair<double, double> meshInfo;
+    calculateLineDensity(bunch, meshInfo);
+    const double &meshSpacing = meshInfo.second;
+    const double &meshOrigin = meshInfo.first + 0.5 * meshSpacing;
 
     if(Ez_m.size() < lineDensity_m.size()) {
         Ez_m.resize(lineDensity_m.size(), 0.0);
@@ -34,7 +38,9 @@ void CSRWakeFunction::apply(PartBunch &bunch) {
 
     Vector_t smin, smax;
     bunch.get_bounds(smin, smax);
-    double minPathLength = smin(2) - FieldBegin_m;
+    double minPathLength = smin(2) + sPos - FieldBegin_m;
+    if (sPos + smax(2) < FieldBegin_m) return;
+
     Ez_m[0] = 0.0;
     // calculate wake field of bunch
     for(unsigned int i = 1; i < lineDensity_m.size(); ++i) {
@@ -54,10 +60,10 @@ void CSRWakeFunction::apply(PartBunch &bunch) {
     // calculate the wake field seen by the particles
     for(unsigned int i = 0; i < bunch.getLocalNum(); ++i) {
         const Vector_t &R = bunch.R[i];
-        double distanceToCenterFirstCell = (R(2) - centerFirstCell) / meshSpacing;
-        // linearly gathering data in CELL centered way
-        unsigned int indexz = (unsigned int)floor(distanceToCenterFirstCell);
-        double leverz = distanceToCenterFirstCell - indexz;
+        double distanceToOrigin = (R(2) - meshOrigin) / meshSpacing;
+
+        unsigned int indexz = (unsigned int)floor(distanceToOrigin);
+        double leverz = distanceToOrigin - indexz;
         PAssert(indexz < lineDensity_m.size() - 1);
 
         bunch.Ef[i](2) += (1. - leverz) * Ez_m[indexz] + leverz * Ez_m[indexz + 1];
@@ -74,20 +80,21 @@ void CSRWakeFunction::apply(PartBunch &bunch) {
         if(print_criterion) {
             static unsigned int file_number = 0;
             if(counter == 0) file_number = 0;
-	    double spos = bunch.get_sPos();
 	    if (Ippl::myNode() == 0) {
-	      std::stringstream filename_str;
-	      filename_str << "data/" << bendName_m << "-CSRWake" << file_number << ".txt";
-	      std::ofstream csr(filename_str.str().c_str());
-	      csr << spos << std::endl;
-	      for(unsigned int i = 0; i < lineDensity_m.size(); ++ i) {
-                csr << i *meshSpacing << "\t"
-                    << Ez_m[i] << "\t"
-                    << lineDensity_m[i] << "\t"
-                    << dlineDensitydz_m[i] << std::endl;
-	      }
-	      csr.close();
-	      msg << "** wrote " << filename_str.str() << endl;
+                std::stringstream filename_str;
+                filename_str << "data/" << bendName_m << "-CSRWake" << file_number << ".txt";
+
+                std::ofstream csr(filename_str.str().c_str());
+                csr << std::setprecision(8);
+                csr << "# " << sPos + smin(2) - FieldBegin_m << "\t" << sPos + smax(2) - FieldBegin_m << std::endl;
+                for(unsigned int i = 0; i < lineDensity_m.size(); ++ i) {
+                  csr << i *meshSpacing << "\t"
+                      << Ez_m[i] << "\t"
+                      << lineDensity_m[i] << "\t"
+                      << dlineDensitydz_m[i] << std::endl;
+                }
+                csr.close();
+                msg << "** wrote " << filename_str.str() << endl;
 	    }
             ++ file_number;
         }
@@ -98,37 +105,28 @@ void CSRWakeFunction::apply(PartBunch &bunch) {
 
 void CSRWakeFunction::initialize(const ElementBase *ref) {
     double End;
-    if(dynamic_cast<const RBend *>(ref)) {
-        const RBend *bend = dynamic_cast<const RBend *>(ref);
-        bendRadius_m = bend->GetBendRadius();
+    if(ref->getType() == ElementBase::RBEND ||
+       ref->getType() == ElementBase::SBEND) {
+        const Bend *bend = static_cast<const Bend *>(ref);
+        bendRadius_m = bend->getBendRadius();
         bend->getDimensions(Begin_m, End);
-        Length_m = bend->GetEffectiveLength();
-        //xpang 09-19-2014 : removed "Begin_m +" from FieldBegin_m
-        FieldBegin_m = bend->GetEffectiveCenter() - Length_m / 2.0;
-        totalBendAngle_m = std::abs(bend->GetBendAngle());
-        bendName_m = bend->getName();
-    } else if(dynamic_cast<const SBend *>(ref)) {
-        const SBend *bend = dynamic_cast<const SBend *>(ref);
-        bendRadius_m = bend->GetBendRadius();
-        bend->getDimensions(Begin_m, End);
-        Length_m = bend->GetEffectiveLength();
-        //xpang 09-19-2014 : removed "Begin_m +" from FieldBegin_m
-        FieldBegin_m = bend->GetEffectiveCenter() - Length_m / 2.0;
-        totalBendAngle_m = bend->GetBendAngle();
+        Length_m = bend->getEffectiveLength();
+        FieldBegin_m = bend->getEffectiveCenter() - Length_m / 2.0;
+        totalBendAngle_m = std::abs(bend->getBendAngle());
         bendName_m = bend->getName();
     }
 }
 
-void CSRWakeFunction::calculateLineDensity(PartBunch &bunch, double meshSpacing) {
-    bunch.calcLineDensity();
-    bunch.getLineDensity(lineDensity_m);
+void CSRWakeFunction::calculateLineDensity(PartBunch &bunch, std::pair<double, double> &meshInfo) {
+    bunch.calcLineDensity(nBins_m, lineDensity_m, meshInfo);
 
     std::vector<Filter *>::const_iterator fit;
     for(fit = filters_m.begin(); fit != filters_m.end(); ++ fit) {
         (*fit)->apply(lineDensity_m);
     }
+
     dlineDensitydz_m.assign(lineDensity_m.begin(), lineDensity_m.end());
-    filters_m.back()->calc_derivative(dlineDensitydz_m, meshSpacing);
+    filters_m.back()->calc_derivative(dlineDensitydz_m, meshInfo.second);
 }
 
 void CSRWakeFunction::calculateContributionInside(size_t sliceNumber, double angleOfSlice, double meshSpacing) {
@@ -140,8 +138,8 @@ void CSRWakeFunction::calculateContributionInside(size_t sliceNumber, double ang
     if(relativeSlippageLength > sliceNumber) {
 
         /*
-        Break integral into sum of integrals between grid points, then
-        use linear interpolation between each grid point.
+          Break integral into sum of integrals between grid points, then
+          use linear interpolation between each grid point.
         */
 
         double dx1 = pow(sliceNumber, 2. / 3.);
diff --git a/src/Classic/Solvers/CSRWakeFunction.hh b/src/Classic/Solvers/CSRWakeFunction.hh
index 1e2ab3f1d70a8057c81e124512c371c16ae5616b..3a6cad9c40921b09417f674b326b48f871019329 100644
--- a/src/Classic/Solvers/CSRWakeFunction.hh
+++ b/src/Classic/Solvers/CSRWakeFunction.hh
@@ -19,7 +19,7 @@ public:
     virtual const std::string getType() const;
 
 private:
-    void calculateLineDensity(PartBunch & bunch, double meshSpacing);
+    void calculateLineDensity(PartBunch & bunch, std::pair<double, double> &meshInfo);
 
     void calculateContributionInside(size_t sliceNumber, double angleOfSlice, double meshSpacing);
     void calculateContributionAfter(size_t sliceNumber, double angleOfSlice, double meshSpacing);
diff --git a/src/Classic/Solvers/CollimatorPhysics.cpp b/src/Classic/Solvers/CollimatorPhysics.cpp
index 8daca079f1adf64aed5cb159c07df02243047521..a44d9df1717f7754cf9240103f9828590fa0bf39 100644
--- a/src/Classic/Solvers/CollimatorPhysics.cpp
+++ b/src/Classic/Solvers/CollimatorPhysics.cpp
@@ -114,17 +114,17 @@ void CollimatorPhysics::doPhysics(PartBunch &bunch, Degrader *deg, Collimator *c
      Do physics if
      -- particle in material
      -- particle not dead (locParts_m[i].label != -1.0)
-     
+
      Absorbed particle i: locParts_m[i].label = -1.0;
-     
+
      Particle goes back to beam if
      -- not absorbed and out of material
      */
-   
+
     for(size_t i = 0; i < locParts_m.size(); ++i) {
         Vector_t &R = locParts_m[i].Rincol;
         Vector_t &P = locParts_m[i].Pincol;
-        
+
         double Eng = (sqrt(1.0  + dot(P, P)) - 1) * m_p;
         if(locParts_m[i].label != -1) {
             if(checkHit(R,P,dT_m, deg, col)) {
@@ -168,19 +168,19 @@ void CollimatorPhysics::doPhysics(PartBunch &bunch, Degrader *deg, Collimator *c
 
 bool CollimatorPhysics::EnergyLoss(double &Eng, double &deltat) {
     /// Eng GeV
-    
+
     Material();
     double dEdx = 0.0;
     const double gamma = (Eng + m_p) / m_p;
     const double beta = sqrt(1.0 - 1.0 / (gamma * gamma));
     const double gamma2 = gamma * gamma;
     const double beta2 = beta * beta;
-    
+
     const double deltas = deltat * beta * Physics::c;
     const double deltasrho = deltas * 100 * rho_m;
     const double K = 4.0 * pi * Avo * r_e * r_e * m_e * 1E7;
     const double sigma_E = sqrt(K * m_e * rho_m * (Z_m/A_m)* deltas * 1E5);
-    
+
     if ((Eng > 0.00001) && (Eng < 0.0006)) {
         const double Ts = (Eng*1E6)/1.0073; // 1.0073 is the proton mass divided by the atomic mass number. T is in KeV
         const double epsilon_low = A2_c*pow(Ts,0.45);
@@ -191,13 +191,13 @@ bool CollimatorPhysics::EnergyLoss(double &Eng, double &deltat) {
         const double delta_E = delta_Eave + gsl_ran_gaussian(rGen_m,sigma_E);
         Eng = Eng + delta_E / 1E3;
     }
-    
+
     if (Eng >= 0.0006) {
         const double Tmax = 2.0 * m_e * 1e9 * beta2 * gamma2 /
         (1.0 + 2.0 * gamma * m_e / m_p + (m_e / m_p) * (m_e / m_p));
         dEdx = -K * z_p * z_p * Z_m / (A_m * beta2) *
         (1.0 / 2.0 * std::log(2 * m_e * 1e9 * beta2 * gamma2 * Tmax / I_m / I_m) - beta2);
-        
+
         // INFOMSG("stopping power_BB: " << dEdx << " MeV" << endl);
         const double delta_Eave = deltasrho * dEdx;
         double tmp = gsl_ran_gaussian(rGen_m,sigma_E);
@@ -255,7 +255,7 @@ void CollimatorPhysics::apply(PartBunch &bunch, size_t numParticlesInSimulation)
 
     /*
       Because this is not propper set in the Component class when calling in the Constructor
-    */  
+    */
     Degrader   *deg  = NULL;
     Collimator *coll = NULL;
 
@@ -279,13 +279,13 @@ void CollimatorPhysics::apply(PartBunch &bunch, size_t numParticlesInSimulation)
 
         //write particles to GPU if there are any to write
         if (dksParts_m.size() > 0) {
-	  //wrtie data from dksParts_m to the end of mem_ptr (offset = numparticles)  
+	  //wrtie data from dksParts_m to the end of mem_ptr (offset = numparticles)
 	  dksbase.writeDataAsync<PART_DKS>(mem_ptr, &dksParts_m[0],
 					   dksParts_m.size(), -1, numparticles);
-	  
+
 	  //update number of particles on Device
 	  numparticles += dksParts_m.size();
-	  
+
 	  //free locParts_m vector
 	  dksParts_m.erase(dksParts_m.begin(), dksParts_m.end());
         }
@@ -294,7 +294,7 @@ void CollimatorPhysics::apply(PartBunch &bunch, size_t numParticlesInSimulation)
         if (numparticles > 0) {
 	  dksbase.callCollimatorPhysics2(mem_ptr, par_ptr, numparticles);
         }
-	
+
         //sort device particles and get number of particles comming back to bunch
         numaddback = 0;
         if (numparticles > 0) {
@@ -323,10 +323,10 @@ void CollimatorPhysics::apply(PartBunch &bunch, size_t numParticlesInSimulation)
 				    -locParts_m[dksParts_m[i].localID].IDincol);
 	    }
 	  }
-	  
+
 	  //erase particles that came from device from host array
 	  dksParts_m.erase(dksParts_m.begin(), dksParts_m.end());
-	  
+
 	  //update number of particles on Device
 	  numparticles -= numaddback;
         }
@@ -342,21 +342,21 @@ void CollimatorPhysics::apply(PartBunch &bunch, size_t numParticlesInSimulation)
 
 	locPartsInMat_m = numparticles;
 	reduce(locPartsInMat_m,locPartsInMat_m, OpAddAssign());
-	
+
 	int maxPerNode = bunch.getLocalNum();
         reduce(maxPerNode, maxPerNode, OpMaxAssign());
-	
+
 	//more than one loop only if all the particles are in this degrader
 	if (allParticleInMat_m) {
 	  onlyOneLoopOverParticles = ( (unsigned)maxPerNode > bunch.getMinimumNumberOfParticlesPerCore() || locPartsInMat_m <= 0);
 	} else {
 	  onlyOneLoopOverParticles = true;
 	}
-	
+
       } while (onlyOneLoopOverParticles == false);
 
     } else {
-      
+
       do{
         IpplTimings::startTimer(DegraderLoopTimer_m);
 
@@ -372,13 +372,13 @@ void CollimatorPhysics::apply(PartBunch &bunch, size_t numParticlesInSimulation)
         */
         if (onlyOneLoopOverParticles)
 	  copyFromBunch(bunch);
-        
+
         T_m += dT_m;              // update local time
 
 	locPartsInMat_m = locParts_m.size();
 	reduce(locPartsInMat_m,locPartsInMat_m, OpAddAssign());
 
-	
+
 	int maxPerNode = bunch.getLocalNum();
         reduce(maxPerNode, maxPerNode, OpMaxAssign());
 	if (allParticleInMat_m) {
@@ -386,7 +386,7 @@ void CollimatorPhysics::apply(PartBunch &bunch, size_t numParticlesInSimulation)
 	} else {
 	  onlyOneLoopOverParticles = true;
 	}
-	
+
       } while (onlyOneLoopOverParticles == false);
 
     }
@@ -401,7 +401,7 @@ void CollimatorPhysics::apply(PartBunch &bunch, size_t numParticlesInSimulation)
         */
         deleteParticleFromLocalVector();
         IpplTimings::stopTimer(DegraderLoopTimer_m);
-      
+
         /*
           if we are not looping copy newly arrived particles
         */
@@ -420,7 +420,7 @@ void CollimatorPhysics::apply(PartBunch &bunch, size_t numParticlesInSimulation)
 	} else {
 	  onlyOneLoopOverParticles = true;
 	}
- 
+
     } while (onlyOneLoopOverParticles == false);
 
 #endif
@@ -437,7 +437,7 @@ const std::string CollimatorPhysics::getType() const {
 //  ------------------------------------------------------------------------
 void  CollimatorPhysics::Material() {
 
-    if(material_m == "Berilium") {
+    if(material_m == "BERILIUM") {
         Z_m = 4.0;
         A_m = 9.012;
         rho_m = 1.848;
@@ -453,7 +453,7 @@ void  CollimatorPhysics::Material() {
 
     }
 
-    else if(material_m == "Graphite") {
+    else if(material_m == "GRAPHITE") {
         Z_m = 6.0;
         A_m = 12.0107;
         rho_m = 2.210;
@@ -469,7 +469,7 @@ void  CollimatorPhysics::Material() {
 
     }
 
-    else if(material_m == "GraphiteR6710") {
+    else if(material_m == "GRAPHITER6710") {
         Z_m = 6.0;
         A_m = 12.0107;
         rho_m = 1.88;
@@ -485,7 +485,7 @@ void  CollimatorPhysics::Material() {
 
     }
 
-    else if(material_m == "Molybdenum") {
+    else if(material_m == "MOLYBDENUM") {
         Z_m = 42.0;
         A_m = 95.94;
         rho_m = 10.22;
@@ -506,7 +506,7 @@ void  CollimatorPhysics::Material() {
       Z from http://journals.aps.org/prb/pdf/10.1103/PhysRevB.40.8530
     */
 
-    else if(material_m == "Mylar") {
+    else if(material_m == "MYLAR") {
         Z_m = 6.702;
         A_m = 12.88;
         rho_m = 1.4;
@@ -522,7 +522,7 @@ void  CollimatorPhysics::Material() {
 
 
     //new materials
-    else if (material_m == "Aluminum") {
+    else if (material_m == "ALUMINUM") {
         Z_m = 13;
         A_m = 26.98;
         rho_m = 2.7;
@@ -537,7 +537,7 @@ void  CollimatorPhysics::Material() {
         A5_c = 2.023e-2;
     }
 
-    else if (material_m == "Copper") {
+    else if (material_m == "COPPER") {
         Z_m = 29;
         A_m = 63.54;
         rho_m = 8.96;
@@ -552,7 +552,7 @@ void  CollimatorPhysics::Material() {
         A5_c = 2.242e-2;
     }
 
-    else if (material_m == "Titan") {
+    else if (material_m == "TITAN") {
         Z_m = 22;
         A_m = 47.8;
         rho_m = 4.54;
@@ -567,7 +567,7 @@ void  CollimatorPhysics::Material() {
         A5_c = 8.930e-3;
     }
 
-    else if (material_m == "AluminaAl2O3") {
+    else if (material_m == "ALUMINAAL2O3") {
         Z_m = 50;
         A_m = 101.96;
         rho_m = 3.97;
@@ -582,7 +582,7 @@ void  CollimatorPhysics::Material() {
         A5_c = 4.474e-3;
     }
 
-    else if (material_m == "Air") {
+    else if (material_m == "AIR") {
         Z_m = 7;
         A_m = 14;
         rho_m = 0.0012;
@@ -597,7 +597,7 @@ void  CollimatorPhysics::Material() {
         A5_c = 2.513e-2;
     }
 
-    else if (material_m == "Kapton") {
+    else if (material_m == "KAPTON") {
         Z_m = 6;
         A_m = 12;
         rho_m = 1.4;
@@ -612,7 +612,7 @@ void  CollimatorPhysics::Material() {
         A5_c = 1.638e-2;
     }
 
-    else if (material_m == "Gold") {
+    else if (material_m == "GOLD") {
         Z_m = 79;
         A_m = 197;
         rho_m = 19.3;
@@ -627,7 +627,7 @@ void  CollimatorPhysics::Material() {
         A5_c = 2.077e-2;
     }
 
-    else if (material_m == "Water") {
+    else if (material_m == "WATER") {
         Z_m = 10;
         A_m = 18;
         rho_m = 1;
@@ -644,7 +644,7 @@ void  CollimatorPhysics::Material() {
 
     else {
       throw GeneralClassicException("CollimatorPhysics::Material","Material not found ...");
-    } 
+    }
     // mean exitation energy from Leo
     if (Z_m < 13.0)
         I_m = 12 * Z_m + 7.0;
@@ -814,7 +814,6 @@ void CollimatorPhysics::addBackToBunch(PartBunch &bunch, unsigned i) {
     bunch.R[bunch.getLocalNum()-1]           = locParts_m[i].Rincol;
     bunch.P[bunch.getLocalNum()-1]           = locParts_m[i].Pincol;
     bunch.Q[bunch.getLocalNum()-1]           = locParts_m[i].Qincol;
-    bunch.LastSection[bunch.getLocalNum()-1] = locParts_m[i].LastSecincol;
     bunch.Bf[bunch.getLocalNum()-1]          = locParts_m[i].Bfincol;
     bunch.Ef[bunch.getLocalNum()-1]          = locParts_m[i].Efincol;
     bunch.dt[bunch.getLocalNum()-1]          = locParts_m[i].DTincol;
@@ -842,7 +841,7 @@ void CollimatorPhysics::copyFromBunch(PartBunch &bunch)
     const unsigned int minNumOfParticlesPerCore = bunch.getMinimumNumberOfParticlesPerCore();
     for(unsigned int i = 0; i < nL; ++i) {
         if ((bunch.Bin[i]==-1 || bunch.Bin[i]==1) && ((nL-ne)>minNumOfParticlesPerCore)
-	    && checkHit(bunch.R[i],bunch.P[i],dT_m, deg, coll)) 
+	    && checkHit(bunch.R[i],bunch.P[i],dT_m, deg, coll))
 	  {
             PART x;
             x.localID      = i;
@@ -852,7 +851,6 @@ void CollimatorPhysics::copyFromBunch(PartBunch &bunch)
             x.Rincol       = bunch.R[i];
             x.Pincol       = bunch.P[i];
             x.Qincol       = bunch.Q[i];
-            x.LastSecincol = bunch.LastSection[i];
             x.Bfincol      = bunch.Bf[i];
             x.Efincol      = bunch.Ef[i];
             x.label        = 0;            // allive in matter
@@ -865,7 +863,7 @@ void CollimatorPhysics::copyFromBunch(PartBunch &bunch)
 	    bunch.destroy(1, i);
         }
     }
-    
+
 }
 
 
@@ -913,7 +911,7 @@ bool CollimatorPhysics::stillAlive(PartBunch &bunch) {
   if(collshape_m == "DEGRADER" && locPartsInMat_m == 0) {
     Degrader   *deg  = NULL;
     deg = dynamic_cast<Degrader *>(element_ref_m);
-    
+
     //get the size of the degrader
     double zBegin, zEnd;
     deg->getDimensions(zBegin, zEnd);
@@ -986,7 +984,6 @@ void CollimatorPhysics::addBackToBunchDKS(PartBunch &bunch, unsigned i) {
     bunch.P[bunch.getLocalNum()-1]           = dksParts_m[i].Pincol;
 
     bunch.Q[bunch.getLocalNum()-1]           = locParts_m[id].Qincol;
-    bunch.LastSection[bunch.getLocalNum()-1] = locParts_m[id].LastSecincol;
     bunch.Bf[bunch.getLocalNum()-1]          = locParts_m[id].Bfincol;
     bunch.Ef[bunch.getLocalNum()-1]          = locParts_m[id].Efincol;
     bunch.dt[bunch.getLocalNum()-1]          = locParts_m[id].DTincol;
@@ -1008,11 +1005,11 @@ void CollimatorPhysics::copyFromBunchDKS(PartBunch &bunch)
 
     const size_t nL = bunch.getLocalNum();
     size_t ne = 0;
-    const unsigned int minNumOfParticlesPerCore = bunch.getMinimumNumberOfParticlesPerCore(); 
+    const unsigned int minNumOfParticlesPerCore = bunch.getMinimumNumberOfParticlesPerCore();
 
     for(unsigned int i = 0; i < nL; ++i) {
-	if ((bunch.Bin[i]==-1 || bunch.Bin[i]==1) && ((nL-ne)>minNumOfParticlesPerCore) 
-	    && checkHit(bunch.R[i],bunch.P[i],dT_m, deg, coll)) 
+	if ((bunch.Bin[i]==-1 || bunch.Bin[i]==1) && ((nL-ne)>minNumOfParticlesPerCore)
+	    && checkHit(bunch.R[i],bunch.P[i],dT_m, deg, coll))
 	  {
 
             PART x;
@@ -1023,7 +1020,6 @@ void CollimatorPhysics::copyFromBunchDKS(PartBunch &bunch)
             x.Rincol       = bunch.R[i];
             x.Pincol       = bunch.P[i];
             x.Qincol       = bunch.Q[i];
-            x.LastSecincol = bunch.LastSection[i];
             x.Bfincol      = bunch.Bf[i];
             x.Efincol      = bunch.Ef[i];
             x.label        = 0;            // allive in matter
@@ -1045,11 +1041,11 @@ void CollimatorPhysics::copyFromBunchDKS(PartBunch &bunch)
 	    bunch.destroy(1, i);
 	  }
     }
-    
+
 }
 
-void CollimatorPhysics::setupCollimatorDKS(PartBunch &bunch, Degrader *deg, 
-					   size_t numParticlesInSimulation) 
+void CollimatorPhysics::setupCollimatorDKS(PartBunch &bunch, Degrader *deg,
+					   size_t numParticlesInSimulation)
 {
 
     if (curandInitSet == -1) {
@@ -1179,6 +1175,4 @@ void CollimatorPhysics::deleteParticleFromLocalVectorDKS() {
 
 }
 
-#endif
-
-
+#endif
\ No newline at end of file
diff --git a/src/Classic/Solvers/CollimatorPhysics.hh b/src/Classic/Solvers/CollimatorPhysics.hh
index c2d99f4e92a780fdce1fb293c1af62a78031daa5..3da3fdd0a121492d03a7fc96d1ced072ac7c1e4c 100644
--- a/src/Classic/Solvers/CollimatorPhysics.hh
+++ b/src/Classic/Solvers/CollimatorPhysics.hh
@@ -110,13 +110,13 @@ private:
     void applyDKS();
     void applyHost(PartBunch &bunch, Degrader *deg, Collimator *coll);
     void deleteParticleFromLocalVectorDKS();
-  
+
 #endif
 
 
     void deleteParticleFromLocalVector();
 
-    bool checkHit(Vector_t R, Vector_t P, double dt, Degrader *deg, Collimator *coll); 
+    bool checkHit(Vector_t R, Vector_t P, double dt, Degrader *deg, Collimator *coll);
 
     inline void calcStat(double Eng) {
       Eavg_m += Eng;
@@ -127,9 +127,9 @@ private:
     }
 
     bool allParticlesIn_m;
-  
+
     double  T_m;                     // own time, maybe larger than in the bunch object
-                                    
+
     double dT_m;                     // dt from bunch
 
     gsl_rng *rGen_m;
@@ -168,7 +168,7 @@ private:
 #ifdef OPAL_DKS
     DKSBase dksbase;
     int curandInitSet;
-  
+
     int ierr;
     int maxparticles;
     int numparticles;
diff --git a/src/Classic/Solvers/GreenWakeFunction.cpp b/src/Classic/Solvers/GreenWakeFunction.cpp
index 97ad8bf5a292ce1d6fcad648aabf03acadc86029..e612204eaaf544b81454c78093a29e8dbf3b4a77 100644
--- a/src/Classic/Solvers/GreenWakeFunction.cpp
+++ b/src/Classic/Solvers/GreenWakeFunction.cpp
@@ -1,9 +1,9 @@
 #include "Solvers/GreenWakeFunction.hh"
 #include "Algorithms/PartBunch.h"
 #include "Utilities/GeneralClassicException.h"
-//#ifdef ENABLE_WAKE_TESTS
+#ifdef ENABLE_WAKE_TESTS
 #include "Solvers/TestLambda.h" // used for tests
-//#endif
+#endif
 
 #include <fstream>
 #include <string>
@@ -55,7 +55,7 @@ GreenWakeFunction::GreenWakeFunction(const std::string &name,
                                      int direction,
                                      bool constLength,
                                      std::string fname):
-    WakeFunction(name, element),
+    WakeFunction(name, element, NBIN),
     lineDensity_m(),
     //~ FftWField_m(0),
     NBin_m(NBIN),
@@ -153,9 +153,8 @@ void GreenWakeFunction::apply(PartBunch &bunch) {
     }
 
     // Calculate the line density of the particle bunch
-    bunch.boundp(); //IFF: added boundp (need if no FS available)
-    bunch.calcLineDensity();
-    bunch.getLineDensity(lineDensity_m);
+    std::pair<double, double> meshInfo;
+    bunch.calcLineDensity(nBins_m, lineDensity_m, meshInfo);
 
 #ifdef ENABLE_WAKE_DEBUG
     *gmsg << "* ************* W A K E ************************************************************ " << endl;
@@ -243,6 +242,7 @@ void GreenWakeFunction::apply(PartBunch &bunch) {
  * @brief   Just a test function
  */
 void GreenWakeFunction::testApply(PartBunch &bunch) {
+#ifdef ENABLE_WAKE_TESTS
     double spacing;
     // determine K and charge
     double charge = 0.8e-9; // nC
@@ -260,7 +260,6 @@ void GreenWakeFunction::testApply(PartBunch &bunch) {
 
     compEnergy(K, charge, testLambda, OutEnergy.data());
 
-#ifdef ENABLE_WAKE_TESTS
     ofstream  f2("OutEnergy.dat");
     f2 << "# Energy of the Wake calculated in Opal\n"
        << "# Z0 = " << Z0_m << "\n"
diff --git a/src/Classic/Solvers/WakeFunction.hh b/src/Classic/Solvers/WakeFunction.hh
index 8fb0510aba77afbcf5b902429c9a76fbe222d22f..cf45a7802ced059e17b7ce49168d1c6b71634f8a 100644
--- a/src/Classic/Solvers/WakeFunction.hh
+++ b/src/Classic/Solvers/WakeFunction.hh
@@ -9,8 +9,10 @@ class PartBunch;
 
 class WakeFunction {
 public:
-    WakeFunction(std::string name, ElementBase *elref):
-        name_m(name) { }
+    WakeFunction(std::string name, ElementBase *elref, unsigned int n):
+        name_m(name),
+        nBins_m(n) { };
+
     virtual ~WakeFunction(){ };
     virtual void initialize(const ElementBase *ref){ };
     virtual void apply(PartBunch &bunch) = 0;
@@ -19,6 +21,9 @@ public:
         return name_m;
     }
 
+protected:
+    const unsigned int nBins_m;
+
 private:
     const std::string name_m;
 };
diff --git a/src/Classic/Structure/CMakeLists.txt b/src/Classic/Structure/CMakeLists.txt
index 3b058425d6f103f13e54b6c4ef650baf80d50c1f..b24161bc273de274fe93f3ce177e7b4ce5b77612 100644
--- a/src/Classic/Structure/CMakeLists.txt
+++ b/src/Classic/Structure/CMakeLists.txt
@@ -1,9 +1,17 @@
 set (_SRCS
     LossDataSink.cpp
+    MeshGenerator.cpp
   )
 
 include_directories (
   ${CMAKE_CURRENT_SOURCE_DIR}
 )
 
-add_sources(${_SRCS})
+ADD_OPAL_SOURCES(${_SRCS})
+
+set (HDRS
+    LossDataSink.h
+    MeshGenerator.h
+)
+
+install (FILES ${HDRS} DESTINATION "${CMAKE_INSTALL_PREFIX}/include/Structure")
\ No newline at end of file
diff --git a/src/Classic/Structure/LossDataSink.cpp b/src/Classic/Structure/LossDataSink.cpp
index ef444b397b160dcf6cdc7f3b9ec6d17ff7664f0f..98c5767f2e66d72f79293fe56efceafb377edd92 100644
--- a/src/Classic/Structure/LossDataSink.cpp
+++ b/src/Classic/Structure/LossDataSink.cpp
@@ -4,15 +4,25 @@
 #include "Utilities/Options.h"
 #include "AbstractObjects/OpalData.h"
 #include "Utilities/GeneralClassicException.h"
-#include "config.h"
-#include "revision.h"
+#include "Utilities/Util.h"
 
-#include <assert.h>
+#include <boost/filesystem.hpp>
+#include "OPALconfig.h"
 
-LossDataSink::LossDataSink(std::string elem, bool hdf5Save):
+#include <cassert>
+
+#define REPORTONERROR(rc) reportOnError(rc, __FILE__, __LINE__)
+
+extern Inform *gmsg;
+
+std::map<double, std::string> LossDataSink::statFileEntries_s;
+
+LossDataSink::LossDataSink(std::string elem, bool hdf5Save, ElementBase::ElementType type):
     element_m(elem),
     h5hut_mode_m(hdf5Save),
-    H5file_m(0)
+    H5file_m(0),
+    H5call_m(0),
+    type_m(type)
 {
     x_m.clear();
     y_m.clear();
@@ -28,7 +38,14 @@ LossDataSink::LossDataSink(std::string elem, bool hdf5Save):
 LossDataSink::LossDataSink(const LossDataSink &rsh):
     element_m(rsh.element_m),
     h5hut_mode_m(rsh.h5hut_mode_m),
-    H5file_m(rsh.H5file_m)
+    H5file_m(rsh.H5file_m),
+    H5call_m(rsh.H5call_m),
+    RefPartR_m(rsh.RefPartR_m),
+    RefPartP_m(rsh.RefPartP_m),
+    globalTrackStep_m(rsh.globalTrackStep_m),
+    refTime_m(rsh.refTime_m),
+    spos_m(rsh.spos_m),
+    type_m(rsh.type_m)
 {
     x_m.clear();
     y_m.clear();
@@ -48,9 +65,6 @@ LossDataSink::LossDataSink() {
 LossDataSink::~LossDataSink() {
     if (H5file_m) {
         h5_int64_t rc;
-#if defined (NDEBUG)
-        (void)rc;
-#endif
         rc = H5CloseFile(H5file_m);
         assert (rc != H5_ERR);
         H5file_m = 0;
@@ -58,7 +72,7 @@ LossDataSink::~LossDataSink() {
     Ippl::Comm->barrier();
 }
 
-void LossDataSink::openH5() {
+void LossDataSink::openH5(h5_int32_t mode) {
 #if defined (USE_H5HUT2)
     h5_prop_t props = H5CreateFileProp ();
     MPI_Comm comm = Ippl::getComm();
@@ -70,6 +84,7 @@ void LossDataSink::openH5() {
                                       "failed to open h5 file '" + fn_m + "'");
     }
 #else
+
     H5file_m = H5OpenFile(fn_m.c_str(), H5_O_WRONLY, Ippl::getComm());
     if(H5file_m == (void*)H5_ERR) {
         throw GeneralClassicException("LossDataSink::openH5",
@@ -80,68 +95,48 @@ void LossDataSink::openH5() {
 
 void LossDataSink::writeHeaderH5() {
 
-    h5_int64_t rc;
     // Write file attributes to describe phase space to H5 file.
     std::stringstream OPAL_version;
-    OPAL_version << PACKAGE_NAME << " " << PACKAGE_VERSION << " git rev. " << GIT_VERSION;
-    rc = H5WriteFileAttribString(H5file_m, "OPAL_version", OPAL_version.str().c_str());
-    if(rc != H5_SUCCESS)
-        ERRORMSG("H5 rc= " << rc << " in " << __FILE__ << " @ line " << __LINE__ << endl);
-    rc = H5WriteFileAttribString(H5file_m, "tUnit", "s");
-    if(rc != H5_SUCCESS)
-        ERRORMSG("H5 rc= " << rc << " in " << __FILE__ << " @ line " << __LINE__ << endl);
-    rc = H5WriteFileAttribString(H5file_m, "xUnit", "m");
-    if(rc != H5_SUCCESS)
-        ERRORMSG("H5 rc= " << rc << " in " << __FILE__ << " @ line " << __LINE__ << endl);
-    rc = H5WriteFileAttribString(H5file_m, "yUnit", "m");
-    if(rc != H5_SUCCESS)
-        ERRORMSG("H5 rc= " << rc << " in " << __FILE__ << " @ line " << __LINE__ << endl);
-    rc = H5WriteFileAttribString(H5file_m, "zUnit", "m");
-    if(rc != H5_SUCCESS)
-        ERRORMSG("H5 rc= " << rc << " in " << __FILE__ << " @ line " << __LINE__ << endl);
-    rc = H5WriteFileAttribString(H5file_m, "pxUnit", "#beta#gamma");
-    if(rc != H5_SUCCESS)
-        ERRORMSG("H5 rc= " << rc << " in " << __FILE__ << " @ line " << __LINE__ << endl);
-    rc = H5WriteFileAttribString(H5file_m, "pyUnit", "#beta#gamma");
-    if(rc != H5_SUCCESS)
-        ERRORMSG("H5 rc= " << rc << " in " << __FILE__ << " @ line " << __LINE__ << endl);
-    rc = H5WriteFileAttribString(H5file_m, "pzUnit", "#beta#gamma");
-    if(rc != H5_SUCCESS)
-        ERRORMSG("H5 rc= " << rc << " in " << __FILE__ << " @ line " << __LINE__ << endl);
-    rc = H5WriteFileAttribString(H5file_m, "idUnit", "1");
-    if(rc != H5_SUCCESS)
-        ERRORMSG("H5 rc= " << rc << " in " << __FILE__ << " @ line " << __LINE__ << endl);
+    OPAL_version << PACKAGE_NAME << " " << PACKAGE_VERSION_STR << " git rev. " << Util::getGitRevision();
+    REPORTONERROR(H5WriteFileAttribString(H5file_m, "OPAL_version", OPAL_version.str().c_str()));
+    REPORTONERROR(H5WriteFileAttribString(H5file_m, "tUnit", "s"));
+    REPORTONERROR(H5WriteFileAttribString(H5file_m, "xUnit", "m"));
+    REPORTONERROR(H5WriteFileAttribString(H5file_m, "yUnit", "m"));
+    REPORTONERROR(H5WriteFileAttribString(H5file_m, "zUnit", "m"));
+    REPORTONERROR(H5WriteFileAttribString(H5file_m, "pxUnit", "#beta#gamma"));
+    REPORTONERROR(H5WriteFileAttribString(H5file_m, "pyUnit", "#beta#gamma"));
+    REPORTONERROR(H5WriteFileAttribString(H5file_m, "pzUnit", "#beta#gamma"));
+    REPORTONERROR(H5WriteFileAttribString(H5file_m, "idUnit", "1"));
 
     /// in case of circular machines
     if (hasTimeAttribute()) {
-      rc = H5WriteFileAttribString(H5file_m, "turnUnit", "1");
-      if(rc != H5_SUCCESS)
-	ERRORMSG("H5 rc= " << rc << " in " << __FILE__ << " @ line " << __LINE__ << endl);
+        REPORTONERROR(H5WriteFileAttribString(H5file_m, "turnUnit", "1"));
 
-      rc = H5WriteFileAttribString(H5file_m, "timeUnit", "s");
-      if(rc != H5_SUCCESS)
-	ERRORMSG("H5 rc= " << rc << " in " << __FILE__ << " @ line " << __LINE__ << endl);
+        REPORTONERROR(H5WriteFileAttribString(H5file_m, "timeUnit", "s"));
     }
-    rc = H5WriteFileAttribString(H5file_m, "SPOSUnit", "mm");
-    if(rc != H5_SUCCESS)
-        ERRORMSG("H5 rc= " << rc << " in " << __FILE__ << " @ line " << __LINE__ << endl);
-    rc = H5WriteFileAttribString(H5file_m, "TIMEUnit", "s");
-    if(rc != H5_SUCCESS)
-        ERRORMSG("H5 rc= " << rc << " in " << __FILE__ << " @ line " << __LINE__ << endl);
-
-    rc = H5WriteFileAttribString(H5file_m, "mpart", "GeV");
-    if(rc != H5_SUCCESS)
-        ERRORMSG("H5 rc= " << rc << " in " << __FILE__ << " @ line " << __LINE__ << endl);
-    rc = H5WriteFileAttribString(H5file_m, "qi", "C");
-    if(rc != H5_SUCCESS)
-        ERRORMSG("H5 rc= " << rc << " in " << __FILE__ << " @ line " << __LINE__ << endl);
-
-    rc = H5AddAttachment(H5file_m, OpalData::getInstance()->getInputFn().c_str());
-    if(rc != H5_SUCCESS)
-        ERRORMSG("H5 rc= " << rc << " in " << __FILE__ << " @ line " << __LINE__ << endl);
+    REPORTONERROR(H5WriteFileAttribString(H5file_m, "SPOSUnit", "mm"));
+    REPORTONERROR(H5WriteFileAttribString(H5file_m, "TIMEUnit", "s"));
+
+    REPORTONERROR(H5WriteFileAttribString(H5file_m, "mpart", "GeV"));
+    REPORTONERROR(H5WriteFileAttribString(H5file_m, "qi", "C"));
+
+    REPORTONERROR(H5AddAttachment(H5file_m, OpalData::getInstance()->getInputFn().c_str()));
+}
+
+void LossDataSink::addReferenceParticle(const Vector_t &x,
+                                        const  Vector_t &p,
+                                        double time,
+                                        double spos,
+                                        long long globalTrackStep
+                                        ) {
+    RefPartR_m.push_back(x);
+    RefPartP_m.push_back(p);
+    globalTrackStep_m.push_back((h5_int64_t)globalTrackStep);
+    spos_m.push_back(spos);
+    refTime_m.push_back(time);
 }
 
-void LossDataSink::addParticle(const Vector_t x,const  Vector_t p, const size_t  id) {
+void LossDataSink::addParticle(const Vector_t &x,const  Vector_t &p, const size_t  id) {
     x_m.push_back(x(0));
     y_m.push_back(x(1));
     z_m.push_back(x(2));
@@ -152,27 +147,40 @@ void LossDataSink::addParticle(const Vector_t x,const  Vector_t p, const size_t
 }
 
 // For ring type simulation, dump the time and turn number
-void LossDataSink::addParticle(const Vector_t x, const Vector_t p, const size_t id, const double time, const size_t turn) {
+void LossDataSink::addParticle(const Vector_t &x, const Vector_t &p, const size_t id, const double time, const size_t turn) {
     addParticle(x, p, id);
     turn_m.push_back(turn);
     time_m.push_back(time);
 }
 
-void LossDataSink::save() {
+void LossDataSink::save(unsigned int numSets) {
 
     if (element_m == std::string("")) return;
 
     if (hasNoParticlesToDump()) return;
 
     if (h5hut_mode_m) {
+        namespace fs = boost::filesystem;
 
         if (!Options::enableHDF5) return;
 
         fn_m = element_m + std::string(".h5");
-	INFOMSG("Save " << fn_m << endl);
-	openH5();
-	writeHeaderH5();
-	saveH5();
+	INFOMSG(level2 << "Save " << fn_m << endl);
+        if (Options::openMode == Options::WRITE || !fs::exists(fn_m)) {
+            openH5();
+            writeHeaderH5();
+        } else {
+            openH5(H5_O_RDONLY);
+            H5call_m = H5GetNumSteps(H5file_m);
+            H5CloseFile(H5file_m);
+            openH5(H5_O_APPEND);
+        }
+
+        splitSets(numSets);
+        saveStatistics(numSets);
+        for (unsigned int i = 0; i < numSets; ++ i) {
+            saveH5(i);
+        }
 	H5CloseFile(H5file_m);
 	H5file_m = 0;
 	Ippl::Comm->barrier();
@@ -201,6 +209,11 @@ void LossDataSink::save() {
     id_m.clear();
     turn_m.clear();
     time_m.clear();
+    spos_m.clear();
+    refTime_m.clear();
+    RefPartR_m.clear();
+    RefPartP_m.clear();
+    globalTrackStep_m.clear();
 }
 
 // Note: This was changed to calculate the global number of dumped particles
@@ -224,17 +237,20 @@ bool LossDataSink::hasTimeAttribute() {
 
     reduce(tLoc, tLoc, OpAddAssign());
 
-    return tLoc != 0;
+    return tLoc > 0;
 }
 
 
 
 
 
-void LossDataSink::saveH5() {
-    h5_int64_t rc;
-
+void LossDataSink::saveH5(unsigned int setIdx) {
+    size_t startIdx = 0;
     size_t nLoc = x_m.size();
+    if (setIdx + 1 < startSet_m.size()) {
+        startIdx = startSet_m[setIdx];
+        nLoc = startSet_m[setIdx + 1] - startSet_m[setIdx];
+    }
 
     std::unique_ptr<char[]> varray(new char[(nLoc)*sizeof(double)]);
     double *farray = reinterpret_cast<double *>(varray.get());
@@ -251,71 +267,66 @@ void LossDataSink::saveH5() {
     reduce(locN.get(), locN.get() + Ippl::getNodes(), globN.get(), OpAddAssign());
 
     /// Set current record/time step.
-    rc = H5SetStep(H5file_m, 0);
-    if(rc != H5_SUCCESS)
-        ERRORMSG("H5 rc= " << rc << " in " << __FILE__ << " @ line " << __LINE__ << endl);
-    rc = H5PartSetNumParticles(H5file_m, nLoc);
-    if(rc != H5_SUCCESS)
-        ERRORMSG("H5 rc= " << rc << " in " << __FILE__ << " @ line " << __LINE__ << endl);
-
+    REPORTONERROR(H5SetStep(H5file_m, H5call_m));
+    REPORTONERROR(H5PartSetNumParticles(H5file_m, nLoc));
+
+    if (setIdx < spos_m.size()) {
+        REPORTONERROR(H5WriteStepAttribFloat64(H5file_m, "SPOS", &(spos_m[setIdx]), 1));
+        REPORTONERROR(H5WriteStepAttribFloat64(H5file_m, "TIME", &(refTime_m[setIdx]), 1));
+        REPORTONERROR(H5WriteStepAttribFloat64(H5file_m, "RefPartR", (h5_float64_t *)&(RefPartR_m[setIdx]), 3));
+        REPORTONERROR(H5WriteStepAttribFloat64(H5file_m, "RefPartP", (h5_float64_t *)&(RefPartP_m[setIdx]), 3));
+        REPORTONERROR(H5WriteStepAttribInt64(H5file_m, "GlobalTrackStep", &(globalTrackStep_m[setIdx]), 1));
+    }
     // Write all data
-    for(size_t i = 0; i < nLoc; i++)
-        farray[i] = x_m[i];
-    rc = H5PartWriteDataFloat64(H5file_m, "x", farray);
-    if(rc != H5_SUCCESS)
-        ERRORMSG("H5 rc= " << rc << " in " << __FILE__ << " @ line " << __LINE__ << endl);
-
-    for(size_t i = 0; i < nLoc; i++)
-        farray[i] = y_m[i];
-    rc = H5PartWriteDataFloat64(H5file_m, "y", farray);
-    if(rc != H5_SUCCESS)
-        ERRORMSG("H5 rc= " << rc << " in " << __FILE__ << " @ line " << __LINE__ << endl);
-
-    for(size_t i = 0; i < nLoc; i++)
-        farray[i] = z_m[i];
-    rc = H5PartWriteDataFloat64(H5file_m, "z", farray);
-    if(rc != H5_SUCCESS)
-        ERRORMSG("H5 rc= " << rc << " in " << __FILE__ << " @ line " << __LINE__ << endl);
-
-    for(size_t i = 0; i < nLoc; i++)
-        farray[i] = px_m[i];
-    rc = H5PartWriteDataFloat64(H5file_m, "px", farray);
-    if(rc != H5_SUCCESS)
-        ERRORMSG("H5 rc= " << rc << " in " << __FILE__ << " @ line " << __LINE__ << endl);
-
-    for(size_t i = 0; i < nLoc; i++)
-        farray[i] = py_m[i];
-    rc = H5PartWriteDataFloat64(H5file_m, "py", farray);
-    if(rc != H5_SUCCESS)
-        ERRORMSG("H5 rc= " << rc << " in " << __FILE__ << " @ line " << __LINE__ << endl);
-
-    for(size_t i = 0; i < nLoc; i++)
-        farray[i] = pz_m[i];
-    rc = H5PartWriteDataFloat64(H5file_m, "pz", farray);
-    if(rc != H5_SUCCESS)
-        ERRORMSG("H5 rc= " << rc << " in " << __FILE__ << " @ line " << __LINE__ << endl);
+    size_t j = startIdx;
+    for(size_t i = 0; i < nLoc; ++ i, ++ j)
+        farray[i] = x_m[j];
+    REPORTONERROR(H5PartWriteDataFloat64(H5file_m, "x", farray));
+
+    j = startIdx;
+    for(size_t i = 0; i < nLoc; ++ i, ++ j)
+        farray[i] = y_m[j];
+    REPORTONERROR(H5PartWriteDataFloat64(H5file_m, "y", farray));
+
+    j = startIdx;
+    for(size_t i = 0; i < nLoc; ++ i, ++ j)
+        farray[i] = z_m[j];
+    REPORTONERROR(H5PartWriteDataFloat64(H5file_m, "z", farray));
+
+    j = startIdx;
+    for(size_t i = 0; i < nLoc; ++ i, ++ j)
+        farray[i] = px_m[j];
+    REPORTONERROR(H5PartWriteDataFloat64(H5file_m, "px", farray));
+
+    j = startIdx;
+    for(size_t i = 0; i < nLoc; ++ i, ++ j)
+        farray[i] = py_m[j];
+    REPORTONERROR(H5PartWriteDataFloat64(H5file_m, "py", farray));
+
+    j = startIdx;
+    for(size_t i = 0; i < nLoc; ++ i, ++ j)
+        farray[i] = pz_m[j];
+    REPORTONERROR(H5PartWriteDataFloat64(H5file_m, "pz", farray));
 
     /// Write particle id numbers.
-    for(size_t i = 0; i < nLoc; i++)
-        larray[i] =  id_m[i];
-    rc = H5PartWriteDataInt64(H5file_m, "id", larray);
-    if(rc != H5_SUCCESS)
-        ERRORMSG("H5 rc= " << rc << " in " << __FILE__ << " @ line " << __LINE__ << endl);
+    j = startIdx;
+    for(size_t i = 0; i < nLoc; ++ i, ++ j)
+        larray[i] =  id_m[j];
+    REPORTONERROR(H5PartWriteDataInt64(H5file_m, "id", larray));
 
     if (hasTimeAttribute()) {
-      for(size_t i = 0; i < nLoc; i++)
-	farray[i] = time_m[i];
-      rc = H5PartWriteDataFloat64(H5file_m, "time", farray);
-      if(rc != H5_SUCCESS)
-	ERRORMSG("H5 rc= " << rc << " in " << __FILE__ << " @ line " << __LINE__ << endl);
-
-      for(size_t i = 0; i < nLoc; i++)
-	larray[i] =  turn_m[i];
-      rc = H5PartWriteDataInt64(H5file_m, "turn", larray);
-      if(rc != H5_SUCCESS)
-	ERRORMSG("H5 rc= " << rc << " in " << __FILE__ << " @ line " << __LINE__ << endl);
+        j = startIdx;
+        for(size_t i = 0; i < nLoc; ++ i, ++ j)
+            farray[i] = time_m[j];
+        REPORTONERROR(H5PartWriteDataFloat64(H5file_m, "time", farray));
+
+        j = startIdx;
+        for(size_t i = 0; i < nLoc; ++ i, ++ j)
+            larray[i] =  turn_m[j];
+        REPORTONERROR(H5PartWriteDataInt64(H5file_m, "turn", larray));
     }
-    H5call_m++;
+
+    ++ H5call_m;
 }
 
 void LossDataSink::saveASCII() {
@@ -445,9 +456,434 @@ void LossDataSink::saveASCII() {
     }
 }
 
-// vi: set et ts=4 sw=4 sts=4:
-// Local Variables:
-// mode:c
-// c-basic-offset: 4
-// indent-tabs-mode:nil
-// End:
+void LossDataSink::splitSets(unsigned int numSets) {
+    if (numSets <= 1) return;
+
+    const size_t nLoc = x_m.size();
+    size_t avgNumPerSet = nLoc / numSets;
+    std::vector<size_t> numPartsInSet(numSets, avgNumPerSet);
+    size_t test = numSets * avgNumPerSet;
+    for (unsigned int j = 0; j < (nLoc - numSets * avgNumPerSet); ++ j) {
+        ++ numPartsInSet[j];
+        ++ test;
+    }
+
+    if (/*nLoc > 0 && */time_m.size() == nLoc) {
+        std::vector<double> meanT(2 * numSets, 0.0);
+        std::vector<double> timeRange(2 * numSets, 0.0);
+        double minmaxT[] = {time_m[0], -time_m[0]};
+        size_t i = 0;
+        for (unsigned int j = 0; j < numSets; ++ j) {
+            const size_t &numThisSet = numPartsInSet[j];
+            for (size_t k = 0; k < numThisSet; ++ k, ++ i) {
+                meanT[2 * j] += time_m[i];
+                minmaxT[0] = std::min(minmaxT[0], time_m[i]);
+                minmaxT[1] = std::min(minmaxT[1], -time_m[i]);
+            }
+            meanT[2 * j + 1] = numThisSet;
+        }
+
+        reduce(&(meanT[0]), &(meanT[0]) + 2 * numSets, &(meanT[0]), OpAddAssign());
+        reduce(minmaxT, minmaxT + 2, minmaxT, OpMinAssign());
+
+        for (unsigned int j = 0; j < numSets; ++ j) {
+            meanT[2 * j] /= meanT[2 * j + 1];
+        }
+
+        timeRange[0] = minmaxT[0];
+        for (unsigned int j = 1; j < numSets; ++ j) {
+            timeRange[2 * j - 1] = 0.5 * (meanT[2 * (j - 1)] + meanT[2 * j]);
+            timeRange[2 * j] = timeRange[2 * j - 1];
+        }
+        timeRange[2 * numSets - 1] = -minmaxT[1];
+
+        size_t j = 0;
+        size_t idxPrior = 0;
+        startSet_m.push_back(0);
+
+        for (size_t idx = 0; idx < nLoc; ++ idx) {
+            if (time_m[idx] > timeRange[2 * j + 1]) {
+                startSet_m.push_back(idx);
+                numPartsInSet[j] = idx - idxPrior;
+                idxPrior = idx;
+                ++ j;
+            }
+        }
+        numPartsInSet[numSets - 1] = nLoc - idxPrior;
+        startSet_m.push_back(nLoc);
+
+        i = 0;
+        for (unsigned int j = 0; j < numSets; ++ j) {
+            const size_t &numThisSet = numPartsInSet[j];
+            for (size_t k = 0; k < numThisSet; ++ k, ++ i) {
+                meanT[2 * j] += time_m[i];
+                minmaxT[0] = std::min(minmaxT[0], time_m[i]);
+                minmaxT[1] = std::min(minmaxT[1], -time_m[i]);
+            }
+            meanT[2 * j + 1] = numThisSet;
+        }
+
+        reduce(&(meanT[0]), &(meanT[0]) + 2 * numSets, &(meanT[0]), OpAddAssign());
+
+        for (unsigned int j = 0; j < numSets; ++ j) {
+            meanT[2 * j] /= meanT[2 * j + 1];
+        }
+
+    }
+}
+
+void LossDataSink::saveStatistics(unsigned int numSets) {
+    if (type_m != ElementBase::MONITOR || !hasTimeAttribute()) return;
+
+    for (unsigned int setIdx = 0; setIdx < numSets; ++ setIdx) {
+
+        size_t startIdx = 0;
+        size_t nLoc = x_m.size();
+        if (setIdx + 1 < startSet_m.size()) {
+            startIdx = startSet_m[setIdx];
+            nLoc = startSet_m[setIdx + 1] - startSet_m[setIdx];
+        }
+
+        double tmean(0.0), trms(0.0);
+        Vector_t rmean(0.0), pmean(0.0), rrms(0.0), prms(0.0), rprms(0.0), normEmit(0.0);
+        Vector_t rsqsum(0.0), psqsum(0.0), rpsum(0.0), eps2(0.0), eps_norm(0.0), fac(0.0);
+
+        double part[6];
+
+        const unsigned int totalSize = 45;
+        double plainData[totalSize];
+        double rmax[] = {0.0, 0.0, 0.0};
+
+        {
+            Util::KahanAccumulation data[totalSize];
+            Util::KahanAccumulation *centroid = data + 1;
+            Util::KahanAccumulation *moments = data + 7;
+            Util::KahanAccumulation *others = data + 43;
+
+            data[0].sum = nLoc;
+
+            unsigned int idx = startIdx;
+            for(unsigned long k = 0; k < nLoc; ++ k, ++ idx) {
+                part[1] = px_m[idx];
+                part[3] = py_m[idx];
+                part[5] = pz_m[idx];
+                part[0] = x_m[idx];
+                part[2] = y_m[idx];
+                part[4] = z_m[idx];
+
+                for(int i = 0; i < 6; i++) {
+                    centroid[i] += part[i];
+                    for(int j = 0; j <= i; j++) {
+                        moments[i * 6 + j] += part[i] * part[j];
+                    }
+                }
+                others[0] += time_m[idx];
+                others[1] += std::pow(time_m[idx], 2);
+
+                rmax[0] = std::max(rmax[0], std::abs(x_m[idx]));
+                rmax[1] = std::max(rmax[1], std::abs(y_m[idx]));
+                rmax[2] = std::max(rmax[2], std::abs(z_m[idx]));
+            }
+
+            for(int i = 0; i < 6; i++) {
+                for(int j = 0; j < i; j++) {
+                    moments[j * 6 + i] = moments[i * 6 + j];
+                }
+            }
+
+            for (unsigned int i = 0; i < totalSize; ++ i) {
+                plainData[i] = data[i].sum;
+            }
+        }
+
+        reduce(plainData, plainData + totalSize, plainData, OpAddAssign());
+        reduce(rmax, rmax + 3, rmax, OpMaxAssign());
+
+        if (Ippl::myNode() != 0) continue;
+
+        double *centroid = plainData + 1;
+        double *moments = plainData + 7;
+        double *others = plainData + 43;
+        double nTotal = plainData[0];
+        for(unsigned int i = 0 ; i < 3u; i++) {
+            rmean(i) = centroid[2 * i] / nTotal;
+            pmean(i) = centroid[(2 * i) + 1] / nTotal;
+            rsqsum(i) = moments[2 * i * 6 + 2 * i] - nTotal * rmean(i) * rmean(i);
+            psqsum(i) = std::max(0.0, moments[(2 * i + 1) * 6 + (2 * i) + 1] - nTotal * pmean(i) * pmean(i));
+            rpsum(i) = moments[(2 * i) * 6 + (2 * i) + 1] - nTotal * rmean(i) * pmean(i);
+        }
+        tmean = others[0] / nTotal;
+        trms = sqrt(std::max(0.0, (others[1] / nTotal - std::pow(tmean, 2))));
+
+        eps2 = (rsqsum * psqsum - rpsum * rpsum) / (1.0 * nTotal * nTotal);
+
+        rpsum /= nTotal;
+
+        for(unsigned int i = 0 ; i < 3u; i++) {
+            rrms(i) = sqrt(std::max(0.0, rsqsum(i)) / nTotal);
+            prms(i) = sqrt(std::max(0.0, psqsum(i)) / nTotal);
+            eps_norm(i)  =  std::sqrt(std::max(0.0, eps2(i)));
+            double tmp = rrms(i) * prms(i);
+            fac(i) = (tmp == 0) ? 0.0 : 1.0 / tmp;
+        }
+
+        rprms = rpsum * fac;
+
+        std::stringstream statOut;
+        statOut.precision(8);
+        statOut << element_m << "\t"
+                << spos_m[setIdx] << "\t"
+                << refTime_m[setIdx] * 1e9 << "\t"
+                << (unsigned int)floor(nTotal + 0.5) << "\t"
+                << rrms(0) << "\t"
+                << rrms(1) << "\t"
+                << rrms(2) << "\t"
+                << trms * 1e9 << "\t"
+                << prms(0) << "\t"
+                << prms(1) << "\t"
+                << prms(2) << "\t"
+                << eps_norm(0) << "\t"
+                << eps_norm(1) << "\t"
+                << eps_norm(2) << "\t"
+                << rmean(0) << "\t"
+                << rmean(1) << "\t"
+                << rmean(2) << "\t"
+                << tmean * 1e9 << "\t"
+                << RefPartR_m[setIdx](0) << "\t"
+                << RefPartR_m[setIdx](1) << "\t"
+                << RefPartR_m[setIdx](2) << "\t"
+                << RefPartP_m[setIdx](0) << "\t"
+                << RefPartP_m[setIdx](1) << "\t"
+                << RefPartP_m[setIdx](2) << "\t"
+                << rmax[0] << "\t"
+                << rmax[1] << "\t"
+                << rmax[2] << "\t"
+                << rprms(0) << "\t"
+                << rprms(1) << "\t"
+                << rprms(2) << "\t"
+                << std::endl;
+
+        statFileEntries_s.insert(std::make_pair(spos_m[setIdx], statOut.str()));
+    }
+}
+
+void LossDataSink::writeStatistics() {
+    if (Ippl::myNode() != 0) return;
+
+    namespace fs = boost::filesystem;
+
+    std::string fileName = OpalData::getInstance()->getInputBasename() + std::string("_Monitors.stat");
+    std::ofstream statOut;
+
+    if (Options::openMode == Options::APPEND && fs::exists(fileName)) {
+        Util::rewindLinesSDDS(fileName, statFileEntries_s.begin()->first);
+
+        statOut.open(fileName, std::ios::app);
+    } else {
+        statOut.open(fileName);
+        std::string indent("        ");
+
+        statOut << "SDDS1\n";
+        statOut << "&description \n"
+                << indent << "text=\"Statistics data of monitors\", \n"
+                << indent << "contents=\"stat parameters\"\n"
+                << "&end\n";
+        statOut << "&parameter \n"
+                << indent << "name=revision, \n"
+                << indent << "type=string, \n"
+                << indent << "description=\"git revision of opal\"\n"
+                << "&end\n";
+        statOut << "&column \n"
+                << indent << "name=name, \n"
+                << indent << "type=string \n"
+                << indent << "description=\"1 Monitor name\"\n"
+                << "&end\n";
+        statOut << "&column \n"
+                << indent << "name=s, \n"
+                << indent << "type=double, \n"
+                << indent << "units=m, \n"
+                << indent << "description=\"2 Longitudinal Position\"\n"
+                << "&end\n";
+        statOut << "&column \n"
+                << indent << "name=t, \n"
+                << indent << "type=double, \n"
+                << indent << "units=ns, \n"
+                << indent << "description=\"3 Passage Time Reference Particle\"\n"
+                << "&end\n";
+        statOut << "&column \n"
+                << indent << "name=numParticles, \n"
+                << indent << "type=long, \n"
+                << indent << "units=1, \n"
+                << indent << "description=\"4 Number of Macro Particles\"\n"
+                << "&end\n";
+        statOut << "&column \n"
+                << indent << "name=rms_x, \n"
+                << indent << "type=double, \n"
+                << indent << "units=m, \n"
+                << indent << "description=\"5 RMS Beamsize in x\"\n"
+                << "&end\n";
+        statOut << "&column \n"
+                << indent << "name=rms_y, \n"
+                << indent << "type=double, \n"
+                << indent << "units=m, \n"
+                << indent << "description=\"6 RMS Beamsize in y\"\n"
+                << "&end\n";
+        statOut << "&column \n"
+                << indent << "name=rms_s, \n"
+                << indent << "type=double, \n"
+                << indent << "units=m, \n"
+                << indent << "description=\"7 RMS Beamsize in s\"\n"
+                << "&end\n";
+        statOut << "&column \n"
+                << indent << "name=rms_t, \n"
+                << indent << "type=double, \n"
+                << indent << "units=ns, \n"
+                << indent << "description=\"8 RMS Passage Time\"\n"
+                << "&end\n";
+        statOut << "&column \n"
+                << indent << "name=rms_px, \n"
+                << indent << "type=double, \n"
+                << indent << "units=1, \n"
+                << indent << "description=\"9 RMS Momenta in x\"\n"
+                << "&end\n";
+        statOut << "&column \n"
+                << indent << "name=rms_py, \n"
+                << indent << "type=double, \n"
+                << indent << "units=1, \n"
+                << indent << "description=\"10 RMS Momenta in y\"\n"
+                << "&end\n";
+        statOut << "&column \n"
+                << indent << "name=rms_ps, \n"
+                << indent << "type=double, \n"
+                << indent << "units=1, \n"
+                << indent << "description=\"11 RMS Momenta in s\"\n"
+                << "&end\n";
+        statOut << "&column \n"
+                << indent << "name=emit_x, \n"
+                << indent << "type=double, \n"
+                << indent << "units=m, \n"
+                << indent << "description=\"12 Normalized Emittance x\"\n"
+                << "&end\n";
+        statOut << "&column \n"
+                << indent << "name=emit_y, \n"
+                << indent << "type=double, \n"
+                << indent << "units=m, \n"
+                << indent << "description=\"13 Normalized Emittance y\"\n"
+                << "&end\n";
+        statOut << "&column \n"
+                << indent << "name=emit_s, \n"
+                << indent << "type=double, \n"
+                << indent << "units=m, \n"
+                << indent << "description=\"14 Normalized Emittance s\"\n"
+                << "&end\n";
+        statOut << "&column \n"
+                << indent << "name=mean_x, \n"
+                << indent << "type=double, \n"
+                << indent << "units=m, \n"
+                << indent << "description=\"15 Mean Beam Position in x\"\n"
+                << "&end\n";
+        statOut << "&column \n"
+                << indent << "name=mean_y, \n"
+                << indent << "type=double, \n"
+                << indent << "units=m, \n"
+                << indent << "description=\"16 Mean Beam Position in y\"\n"
+                << "&end\n";
+        statOut << "&column \n"
+                << indent << "name=mean_s, \n"
+                << indent << "type=double, \n"
+                << indent << "units=m, \n"
+                << indent << "description=\"17 Mean Beam Position in s\"\n"
+                << "&end\n";
+        statOut << "&column \n"
+                << indent << "name=mean_t, \n"
+                << indent << "type=double, \n"
+                << indent << "units=ns, \n"
+                << indent << "description=\"18 Mean Passage Time\"\n"
+                << "&end\n";
+        statOut << "&column \n"
+                << indent << "name=ref_x, \n"
+                << indent << "type=double, \n"
+                << indent << "units=m, \n"
+                << indent << "description=\"19 x coordinate of reference particle in lab cs\"\n"
+                << "&end\n";
+        statOut << "&column \n"
+                << indent << "name=ref_y, \n"
+                << indent << "type=double, \n"
+                << indent << "units=m, \n"
+                << indent << "description=\"20 y coordinate of reference particle in lab cs\"\n"
+                << "&end\n";
+        statOut << "&column \n"
+                << indent << "name=ref_z, \n"
+                << indent << "type=double, \n"
+                << indent << "units=m, \n"
+                << indent << "description=\"21 z coordinate of reference particle in lab cs\"\n"
+                << "&end\n";
+        statOut << "&column \n"
+                << indent << "name=ref_px, \n"
+                << indent << "type=double, \n"
+                << indent << "units=1, \n"
+                << indent << "description=\"22 x momentum of reference particle in lab cs\"\n"
+                << "&end\n";
+        statOut << "&column \n"
+                << indent << "name=ref_py, \n"
+                << indent << "type=double, \n"
+                << indent << "units=1, \n"
+                << indent << "description=\"23 y momentum of reference particle in lab cs\"\n"
+                << "&end\n";
+        statOut << "&column \n"
+                << indent << "name=ref_pz, \n"
+                << indent << "type=double, \n"
+                << indent << "units=1, \n"
+                << indent << "description=\"24 z momentum of reference particle in lab cs\"\n"
+                << "&end\n";
+        statOut << "&column \n"
+                << indent << "name=max_x, \n"
+                << indent << "type=double, \n"
+                << indent << "units=m, \n"
+                << indent << "description=\"25 Max Beamsize in x\"\n"
+                << "&end\n";
+        statOut << "&column \n"
+                << indent << "name=max_y, \n"
+                << indent << "type=double, \n"
+                << indent << "units=m, \n"
+                << indent << "description=\"26 Max Beamsize in y\"\n"
+                << "&end\n";
+        statOut << "&column \n"
+                << indent << "name=max_s, \n"
+                << indent << "type=double, \n"
+                << indent << "units=m, \n"
+                << indent << "description=\"27 Max Beamsize in s\"\n"
+                << "&end\n";
+        statOut << "&column \n"
+                << indent << "name=xpx, \n"
+                << indent << "type=double, \n"
+                << indent << "units=1, \n"
+                << indent << "description=\"28 Correlation xpx\"\n"
+                << "&end\n";
+        statOut << "&column \n"
+                << indent << "name=ypy, \n"
+                << indent << "type=double, \n"
+                << indent << "units=1, \n"
+                << indent << "description=\"29 Correlation ypyy\"\n"
+                << "&end\n";
+        statOut << "&column \n"
+                << indent << "name=zpz, \n"
+                << indent << "type=double, \n"
+                << indent << "units=1, \n"
+                << indent << "description=\"30 Correlation zpz\"\n"
+                << "&end\n";
+        statOut << "&data \n"
+                << indent << "mode=ascii,\n"
+                << indent << "no_row_counts=1\n"
+                << "&end\n";
+
+        statOut << PACKAGE_NAME << " " << PACKAGE_VERSION << " git rev. " << Util::getGitRevision() << std::endl;
+    }
+
+    for (auto entry: statFileEntries_s) {
+        statOut << entry.second;
+    }
+
+    statOut.close();
+    statFileEntries_s.clear();
+}
\ No newline at end of file
diff --git a/src/Classic/Structure/LossDataSink.h b/src/Classic/Structure/LossDataSink.h
index 15db3e88947810f6a624b8403b05ea92b5b7c737..ef89c6494875b47506ed85e2d8ba243def171ac2 100644
--- a/src/Classic/Structure/LossDataSink.h
+++ b/src/Classic/Structure/LossDataSink.h
@@ -4,6 +4,7 @@
 //////////////////////////////////////////////////////////////
 #include "Utility/IpplInfo.h"
 #include "Algorithms/Vektor.h"
+#include "AbsBeamline/ElementBase.h"
 
 #include <string>
 #include <fstream>
@@ -20,18 +21,28 @@ class LossDataSink {
  public:
     LossDataSink();
 
-    LossDataSink(std::string elem, bool hdf5Save);
+    LossDataSink(std::string elem, bool hdf5Save, ElementBase::ElementType type = ElementBase::ANY);
 
     LossDataSink(const LossDataSink &rsh);
     ~LossDataSink();
 
     bool inH5Mode() { return h5hut_mode_m;}
 
-    void save();
+    void save(unsigned int numSets = 1);
 
-    void addParticle(const Vector_t x, const Vector_t p, const size_t id);
+    void addReferenceParticle(const Vector_t &x,
+                              const Vector_t &p,
+                              double time,
+                              double spos,
+                              long long globalTrackStep);
 
-    void addParticle(const Vector_t x, const Vector_t p, const size_t  id, const double time, const size_t turn);
+    void addParticle(const Vector_t &x, const Vector_t &p, const size_t id);
+
+    void addParticle(const Vector_t &x, const Vector_t &p, const size_t  id, const double time, const size_t turn);
+
+    size_t size() const;
+
+    static void writeStatistics();
 
 private:
 
@@ -67,13 +78,16 @@ private:
 
     void writeHeaderH5();
 
-    void openH5();
+    void openH5(h5_int32_t mode = H5_O_WRONLY);
 
-    void saveH5();
+    void saveH5(unsigned int setIdx);
 
     void saveASCII();
 
-private:
+    void reportOnError(h5_int64_t rc, const char* file, int line);
+
+    void splitSets(unsigned int numSets);
+    void saveStatistics(unsigned int numSets);
 
     // filename without extension
     std::string fn_m;
@@ -91,7 +105,7 @@ private:
 #else
     h5_file_t *H5file_m;
 #endif
-    
+
     /// Current record, or time step, of H5 file.
     h5_int64_t H5call_m;
 
@@ -105,5 +119,28 @@ private:
 
     std::vector<size_t> turn_m;
     std::vector<double> time_m;
+
+    std::vector<Vector_t> RefPartR_m;
+    std::vector<Vector_t> RefPartP_m;
+    std::vector<h5_int64_t> globalTrackStep_m;
+    std::vector<double> refTime_m;
+    std::vector<double> spos_m;
+
+    std::vector<unsigned long> startSet_m;
+
+    ElementBase::ElementType type_m;
+    static std::map<double, std::string> statFileEntries_s;
 };
-#endif
+
+inline
+size_t LossDataSink::size() const {
+    return x_m.size();
+}
+
+inline
+void LossDataSink::reportOnError(h5_int64_t rc, const char* file, int line) {
+    if (rc != H5_SUCCESS)
+        ERRORMSG("H5 rc= " << rc << " in " << file << " @ line " << line << endl);
+}
+
+#endif
\ No newline at end of file
diff --git a/src/Classic/Utilities/CMakeLists.txt b/src/Classic/Utilities/CMakeLists.txt
index dcb986bd1e9b4468f168e45191e925e680e1451e..b3ee229a20ee403cf4b96b382de3138d72f33c6a 100644
--- a/src/Classic/Utilities/CMakeLists.txt
+++ b/src/Classic/Utilities/CMakeLists.txt
@@ -18,15 +18,47 @@ set (_SRCS
   Options.cpp
   OverflowError.cpp
   ParseError.cpp
-  Random.cpp
+  ClassicRandom.cpp
   RingSection.cpp
   SingularMatrixError.cpp
   SizeError.cpp
   SwitcherError.cpp
+  Util.cpp
   )
 
 include_directories (
   ${CMAKE_CURRENT_SOURCE_DIR}
   )
 
-add_sources(${_SRCS})
+ADD_OPAL_SOURCES(${_SRCS})
+
+set (HDRS
+    ArithmeticError.h
+    AttributeError.h
+    ClassicException.h
+    ClassicField.h
+    ClassicRandom.h
+    CLRangeError.h
+    ComplexErrorFun.h
+    ConvergenceError.h
+    DivideError.h
+    DomainError.h
+    EigenvalueError.h
+    FormatError.h
+    Gauss.h
+    GeneralClassicException.h
+    InverseGauss.h
+    LogicalError.h
+    NormalFormError.h
+    Options.h
+    OptionTypes.h
+    OverflowError.h
+    ParseError.h
+    RingSection.h
+    SingularMatrixError.h
+    SizeError.h
+    SwitcherError.h
+    Util.h
+)
+
+install (FILES ${HDRS} DESTINATION "${CMAKE_INSTALL_PREFIX}/include/Utilities")
\ No newline at end of file
diff --git a/src/Classic/Utilities/ClassicField.cpp b/src/Classic/Utilities/ClassicField.cpp
index fc7661f33d389afba408799ba9f88999228d4aff..31f0dd6d1ea7b272bb83f7ce02454abb587b735f 100644
--- a/src/Classic/Utilities/ClassicField.cpp
+++ b/src/Classic/Utilities/ClassicField.cpp
@@ -27,4 +27,4 @@ void ClassicField::setOff() {
         INFOMSG(level3 << element_m->getName() << " gone off" << endl);
         is_on_m = false;
     }
-}
\ No newline at end of file
+}
diff --git a/src/Classic/Utilities/ClassicField.h b/src/Classic/Utilities/ClassicField.h
index ed410b8f1d7baa2d951756502ccee96a86deec59..180dd0256524721db42fe6189b635552d319fea3 100644
--- a/src/Classic/Utilities/ClassicField.h
+++ b/src/Classic/Utilities/ClassicField.h
@@ -5,12 +5,15 @@
 #include <list>
 #include <memory>
 #include "AbsBeamline/Component.h"
+#include "Algorithms/Quaternion.h"
+#include "Algorithms/CoordinateSystemTrafo.h"
 
 class ClassicField {
 public:
     ClassicField(std::shared_ptr<Component>, const double &, const double &);
     ~ClassicField();
     std::shared_ptr<Component> getElement();
+    std::shared_ptr<const Component> getElement() const;
     double getLength() const;
     const double &getStart() const;
     const double &getEnd() const;
@@ -29,6 +32,11 @@ public:
     }
 
 
+    CoordinateSystemTrafo getCoordTransformationTo() const ;
+    void setCoordTransformationTo(const CoordinateSystemTrafo &trafo);
+    bool isPositioned() const;
+    void fixPosition();
+    unsigned int order_m;
 private:
     std::shared_ptr<Component> element_m;
     double start_m;
@@ -42,6 +50,10 @@ inline std::shared_ptr<Component> ClassicField::getElement() {
     return element_m;
 }
 
+inline std::shared_ptr<const Component> ClassicField::getElement() const {
+    return element_m;
+}
+
 inline double ClassicField::getLength() const {
     return end_m - start_m;
 }
@@ -65,4 +77,25 @@ inline void ClassicField::setStart(const double & z) {
 inline void ClassicField::setEnd(const double & z) {
     end_m = z;
 }
-#endif // CLASSIC_FIELD_H
\ No newline at end of file
+
+inline
+CoordinateSystemTrafo ClassicField::getCoordTransformationTo() const {
+    return element_m->getCSTrafoGlobal2Local();
+}
+
+inline
+void ClassicField::setCoordTransformationTo(const CoordinateSystemTrafo &trafo) {
+    element_m->setCSTrafoGlobal2Local(trafo);
+}
+
+inline
+bool ClassicField::isPositioned() const {
+    return element_m->isPositioned();
+}
+
+inline
+void ClassicField::fixPosition() {
+    element_m->fixPosition();
+}
+
+#endif // CLASSIC_FIELD_H
diff --git a/src/Classic/Utilities/Options.cpp b/src/Classic/Utilities/Options.cpp
index 4de875cbd1376f8ccfc10803027c7febc4461adb..95b4ff9d8d869a51e5028429b56b68f1d9ac6fdb 100644
--- a/src/Classic/Utilities/Options.cpp
+++ b/src/Classic/Utilities/Options.cpp
@@ -1,4 +1,5 @@
-#include "Utilities/Random.h"
+#include "OptionTypes.h"
+#include "Utilities/ClassicRandom.h"
 #include <string>
 
 namespace Options {
@@ -19,6 +20,11 @@ namespace Options {
 
     double beamHaloBoundary = 0;
 
+    bool writeBendTrajectories = false;
+
+    OPENMODE openMode = WRITE;
+
+
     // The global program options.
     bool mtrace = false;
     bool verify = false;
@@ -77,14 +83,15 @@ namespace Options {
 
     std::string rngtype = std::string("RANDOM");
 
-    bool schottkyCorrection = false;
+    bool cloTuneOnly = false;
 
-    double schottkyRennormalization = -1;
-
-    bool cloTuneOnly;
-   
     // Governs how often boundp_destroy is called to destroy lost particles
     // Mainly used in the CyclotronTracker as of now -DW
     int boundpDestroyFreq = 10;
 
-}
+    // Using hard edge model for calculation of path length
+    bool idealized = false;
+
+    // opal version of input file
+    int version = 10000;
+}
\ No newline at end of file
diff --git a/src/Classic/Utilities/Options.h b/src/Classic/Utilities/Options.h
index 3e6e2084527e11fdaefec16b039ea93b1246ddb5..4a97f1dec66b60a0cfa7fa65e4e1ce6558618396 100644
--- a/src/Classic/Utilities/Options.h
+++ b/src/Classic/Utilities/Options.h
@@ -24,7 +24,8 @@
 /// The global OPAL option flags.
 //  This namespace contains the global option flags.
 
-#include "Utilities/Random.h"
+#include "OptionTypes.h"
+#include "Utilities/ClassicRandom.h"
 
 namespace Options {
 
@@ -56,6 +57,11 @@ namespace Options {
 
     extern double beamHaloBoundary;
 
+    extern bool writeBendTrajectories;
+
+    extern OPENMODE openMode;
+
+    extern bool idealized;
 
     // CKR: nowhere used
     // // true if in bet mode
@@ -146,15 +152,10 @@ namespace Options {
 
     extern std::string rngtype;
 
-    /// if true
-    extern bool schottkyCorrection;
-
-    ///
-    extern double schottkyRennormalization;
-
     /// Do closed orbit and tune calculation only.
     extern bool cloTuneOnly;
 
+    extern int version;
 }
 
-#endif // OPAL_Options_HH 
+#endif // OPAL_Options_HH
\ No newline at end of file
diff --git a/src/Classic/Utilities/RingSection.cpp b/src/Classic/Utilities/RingSection.cpp
index 5b7320c193238a55a42abb1238b0880132edaf05..fec374195ce1eb0334a43fe9a7ae254cbb649688 100644
--- a/src/Classic/Utilities/RingSection.cpp
+++ b/src/Classic/Utilities/RingSection.cpp
@@ -93,15 +93,15 @@ bool RingSection::isPastEndPlane(const Vector_t& pos) const {
 }
 
 bool RingSection::getFieldValue(const Vector_t& pos,
-                                    const Vector_t& centroid, const double& t,
-                                    Vector_t& E, Vector_t& B) const {
+                                const Vector_t& centroid, const double& t,
+                                Vector_t& E, Vector_t& B) const {
     // std::cerr << startOrientation_m << " " << componentPosition_m << " " << componentOrientation_m(2) << std::endl;
     // transform position into local coordinate system
     Vector_t pos_local = pos-componentPosition_m;
     rotate(pos_local);
     // std::cerr << "RingSection::getFieldValue for " << component_m->getName() << " at " << startPosition_m << "\n    Global: " << pos << " Local: " << pos_local << std::endl;
     rotateToTCoordinates(pos_local);
-    bool outOfBounds = component_m->apply(pos_local, centroid, t, E, B);
+    bool outOfBounds = component_m->apply(pos_local, Vector_t(0.0), t, E, B);
     // std::cerr << "    B: " << B << std::endl;
     if (outOfBounds) {
         return true;
@@ -194,4 +194,4 @@ void RingSection::rotate_back(Vector_t& vector) const {
     const Vector_t temp(vector);
     vector(0) = +cos2_m * temp(0) - sin2_m * temp(1);
     vector(1) = +sin2_m * temp(0) + cos2_m * temp(1);
-}
+}
\ No newline at end of file
diff --git a/src/Distribution/CMakeLists.txt b/src/Distribution/CMakeLists.txt
index cb8497d7cb834ec23fc8c9df1932c84020eef752..30ee008358bd76cd90551aeea174051a4ea8014d 100644
--- a/src/Distribution/CMakeLists.txt
+++ b/src/Distribution/CMakeLists.txt
@@ -1,6 +1,5 @@
 set (_SRCS
   Distribution.cpp
-  halton1d_sequence.cpp
   LaserProfile.cpp
   MagneticField.cpp
   )
@@ -9,4 +8,20 @@ include_directories (
   ${CMAKE_CURRENT_SOURCE_DIR}
 )
 
-add_sources(${_SRCS})
+add_opal_sources(${_SRCS})
+
+set (HDRS
+    ClosedOrbitFinder.h
+    Distribution.h
+    error.h
+    Harmonics.h
+    LaserProfile.h
+    MagneticField.h
+    MapGenerator.h
+    matrix_vector_operation.h
+    physical_error.h
+    rdm.h
+    SigmaGenerator.h
+)
+
+install (FILES ${HDRS} DESTINATION "${CMAKE_INSTALL_PREFIX}/include/Distribution")
\ No newline at end of file
diff --git a/src/Distribution/Distribution.cpp b/src/Distribution/Distribution.cpp
index fb5624899fc23ebab7253709b3681521839a8be9..491453b70bd06ba87a123f303bb1fc55536860d6 100644
--- a/src/Distribution/Distribution.cpp
+++ b/src/Distribution/Distribution.cpp
@@ -26,8 +26,6 @@
 #include "AbstractObjects/Expressions.h"
 #include "Attributes/Attributes.h"
 #include "Utilities/Options.h"
-#include "Utilities/OpalException.h"
-#include "halton1d_sequence.hh"
 #include "AbstractObjects/OpalData.h"
 #include "Algorithms/PartBunch.h"
 #include "Algorithms/PartBins.h"
@@ -41,6 +39,7 @@
 #include "AbstractObjects/BeamSequence.h"
 #include "Structure/H5PartWrapper.h"
 #include "Structure/H5PartWrapperForPC.h"
+#include "Utilities/Util.h"
 
 #include <gsl/gsl_cdf.h>
 #include <gsl/gsl_randist.h>
@@ -179,7 +178,7 @@ namespace AttributesT
         MAXSTEPSSI,
         ORDERMAPS,
         E2,
-	RGUESS,
+        RGUESS,
         ID1,                       // special particle that the user can set
         ID2,                       // special particle that the user can set
         SIZE
@@ -230,7 +229,7 @@ Distribution::Distribution():
     numberOfSampleBins_m(0),
     energyBins_m(NULL),
     energyBinHist_m(NULL),
-    randGenEmit_m(NULL),
+    randGen_m(NULL),
     pTotThermal_m(0.0),
     pmean_m(0.0),
     cathodeWorkFunc_m(0.0),
@@ -238,6 +237,8 @@ Distribution::Distribution():
     cathodeFermiEnergy_m(0.0),
     cathodeTemp_m(0.0),
     emitEnergyUpperLimit_m(0.0),
+    totalNumberParticles_m(0),
+    totalNumberEmittedParticles_m(0),
     inputMoUnits_m(InputMomentumUnitsT::NONE),
     sigmaTRise_m(0.0),
     sigmaTFall_m(0.0),
@@ -270,7 +271,7 @@ Distribution::Distribution():
     bega_m(0.0),
     M_m(0.0)
 {
-    SetAttributes();
+    setAttributes();
 
     Distribution *defaultDistribution = clone("UNNAMED_Distribution");
     defaultDistribution->builtin = true;
@@ -281,7 +282,11 @@ Distribution::Distribution():
         delete defaultDistribution;
     }
 
-    SetFieldEmissionParameters();
+    setFieldEmissionParameters();
+
+    gsl_rng_env_setup();
+    randGen_m = gsl_rng_alloc(gsl_rng_default);
+    gsl_rng_set(randGen_m, Options::seed);
 }
 /**
  *
@@ -309,7 +314,7 @@ Distribution::Distribution(const std::string &name, Distribution *parent):
     numberOfSampleBins_m(parent->numberOfSampleBins_m),
     energyBins_m(NULL),
     energyBinHist_m(NULL),
-    randGenEmit_m(parent->randGenEmit_m),
+    randGen_m(NULL),
     pTotThermal_m(parent->pTotThermal_m),
     pmean_m(parent->pmean_m),
     cathodeWorkFunc_m(parent->cathodeWorkFunc_m),
@@ -317,6 +322,8 @@ Distribution::Distribution(const std::string &name, Distribution *parent):
     cathodeFermiEnergy_m(parent->cathodeFermiEnergy_m),
     cathodeTemp_m(parent->cathodeTemp_m),
     emitEnergyUpperLimit_m(parent->emitEnergyUpperLimit_m),
+    totalNumberParticles_m(parent->totalNumberParticles_m),
+    totalNumberEmittedParticles_m(parent->totalNumberEmittedParticles_m),
     xDist_m(parent->xDist_m),
     pxDist_m(parent->pxDist_m),
     yDist_m(parent->yDist_m),
@@ -368,6 +375,9 @@ Distribution::Distribution(const std::string &name, Distribution *parent):
     bega_m(parent->bega_m),
     M_m(parent->M_m)
 {
+    gsl_rng_env_setup();
+    randGen_m = gsl_rng_alloc(gsl_rng_default);
+    gsl_rng_set(randGen_m, Options::seed);
 }
 
 Distribution::~Distribution() {
@@ -385,9 +395,9 @@ Distribution::~Distribution() {
         energyBinHist_m = NULL;
     }
 
-    if (randGenEmit_m != NULL) {
-        gsl_rng_free(randGenEmit_m);
-        randGenEmit_m = NULL;
+    if (randGen_m != NULL) {
+        gsl_rng_free(randGen_m);
+        randGen_m = NULL;
     }
 
     if(laserProfile_m) {
@@ -414,7 +424,7 @@ Distribution::~Distribution() {
  * @param
  * @param
  */
-void Distribution::WriteToFile() {
+void Distribution::writeToFile() {
     /*
       if(Ippl::getNodes() == 1) {
       if(os_m.is_open()) {
@@ -448,32 +458,32 @@ void Distribution::execute() {
 void Distribution::update() {
 }
 
-void Distribution::Create(size_t &numberOfParticles, double massIneV) {
+void Distribution::create(size_t &numberOfParticles, double massIneV) {
 
-    SetFieldEmissionParameters();
+    setFieldEmissionParameters();
 
     switch (distrTypeT_m) {
 
     case DistrTypeT::MATCHEDGAUSS:
-        CreateMatchedGaussDistribution(numberOfParticles, massIneV);
+        createMatchedGaussDistribution(numberOfParticles, massIneV);
         break;
     case DistrTypeT::FROMFILE:
-        CreateDistributionFromFile(numberOfParticles, massIneV);
+        createDistributionFromFile(numberOfParticles, massIneV);
         break;
     case DistrTypeT::GAUSS:
-        CreateDistributionGauss(numberOfParticles, massIneV);
+        createDistributionGauss(numberOfParticles, massIneV);
         break;
     case DistrTypeT::BINOMIAL:
-        CreateDistributionBinomial(numberOfParticles, massIneV);
+        createDistributionBinomial(numberOfParticles, massIneV);
         break;
     case DistrTypeT::FLATTOP:
-        CreateDistributionFlattop(numberOfParticles, massIneV);
+        createDistributionFlattop(numberOfParticles, massIneV);
         break;
     case DistrTypeT::GUNGAUSSFLATTOPTH:
-        CreateDistributionFlattop(numberOfParticles, massIneV);
+        createDistributionFlattop(numberOfParticles, massIneV);
         break;
     case DistrTypeT::ASTRAFLATTOPTH:
-        CreateDistributionFlattop(numberOfParticles, massIneV);
+        createDistributionFlattop(numberOfParticles, massIneV);
         break;
     default:
         INFOMSG("Distribution unknown." << endl;);
@@ -481,8 +491,13 @@ void Distribution::Create(size_t &numberOfParticles, double massIneV) {
     }
 
     if (emitting_m) {
+
+        std::string model = Util::toUpper(Attributes::getString(itsAttr[AttributesT::EMISSIONMODEL]));
         unsigned int numAdditionalRNsPerParticle = 0;
-        if (emissionModel_m == EmissionModelT::ASTRA) {
+        if (model == "ASTRA" ||
+            distrTypeT_m == DistrTypeT::ASTRAFLATTOPTH ||
+            distrTypeT_m == DistrTypeT::GUNGAUSSFLATTOPTH) {
+
             numAdditionalRNsPerParticle = 2;
         }
 
@@ -502,29 +517,30 @@ void Distribution::Create(size_t &numberOfParticles, double massIneV) {
             if (Ippl::myNode() == saveProcessor) {
                 std::vector<double> rns;
                 for (unsigned int i = 0; i < numAdditionalRNsPerParticle; ++ i) {
-                    double x = gsl_rng_uniform(randGenEmit_m);
+                    double x = gsl_rng_uniform(randGen_m);
                     rns.push_back(x);
                 }
                 additionalRNs_m.push_back(rns);
             } else {
                 for (unsigned int i = 0; i < numAdditionalRNsPerParticle; ++ i) {
-                    gsl_rng_uniform(randGenEmit_m);
+                    gsl_rng_uniform(randGen_m);
                 }
             }
         }
     }
 
-    // AAA Scale and shift coordinates according to distribution input.
-    ScaleDistCoordinates();
+    // Scale coordinates according to distribution input.
+    scaleDistCoordinates();
+    Options::seed = gsl_rng_uniform_int(randGen_m, gsl_rng_max(randGen_m));
 }
 
-void  Distribution::CreatePriPart(PartBunch *beam, BoundaryGeometry &bg) {
+void  Distribution::createPriPart(PartBunch *beam, BoundaryGeometry &bg) {
 
     if(Options::ppdebug) {  // This is Parallel Plate Benchmark.
         int pc = 0;
         size_t lowMark = beam->getLocalNum();
-        double vw = this->GetVw();
-        double vt = this->GetvVThermal();
+        double vw = this->getVw();
+        double vt = this->getvVThermal();
         double f_max = vw / vt * exp(-0.5);
         double test_a = vt / vw;
         double test_asq = test_a * test_a;
@@ -565,7 +581,6 @@ void  Distribution::CreatePriPart(PartBunch *beam, BoundaryGeometry &bg) {
                         beam->PType[lowMark + count] = ParticleType::REGULAR;
                         beam->TriID[lowMark + count] = 0;
                         beam->Q[lowMark + count] = beam->getChargePerParticle();
-                        beam->LastSection[lowMark + count] = 0;
                         beam->Ef[lowMark + count] = Vector_t(0.0);
                         beam->Bf[lowMark + count] = Vector_t(0.0);
                         beam->dt[lowMark + count] = beam->getdT();
@@ -607,7 +622,6 @@ void  Distribution::CreatePriPart(PartBunch *beam, BoundaryGeometry &bg) {
                         beam->PType[lowMark + count] = ParticleType::REGULAR;
                         beam->TriID[lowMark + count] = 0;
                         beam->Q[lowMark + count] = beam->getChargePerParticle();
-                        beam->LastSection[lowMark + count] = 0;
                         beam->Ef[lowMark + count] = Vector_t(0.0);
                         beam->Bf[lowMark + count] = Vector_t(0.0);
                         beam->dt[lowMark + count] = beam->getdT();
@@ -629,7 +643,7 @@ void  Distribution::CreatePriPart(PartBunch *beam, BoundaryGeometry &bg) {
     *gmsg << *beam << endl;
 }
 
-void Distribution::DoRestartOpalT(PartBunch &beam, size_t Np, int restartStep, H5PartWrapper *dataSource) {
+void Distribution::doRestartOpalT(PartBunch &beam, size_t Np, int restartStep, H5PartWrapper *dataSource) {
 
     IpplTimings::startTimer(beam.distrReload_m);
 
@@ -663,7 +677,7 @@ void Distribution::DoRestartOpalT(PartBunch &beam, size_t Np, int restartStep, H
           << "time of restart= " << actualT << "; phishift= " << OpalData::getInstance()->getGlobalPhaseShift() << endl;
 }
 
-void Distribution::DoRestartOpalCycl(PartBunch &beam,
+void Distribution::doRestartOpalCycl(PartBunch &beam,
                                      size_t Np,
                                      int restartStep,
                                      const int specifiedNumBunch,
@@ -711,7 +725,8 @@ void Distribution::DoRestartOpalCycl(PartBunch &beam,
         INFOMSG("Restart from hdf5 file generated by OPAL-cycl" << endl);
         if(specifiedNumBunch > 1) {
             // the allowed maximal bin number is set to 1000
-            beam.setPBins(new PartBinsCyc(1000, beam.getNumBunch()));
+            energyBins_m = new PartBinsCyc(1000, beam.getNumBunch());
+            beam.setPBins(energyBins_m);
         }
 
     } else {
@@ -742,7 +757,7 @@ void Distribution::DoRestartOpalCycl(PartBunch &beam,
     IpplTimings::stopTimer(beam.distrReload_m);
 }
 
-void Distribution::DoRestartOpalE(EnvelopeBunch &beam, size_t Np, int restartStep,
+void Distribution::doRestartOpalE(EnvelopeBunch &beam, size_t Np, int restartStep,
                                   H5PartWrapper *dataSource) {
     IpplTimings::startTimer(beam.distrReload_m);
     int N = dataSource->getNumParticles();
@@ -770,12 +785,12 @@ Distribution *Distribution::find(const std::string &name) {
     return dist;
 }
 
-double Distribution::GetTEmission() {
+double Distribution::getTEmission() {
     if(tEmission_m > 0.0) {
         return tEmission_m;
     }
 
-    distT_m = Attributes::getString(itsAttr[AttributesT::DISTRIBUTION]);
+    distT_m = Util::toUpper(Attributes::getString(itsAttr[AttributesT::DISTRIBUTION]));
     if(distT_m == "GAUSS")
         distrTypeT_m = DistrTypeT::GAUSS;
     else if(distT_m == "GUNGAUSSFLATTOPTH")
@@ -822,37 +837,37 @@ double Distribution::GetTEmission() {
     return tEmission_m;
 }
 
-double Distribution::GetEkin() const {return Attributes::getReal(itsAttr[AttributesT::EKIN]);}
-double Distribution::GetLaserEnergy() const {return Attributes::getReal(itsAttr[AttributesT::ELASER]);}
-double Distribution::GetWorkFunctionRf() const {return Attributes::getReal(itsAttr[AttributesT::W]);}
-
-size_t Distribution::GetNumberOfDarkCurrentParticles() { return (size_t) Attributes::getReal(itsAttr[AttributesT::NPDARKCUR]);}
-double Distribution::GetDarkCurrentParticlesInwardMargin() { return Attributes::getReal(itsAttr[AttributesT::INWARDMARGIN]);}
-double Distribution::GetEInitThreshold() { return Attributes::getReal(itsAttr[AttributesT::EINITHR]);}
-double Distribution::GetWorkFunction() { return Attributes::getReal(itsAttr[AttributesT::FNPHIW]); }
-double Distribution::GetFieldEnhancement() { return Attributes::getReal(itsAttr[AttributesT::FNBETA]); }
-size_t Distribution::GetMaxFNemissionPartPerTri() { return (size_t) Attributes::getReal(itsAttr[AttributesT::FNMAXEMI]);}
-double Distribution::GetFieldFNThreshold() { return Attributes::getReal(itsAttr[AttributesT::FNFIELDTHR]);}
-double Distribution::GetFNParameterA() { return Attributes::getReal(itsAttr[AttributesT::FNA]);}
-double Distribution::GetFNParameterB() { return Attributes::getReal(itsAttr[AttributesT::FNB]);}
-double Distribution::GetFNParameterY() { return Attributes::getReal(itsAttr[AttributesT::FNY]);}
-double Distribution::GetFNParameterVYZero() { return Attributes::getReal(itsAttr[AttributesT::FNVYZERO]);}
-double Distribution::GetFNParameterVYSecond() { return Attributes::getReal(itsAttr[AttributesT::FNVYSECOND]);}
-int    Distribution::GetSecondaryEmissionFlag() { return Attributes::getReal(itsAttr[AttributesT::SECONDARYFLAG]);}
-bool   Distribution::GetEmissionMode() { return Attributes::getBool(itsAttr[AttributesT::NEMISSIONMODE]);}
-
-std::string Distribution::GetTypeofDistribution() { return (std::string) Attributes::getString(itsAttr[AttributesT::DISTRIBUTION]);}
-
-double Distribution::GetvSeyZero() {return Attributes::getReal(itsAttr[AttributesT::VSEYZERO]);}// return sey_0 in Vaughan's model
-double Distribution::GetvEZero() {return Attributes::getReal(itsAttr[AttributesT::VEZERO]);}// return the energy related to sey_0 in Vaughan's model
-double Distribution::GetvSeyMax() {return Attributes::getReal(itsAttr[AttributesT::VSEYMAX]);}// return sey max in Vaughan's model
-double Distribution::GetvEmax() {return Attributes::getReal(itsAttr[AttributesT::VEMAX]);}// return Emax in Vaughan's model
-double Distribution::GetvKenergy() {return Attributes::getReal(itsAttr[AttributesT::VKENERGY]);}// return fitting parameter denotes the roughness of surface for impact energy in Vaughan's model
-double Distribution::GetvKtheta() {return Attributes::getReal(itsAttr[AttributesT::VKTHETA]);}// return fitting parameter denotes the roughness of surface for impact angle in Vaughan's model
-double Distribution::GetvVThermal() {return Attributes::getReal(itsAttr[AttributesT::VVTHERMAL]);}// thermal velocity of Maxwellian distribution of secondaries in Vaughan's model
-double Distribution::GetVw() {return Attributes::getReal(itsAttr[AttributesT::VW]);}// velocity scalar for parallel plate benchmark;
-
-int Distribution::GetSurfMaterial() {return (int)Attributes::getReal(itsAttr[AttributesT::SURFMATERIAL]);}// Surface material number for Furman-Pivi's Model;
+double Distribution::getEkin() const {return Attributes::getReal(itsAttr[AttributesT::EKIN]);}
+double Distribution::getLaserEnergy() const {return Attributes::getReal(itsAttr[AttributesT::ELASER]);}
+double Distribution::getWorkFunctionRf() const {return Attributes::getReal(itsAttr[AttributesT::W]);}
+
+size_t Distribution::getNumberOfDarkCurrentParticles() { return (size_t) Attributes::getReal(itsAttr[AttributesT::NPDARKCUR]);}
+double Distribution::getDarkCurrentParticlesInwardMargin() { return Attributes::getReal(itsAttr[AttributesT::INWARDMARGIN]);}
+double Distribution::getEInitThreshold() { return Attributes::getReal(itsAttr[AttributesT::EINITHR]);}
+double Distribution::getWorkFunction() { return Attributes::getReal(itsAttr[AttributesT::FNPHIW]); }
+double Distribution::getFieldEnhancement() { return Attributes::getReal(itsAttr[AttributesT::FNBETA]); }
+size_t Distribution::getMaxFNemissionPartPerTri() { return (size_t) Attributes::getReal(itsAttr[AttributesT::FNMAXEMI]);}
+double Distribution::getFieldFNThreshold() { return Attributes::getReal(itsAttr[AttributesT::FNFIELDTHR]);}
+double Distribution::getFNParameterA() { return Attributes::getReal(itsAttr[AttributesT::FNA]);}
+double Distribution::getFNParameterB() { return Attributes::getReal(itsAttr[AttributesT::FNB]);}
+double Distribution::getFNParameterY() { return Attributes::getReal(itsAttr[AttributesT::FNY]);}
+double Distribution::getFNParameterVYZero() { return Attributes::getReal(itsAttr[AttributesT::FNVYZERO]);}
+double Distribution::getFNParameterVYSecond() { return Attributes::getReal(itsAttr[AttributesT::FNVYSECOND]);}
+int    Distribution::getSecondaryEmissionFlag() { return Attributes::getReal(itsAttr[AttributesT::SECONDARYFLAG]);}
+bool   Distribution::getEmissionMode() { return Attributes::getBool(itsAttr[AttributesT::NEMISSIONMODE]);}
+
+std::string Distribution::getTypeofDistribution() { return (std::string) Attributes::getString(itsAttr[AttributesT::DISTRIBUTION]);}
+
+double Distribution::getvSeyZero() {return Attributes::getReal(itsAttr[AttributesT::VSEYZERO]);}// return sey_0 in Vaughan's model
+double Distribution::getvEZero() {return Attributes::getReal(itsAttr[AttributesT::VEZERO]);}// return the energy related to sey_0 in Vaughan's model
+double Distribution::getvSeyMax() {return Attributes::getReal(itsAttr[AttributesT::VSEYMAX]);}// return sey max in Vaughan's model
+double Distribution::getvEmax() {return Attributes::getReal(itsAttr[AttributesT::VEMAX]);}// return Emax in Vaughan's model
+double Distribution::getvKenergy() {return Attributes::getReal(itsAttr[AttributesT::VKENERGY]);}// return fitting parameter denotes the roughness of surface for impact energy in Vaughan's model
+double Distribution::getvKtheta() {return Attributes::getReal(itsAttr[AttributesT::VKTHETA]);}// return fitting parameter denotes the roughness of surface for impact angle in Vaughan's model
+double Distribution::getvVThermal() {return Attributes::getReal(itsAttr[AttributesT::VVTHERMAL]);}// thermal velocity of Maxwellian distribution of secondaries in Vaughan's model
+double Distribution::getVw() {return Attributes::getReal(itsAttr[AttributesT::VW]);}// velocity scalar for parallel plate benchmark;
+
+int Distribution::getSurfMaterial() {return (int)Attributes::getReal(itsAttr[AttributesT::SURFMATERIAL]);}// Surface material number for Furman-Pivi's Model;
 
 Inform &Distribution::printInfo(Inform &os) const {
 
@@ -866,16 +881,16 @@ Inform &Distribution::printInfo(Inform &os) const {
                << "-----------------" << endl;
 
         if (particlesPerDist_m.empty())
-            PrintDist(os, 0);
+            printDist(os, 0);
         else
-            PrintDist(os, particlesPerDist_m.at(0));
+            printDist(os, particlesPerDist_m.at(0));
 
         size_t distCount = 1;
         for (unsigned distIndex = 0; distIndex < addedDistributions_m.size(); distIndex++) {
             os << "* " << endl;
             os << "* Added Distribution #" << distCount << endl;
             os << "* ----------------------" << endl;
-            addedDistributions_m.at(distIndex)->PrintDist(os, particlesPerDist_m.at(distCount));
+            addedDistributions_m.at(distIndex)->printDist(os, particlesPerDist_m.at(distCount));
             distCount++;
         }
 
@@ -884,7 +899,7 @@ Inform &Distribution::printInfo(Inform &os) const {
             os << "* Number of energy bins    = " << numberOfEnergyBins_m << endl;
 
             //            if (numberOfEnergyBins_m > 1)
-            //    PrintEnergyBins(os);
+            //    printEnergyBins(os);
         }
 
         if (emitting_m) {
@@ -893,7 +908,7 @@ Inform &Distribution::printInfo(Inform &os) const {
             os << "* Time per bin             = " << tEmission_m / numberOfEnergyBins_m << " [sec]" << endl;
             os << "* Delta t during emission  = " << tBin_m / numberOfSampleBins_m << " [sec]" << endl;
             os << "* " << endl;
-            PrintEmissionModel(os);
+            printEmissionModel(os);
             os << "* " << endl;
         } else
             os << "* Distribution is injected." << endl;
@@ -904,13 +919,13 @@ Inform &Distribution::printInfo(Inform &os) const {
     return os;
 }
 
-const PartData &Distribution::GetReference() const {
+const PartData &Distribution::getReference() const {
     // Cast away const, to allow logically constant Distribution to update.
     const_cast<Distribution *>(this)->update();
     return particleRefData_m;
 }
 
-void Distribution::AddDistributions() {
+void Distribution::addDistributions() {
     /*
      * Move particle coordinates from added distributions to main distribution.
      */
@@ -920,69 +935,69 @@ void Distribution::AddDistributions() {
          addedDistIt != addedDistributions_m.end(); addedDistIt++) {
 
         std::vector<double>::iterator distIt;
-        for (distIt = (*addedDistIt)->GetXDist().begin();
-             distIt != (*addedDistIt)->GetXDist().end();
+        for (distIt = (*addedDistIt)->getXDist().begin();
+             distIt != (*addedDistIt)->getXDist().end();
              distIt++) {
             xDist_m.push_back(*distIt);
         }
-        (*addedDistIt)->EraseXDist();
+        (*addedDistIt)->eraseXDist();
 
-        for (distIt = (*addedDistIt)->GetBGxDist().begin();
-             distIt != (*addedDistIt)->GetBGxDist().end();
+        for (distIt = (*addedDistIt)->getBGxDist().begin();
+             distIt != (*addedDistIt)->getBGxDist().end();
              distIt++) {
             pxDist_m.push_back(*distIt);
         }
-        (*addedDistIt)->EraseBGxDist();
+        (*addedDistIt)->eraseBGxDist();
 
-        for (distIt = (*addedDistIt)->GetYDist().begin();
-             distIt != (*addedDistIt)->GetYDist().end();
+        for (distIt = (*addedDistIt)->getYDist().begin();
+             distIt != (*addedDistIt)->getYDist().end();
              distIt++) {
             yDist_m.push_back(*distIt);
         }
-        (*addedDistIt)->EraseYDist();
+        (*addedDistIt)->eraseYDist();
 
-        for (distIt = (*addedDistIt)->GetBGyDist().begin();
-             distIt != (*addedDistIt)->GetBGyDist().end();
+        for (distIt = (*addedDistIt)->getBGyDist().begin();
+             distIt != (*addedDistIt)->getBGyDist().end();
              distIt++) {
             pyDist_m.push_back(*distIt);
         }
-        (*addedDistIt)->EraseBGyDist();
+        (*addedDistIt)->eraseBGyDist();
 
-        for (distIt = (*addedDistIt)->GetTOrZDist().begin();
-             distIt != (*addedDistIt)->GetTOrZDist().end();
+        for (distIt = (*addedDistIt)->getTOrZDist().begin();
+             distIt != (*addedDistIt)->getTOrZDist().end();
              distIt++) {
             tOrZDist_m.push_back(*distIt);
         }
-        (*addedDistIt)->EraseTOrZDist();
+        (*addedDistIt)->eraseTOrZDist();
 
-        for (distIt = (*addedDistIt)->GetBGzDist().begin();
-             distIt != (*addedDistIt)->GetBGzDist().end();
+        for (distIt = (*addedDistIt)->getBGzDist().begin();
+             distIt != (*addedDistIt)->getBGzDist().end();
              distIt++) {
             pzDist_m.push_back(*distIt);
         }
-        (*addedDistIt)->EraseBGzDist();
+        (*addedDistIt)->eraseBGzDist();
     }
 }
 
-void Distribution::ApplyEmissionModel(double eZ, double &px, double &py, double &pz, const std::vector<double> &additionalRNs) {
+void Distribution::applyEmissionModel(double eZ, double &px, double &py, double &pz, const std::vector<double> &additionalRNs) {
 
     switch (emissionModel_m) {
 
     case EmissionModelT::NONE:
-        ApplyEmissModelNone(pz);
+        applyEmissModelNone(pz);
         break;
     case EmissionModelT::ASTRA:
-        ApplyEmissModelAstra(px, py, pz, additionalRNs);
+        applyEmissModelAstra(px, py, pz, additionalRNs);
         break;
     case EmissionModelT::NONEQUIL:
-        ApplyEmissModelNonEquil(eZ, px, py, pz);
+        applyEmissModelNonEquil(eZ, px, py, pz);
         break;
     default:
         break;
     }
 }
 
-void Distribution::ApplyEmissModelAstra(double &px, double &py, double &pz, const std::vector<double> &additionalRNs) {
+void Distribution::applyEmissModelAstra(double &px, double &py, double &pz, const std::vector<double> &additionalRNs) {
 
     double phi = 2.0 * acos(sqrt(additionalRNs[0]));
     double theta = 2.0 * Physics::pi * additionalRNs[1];
@@ -993,11 +1008,11 @@ void Distribution::ApplyEmissModelAstra(double &px, double &py, double &pz, cons
 
 }
 
-void Distribution::ApplyEmissModelNone(double &pz) {
+void Distribution::applyEmissModelNone(double &pz) {
     pz += pTotThermal_m;
 }
 
-void Distribution::ApplyEmissModelNonEquil(double eZ,
+void Distribution::applyEmissModelNonEquil(double eZ,
                                            double &bgx,
                                            double &bgy,
                                            double &bgz) {
@@ -1011,8 +1026,8 @@ void Distribution::ApplyEmissModelNonEquil(double eZ,
     double energy = 0.0;
     bool allow = false;
     while (!allow) {
-        energy = lowEnergyLimit + (gsl_rng_uniform(randGenEmit_m)*emitEnergyUpperLimit_m);
-        double randFuncValue = gsl_rng_uniform(randGenEmit_m);
+        energy = lowEnergyLimit + (gsl_rng_uniform(randGen_m)*emitEnergyUpperLimit_m);
+        double randFuncValue = gsl_rng_uniform(randGen_m);
         double funcValue = (1.0
                             - 1.0
                             / (1.0
@@ -1032,9 +1047,9 @@ void Distribution::ApplyEmissModelNonEquil(double eZ,
 
     double thetaInMax = acos(sqrt((cathodeFermiEnergy_m + phiEffective)
                                   / (energy + laserEnergy_m)));
-    double thetaIn = gsl_rng_uniform(randGenEmit_m)*thetaInMax;
+    double thetaIn = gsl_rng_uniform(randGen_m)*thetaInMax;
     double sinThetaOut = sin(thetaIn) * sqrt(energyInternal / energyExternal);
-    double phi = Physics::two_pi * gsl_rng_uniform(randGenEmit_m);
+    double phi = Physics::two_pi * gsl_rng_uniform(randGen_m);
 
     // Compute emission momenta.
     double betaGammaExternal
@@ -1046,22 +1061,22 @@ void Distribution::ApplyEmissModelNonEquil(double eZ,
 
 }
 
-void Distribution::CalcPartPerDist(size_t numberOfParticles) {
+void Distribution::calcPartPerDist(size_t numberOfParticles) {
 
     typedef std::vector<Distribution *>::iterator iterator;
 
     if (numberOfDistributions_m == 1)
         particlesPerDist_m.push_back(numberOfParticles);
     else {
-        double totalWeight = GetWeight();
+        double totalWeight = getWeight();
         for (iterator it = addedDistributions_m.begin(); it != addedDistributions_m.end(); it++) {
-            totalWeight += (*it)->GetWeight();
+            totalWeight += (*it)->getWeight();
         }
 
         particlesPerDist_m.push_back(0);
         size_t numberOfCommittedPart = 0;
         for (iterator it = addedDistributions_m.begin(); it != addedDistributions_m.end(); it++) {
-            size_t particlesCurrentDist = numberOfParticles * (*it)->GetWeight() / totalWeight;
+            size_t particlesCurrentDist = numberOfParticles * (*it)->getWeight() / totalWeight;
             particlesPerDist_m.push_back(particlesCurrentDist);
             numberOfCommittedPart += particlesCurrentDist;
         }
@@ -1073,7 +1088,7 @@ void Distribution::CalcPartPerDist(size_t numberOfParticles) {
 
 }
 
-void Distribution::CheckEmissionParameters() {
+void Distribution::checkEmissionParameters() {
 
     // There must be at least on energy bin for an emitted beam.
     numberOfEnergyBins_m
@@ -1098,7 +1113,7 @@ void Distribution::CheckEmissionParameters() {
 
 }
 
-void Distribution::CheckIfEmitted() {
+void Distribution::checkIfEmitted() {
 
     emitting_m = Attributes::getBool(itsAttr[AttributesT::EMITTED]);
 
@@ -1115,11 +1130,11 @@ void Distribution::CheckIfEmitted() {
     }
 }
 
-void Distribution::CheckParticleNumber(size_t &numberOfParticles) {
+void Distribution::checkParticleNumber(size_t &numberOfParticles) {
 
     size_t numberOfDistParticles = tOrZDist_m.size();
     reduce(numberOfDistParticles, numberOfDistParticles, OpAddAssign());
-    
+
     if (numberOfDistParticles != numberOfParticles) {
         *gmsg << "\n--------------------------------------------------" << endl
               << "Error!! The number of particles in the initial" << endl
@@ -1134,18 +1149,18 @@ void Distribution::CheckParticleNumber(size_t &numberOfParticles) {
               << "(" << numberOfDistParticles << ") "
               << "will take precedence." << endl
               << "---------------------------------------------------\n" << endl;
-        throw OpalException("Distribution::CheckParticleNumber",
-                            "Number of macro particles and NPART on BEAM are not equal");    
+        throw OpalException("Distribution::checkParticleNumber",
+                            "Number of macro particles and NPART on BEAM are not equal");
     }
     numberOfParticles = numberOfDistParticles;
 }
 
-void Distribution::ChooseInputMomentumUnits(InputMomentumUnitsT::InputMomentumUnitsT inputMoUnits) {
+void Distribution::chooseInputMomentumUnits(InputMomentumUnitsT::InputMomentumUnitsT inputMoUnits) {
 
     /*
      * Toggle what units to use for inputing momentum.
      */
-    std::string inputUnits = Attributes::getString(itsAttr[AttributesT::INPUTMOUNITS]);
+    std::string inputUnits = Util::toUpper(Attributes::getString(itsAttr[AttributesT::INPUTMOUNITS]));
     if (inputUnits == "NONE")
         inputMoUnits_m = InputMomentumUnitsT::NONE;
     else if (inputUnits == "EV")
@@ -1155,44 +1170,44 @@ void Distribution::ChooseInputMomentumUnits(InputMomentumUnitsT::InputMomentumUn
 
 }
 
-double Distribution::ConvertBetaGammaToeV(double valueInBetaGamma, double massIneV) {
+double Distribution::convertBetaGammaToeV(double valueInBetaGamma, double massIneV) {
     if (valueInBetaGamma < 0)
         return -1.0 * (sqrt(pow(valueInBetaGamma, 2.0) + 1.0) - 1.0) * massIneV;
     else
         return (sqrt(pow(valueInBetaGamma, 2.0) + 1.0) - 1.0) * massIneV;
 }
 
-double Distribution::ConverteVToBetaGamma(double valueIneV, double massIneV) {
+double Distribution::converteVToBetaGamma(double valueIneV, double massIneV) {
     if (valueIneV < 0)
         return -1.0 * sqrt( pow( -1.0 * valueIneV / massIneV + 1.0, 2.0) - 1.0);
     else
         return sqrt( pow( valueIneV / massIneV + 1.0, 2.0) - 1.0);
 }
 
-double Distribution::ConvertMeVPerCToBetaGamma(double valueInMeVPerC, double massIneV) {
+double Distribution::convertMeVPerCToBetaGamma(double valueInMeVPerC, double massIneV) {
     return sqrt(pow(valueInMeVPerC * 1.0e6 * Physics::c / massIneV + 1.0, 2.0) - 1.0);
 }
 
-void Distribution::CreateDistributionBinomial(size_t numberOfParticles, double massIneV) {
+void Distribution::createDistributionBinomial(size_t numberOfParticles, double massIneV) {
 
-    SetDistParametersBinomial(massIneV);
-    GenerateBinomial(numberOfParticles);
+    setDistParametersBinomial(massIneV);
+    generateBinomial(numberOfParticles);
 }
 
-void Distribution::CreateDistributionFlattop(size_t numberOfParticles, double massIneV) {
+void Distribution::createDistributionFlattop(size_t numberOfParticles, double massIneV) {
 
-    SetDistParametersFlattop(massIneV);
+    setDistParametersFlattop(massIneV);
 
     if (emitting_m) {
         if (laserProfile_m == NULL)
-            GenerateFlattopT(numberOfParticles);
+            generateFlattopT(numberOfParticles);
         else
-            GenerateFlattopLaserProfile(numberOfParticles);
+            generateFlattopLaserProfile(numberOfParticles);
     } else
-        GenerateFlattopZ(numberOfParticles);
+        generateFlattopZ(numberOfParticles);
 }
 
-void Distribution::CreateDistributionFromFile(size_t numberOfParticles, double massIneV) {
+void Distribution::createDistributionFromFile(size_t numberOfParticles, double massIneV) {
 
     *gmsg << level3 << "\n"
           << "------------------------------------------------------------------------------------\n";
@@ -1208,13 +1223,17 @@ void Distribution::CreateDistributionFromFile(size_t numberOfParticles, double m
         std::string fileName = Attributes::getString(itsAttr[AttributesT::FNAME]);
         inputFile.open(fileName.c_str());
         if (inputFile.fail())
-            throw OpalException("Distribution::Create()",
+            throw OpalException("Distribution::create()",
                                 "Open file operation failed, please check if \""
                                 + fileName
                                 + "\" really exists.");
         else {
             int tempInt = 0;
             inputFile >> tempInt;
+            if (tempInt <= 0) {
+                throw OpalException("Distribution::createDistributionFromFile",
+                                    "The file '" + fileName + "' does not seem to be an ASCII file containing a distribution.");
+            }
             numberOfParticlesRead = static_cast<size_t>(tempInt);
         }
     }
@@ -1226,242 +1245,304 @@ void Distribution::CreateDistributionFromFile(size_t numberOfParticles, double m
      */
     int saveProcessor = -1;
 
-    for (size_t particleIndex = 0; particleIndex < numberOfParticlesRead; particleIndex++) {
+    pmean_m = 0.0;
+
+    size_t numPartsToSend = 0;
+    unsigned int distributeFrequency = 1000;
+    size_t singleDataSize = (sizeof(int) + 6 * sizeof(double));
+    size_t dataSize = distributeFrequency * singleDataSize;
+    std::vector<char> data;
+
+    data.reserve(dataSize);
+
+    const char* buffer;
+    for (size_t particleIndex = 0; particleIndex < numberOfParticlesRead; ++ particleIndex) {
 
         // Read particle.
-        double x = 0.0;
-        double px =0.0;
-        double y = 0.0;
-        double py = 0.0;
-        double tOrZ = 0.0;
-        double pz = 0.0;
+        Vector_t R(0.0);
+        Vector_t P(0.0);
+
+        ++ saveProcessor;
+        if (saveProcessor >= Ippl::getNodes())
+            saveProcessor = 0;
+
         if (Ippl::myNode() == 0) {
-            inputFile >> x
-                      >> px
-                      >> y
-                      >> py
-                      >> tOrZ
-                      >> pz;
-
-            switch (inputMoUnits_m) {
-
-            case InputMomentumUnitsT::EV:
-                px = ConverteVToBetaGamma(px, massIneV);
-                py = ConverteVToBetaGamma(py, massIneV);
-                pz = ConverteVToBetaGamma(pz, massIneV);
-                break;
-
-            default:
-                break;
+            inputFile >> R(0)
+                      >> P(0)
+                      >> R(1)
+                      >> P(1)
+                      >> R(2)
+                      >> P(2);
+
+            if (inputMoUnits_m == InputMomentumUnitsT::EV) {
+                P(0) = converteVToBetaGamma(P(0), massIneV);
+                P(1) = converteVToBetaGamma(P(1), massIneV);
+                P(2) = converteVToBetaGamma(P(2), massIneV);
             }
 
-            saveProcessor++;
-            if (saveProcessor >= Ippl::getNodes())
-                saveProcessor = 0;
-        } else
-            saveProcessor = 0;
+            pmean_m += P;
 
-        // Share data.
-        reduce(saveProcessor, saveProcessor, OpAddAssign());
-        reduce(x, x, OpAddAssign());
-        reduce(px, px, OpAddAssign());
-        reduce(y, y, OpAddAssign());
-        reduce(py, py, OpAddAssign());
-        reduce(tOrZ, tOrZ, OpAddAssign());
-        reduce(pz, pz, OpAddAssign());
+            if (saveProcessor > 0) {
+                buffer = reinterpret_cast<const char*>(&saveProcessor);
+                data.insert(data.end(), buffer, buffer + sizeof(int));
+                buffer = reinterpret_cast<const char*>(&R[0]);
+                data.insert(data.end(), buffer, buffer + 3 * sizeof(double));
+                buffer = reinterpret_cast<const char*>(&P[0]);
+                data.insert(data.end(), buffer, buffer + 3 * sizeof(double));
+                ++ numPartsToSend;
+            } else {
+                xDist_m.push_back(R(0));
+                yDist_m.push_back(R(1));
+                tOrZDist_m.push_back(R(2));
+                pxDist_m.push_back(P(0));
+                pyDist_m.push_back(P(1));
+                pzDist_m.push_back(P(2));
+            }
+        } else {
+            if (saveProcessor > 0) {
+                ++ numPartsToSend;
+            }
+        }
 
-        // Store particles on proper processor.
-        if (Ippl::myNode() == saveProcessor) {
-            xDist_m.push_back(x);
-            pxDist_m.push_back(px);
-            yDist_m.push_back(y);
-            pyDist_m.push_back(py);
-            tOrZDist_m.push_back(tOrZ);
-            pzDist_m.push_back(pz);
+        if (numPartsToSend % distributeFrequency == distributeFrequency - 1) {
+            MPI_Bcast(&data[0], dataSize, MPI_CHAR, 0, Ippl::getComm());
+            numPartsToSend = 0;
+
+            if (Ippl::myNode() == 0) {
+                std::vector<char>().swap(data);
+                data.reserve(dataSize);
+            } else {
+                size_t i = 0;
+                while (i < dataSize) {
+                    int saveProcessor = *reinterpret_cast<const int*>(&data[i]);
+
+                    if (saveProcessor == Ippl::myNode()) {
+                        i += sizeof(int);
+                        const double *tmp = reinterpret_cast<const double*>(&data[i]);
+                        xDist_m.push_back(tmp[0]);
+                        yDist_m.push_back(tmp[1]);
+                        tOrZDist_m.push_back(tmp[2]);
+                        pxDist_m.push_back(tmp[3]);
+                        pyDist_m.push_back(tmp[4]);
+                        pzDist_m.push_back(tmp[5]);
+                        i += 6 * sizeof(double);
+                    } else {
+                        i += singleDataSize;
+                    }
+                }
+            }
         }
     }
+
+    MPI_Bcast(&data[0], numPartsToSend * singleDataSize, MPI_CHAR, 0, Ippl::getComm());
+
+    if (Ippl::myNode() > 0) {
+        size_t i = 0;
+        while (i < numPartsToSend * singleDataSize) {
+            int saveProcessor = *reinterpret_cast<const int*>(&data[i]);
+
+            if (saveProcessor == Ippl::myNode()) {
+                i += sizeof(int);
+                const double *tmp = reinterpret_cast<const double*>(&data[i]);
+                xDist_m.push_back(tmp[0]);
+                yDist_m.push_back(tmp[1]);
+                tOrZDist_m.push_back(tmp[2]);
+                pxDist_m.push_back(tmp[3]);
+                pyDist_m.push_back(tmp[4]);
+                pzDist_m.push_back(tmp[5]);
+                i += 6 * sizeof(double);
+            } else {
+                i += singleDataSize;
+            }
+        }
+    }
+
+    pmean_m /= numberOfParticlesRead;
+    reduce(pmean_m, pmean_m, OpAddAssign());
+
     if (Ippl::myNode() == 0)
         inputFile.close();
 }
 
 
-void Distribution::CreateMatchedGaussDistribution(size_t numberOfParticles, double massIneV) {
+void Distribution::createMatchedGaussDistribution(size_t numberOfParticles, double massIneV) {
 
-  /*
-    ToDo:
-    - add flag in order to calculate tunes from FMLOWE to FMHIGHE
-    - eliminate physics and error
-  */
+    /*
+      ToDo:
+      - add flag in order to calculate tunes from FMLOWE to FMHIGHE
+      - eliminate physics and error
+    */
 
-  std::string LineName = Attributes::getString(itsAttr[AttributesT::LINE]);
-  if (LineName != "") {
-    const BeamSequence* LineSequence = BeamSequence::find(LineName);
-    if (LineSequence != NULL) {
-      SpecificElementVisitor<Cyclotron> CyclotronVisitor(*LineSequence->fetchLine());
-      CyclotronVisitor.execute();
-      size_t NumberOfCyclotrons = CyclotronVisitor.size();
+    std::string LineName = Attributes::getString(itsAttr[AttributesT::LINE]);
+    if (LineName != "") {
+        const BeamSequence* LineSequence = BeamSequence::find(LineName);
+        if (LineSequence != NULL) {
+            SpecificElementVisitor<Cyclotron> CyclotronVisitor(*LineSequence->fetchLine());
+            CyclotronVisitor.execute();
+            size_t NumberOfCyclotrons = CyclotronVisitor.size();
+
+            if (NumberOfCyclotrons > 1) {
+                throw OpalException("Distribution::createMatchedGaussDistribution",
+                                    "I am confused, found more than one Cyclotron element in line");
+            }
+            if (NumberOfCyclotrons == 0) {
+                throw OpalException("Distribution::createMatchedGaussDistribution",
+                                    "didn't find any Cyclotron element in line");
+            }
+            const Cyclotron* CyclotronElement = CyclotronVisitor.front();
+
+            *gmsg << "* ----------------------------------------------------" << endl;
+            *gmsg << "* About to find closed orbit and matched distribution " << endl;
+            *gmsg << "* I= " << I_m*1E3 << " (mA)  E= " << E_m*1E-6 << " (MeV)" << endl;
+            *gmsg << "* EX= "  << Attributes::getReal(itsAttr[AttributesT::EX])
+                  << "* EY= " << Attributes::getReal(itsAttr[AttributesT::EY])
+                  << "* ET= " << Attributes::getReal(itsAttr[AttributesT::ET])
+                  << "* FMAPFN " << Attributes::getString(itsAttr[AttributesT::FMAPFN]) << endl //CyclotronElement->getFieldMapFN() << endl
+                  << "* FMSYM= " << (int)Attributes::getReal(itsAttr[AttributesT::MAGSYM])
+                  << "* HN= "   << CyclotronElement->getCyclHarm()
+                  << "* PHIINIT= " << CyclotronElement->getPHIinit() << endl;
+            *gmsg << "* ----------------------------------------------------" << endl;
+
+            const double wo = CyclotronElement->getRfFrequ()*1E6/CyclotronElement->getCyclHarm()*2.0*Physics::pi;
+
+            const double fmLowE  = CyclotronElement->getFMLowE();
+            const double fmHighE = CyclotronElement->getFMHighE();
+
+            double lE,hE;
+            lE = fmLowE;
+            hE = fmHighE;
+
+            if ((lE<0) || (hE<0)) {
+                lE = E_m*1E-6;
+                hE = E_m*1E-6;
+            }
 
-      if (NumberOfCyclotrons > 1) {
-	throw OpalException("Distribution::CreateMatchedGaussDistribution",
-			    "I am confused, found more than one Cyclotron element in line");
-      }
-      if (NumberOfCyclotrons == 0) {
-	throw OpalException("Distribution::CreateMatchedGaussDistribution",
-			    "didn't find any Cyclotron element in line");
-      }
-      const Cyclotron* CyclotronElement = CyclotronVisitor.front();
-
-      *gmsg << "* ----------------------------------------------------" << endl;
-      *gmsg << "* About to find closed orbit and matched distribution " << endl;
-      *gmsg << "* I= " << I_m*1E3 << " (mA)  E= " << E_m*1E-6 << " (MeV)" << endl;
-      *gmsg << "* EX= "  << Attributes::getReal(itsAttr[AttributesT::EX])
-	    << "* EY= " << Attributes::getReal(itsAttr[AttributesT::EY])
-	    << "* ET= " << Attributes::getReal(itsAttr[AttributesT::ET])
-	    << "* FMAPFN " << Attributes::getString(itsAttr[AttributesT::FMAPFN]) << endl //CyclotronElement->getFieldMapFN() << endl
-	    << "* FMSYM= " << (int)Attributes::getReal(itsAttr[AttributesT::MAGSYM])
-	    << "* HN= "   << CyclotronElement->getCyclHarm()
-	    << "* PHIINIT= " << CyclotronElement->getPHIinit() << endl;
-      *gmsg << "* ----------------------------------------------------" << endl;
-
-      const double wo = CyclotronElement->getRfFrequ()*1E6/CyclotronElement->getCyclHarm()*2.0*Physics::pi;
-
-      const double fmLowE  = CyclotronElement->getFMLowE();
-      const double fmHighE = CyclotronElement->getFMHighE();
-
-      double lE,hE;
-      lE = fmLowE;
-      hE = fmHighE;
-
-      if ((lE<0) || (hE<0)) {
-	lE = E_m*1E-6;
-	hE = E_m*1E-6;
-      }
+            int Nint = 1000;
+            bool writeMap = true;
+
+            SigmaGenerator<double,unsigned int> *siggen = new SigmaGenerator<double,unsigned int>(I_m,
+                                                                                                  Attributes::getReal(itsAttr[AttributesT::EX])*1E6,
+                                                                                                  Attributes::getReal(itsAttr[AttributesT::EY])*1E6,
+                                                                                                  Attributes::getReal(itsAttr[AttributesT::ET])*1E6,
+                                                                                                  wo,
+                                                                                                  E_m*1E-6,
+                                                                                                  CyclotronElement->getCyclHarm(),
+                                                                                                  massIneV*1E-6,
+                                                                                                  lE,
+                                                                                                  hE,
+                                                                                                  (int)Attributes::getReal(itsAttr[AttributesT::MAGSYM]),
+                                                                                                  Nint,
+                                                                                                  Attributes::getString(itsAttr[AttributesT::FMAPFN]),
+                                                                                                  Attributes::getReal(itsAttr[AttributesT::ORDERMAPS]),
+                                                                                                  writeMap);
+
+
+            if(siggen->match(Attributes::getReal(itsAttr[AttributesT::RESIDUUM]),
+                             Attributes::getReal(itsAttr[AttributesT::MAXSTEPSSI]),
+                             Attributes::getReal(itsAttr[AttributesT::MAXSTEPSCO]),
+                             CyclotronElement->getPHIinit(),
+                             Attributes::getReal(itsAttr[AttributesT::RGUESS]),
+                             Attributes::getString(itsAttr[AttributesT::FMTYPE]),
+                             false))  {
+
+                std::array<double,3> Emit = siggen->getEmittances();
+
+                if (Attributes::getReal(itsAttr[AttributesT::RGUESS]) > 0)
+                    *gmsg << "* RGUESS " << Attributes::getReal(itsAttr[AttributesT::RGUESS])/1000.0 << " (m) " << endl;
+
+                *gmsg << "* Converged (Ex, Ey, Ez) = (" << Emit[0] << ", " << Emit[1] << ", "
+                      << Emit[2] << ") pi mm mrad for E= " << E_m*1E-6 << " (MeV)" << endl;
+                *gmsg << "* Sigma-Matrix " << endl;
+
+                for(unsigned int i = 0; i < siggen->getSigma().size1(); ++ i) {
+                    *gmsg << std::setprecision(4)  << std::setw(11) << siggen->getSigma()(i,0);
+                    for(unsigned int j = 1; j < siggen->getSigma().size2(); ++ j) {
+                        *gmsg << " & " <<  std::setprecision(4)  << std::setw(11) << siggen->getSigma()(i,j);
+                    }
+                    *gmsg << " \\\\" << endl;
+                }
 
-      int Nint = 1000;
-      bool writeMap = true;
-
-      SigmaGenerator<double,unsigned int> *siggen = new SigmaGenerator<double,unsigned int>(I_m,
-						 Attributes::getReal(itsAttr[AttributesT::EX])*1E6,
-						 Attributes::getReal(itsAttr[AttributesT::EY])*1E6,
-						 Attributes::getReal(itsAttr[AttributesT::ET])*1E6,
-						 wo,
-						 E_m*1E-6,
-						 CyclotronElement->getCyclHarm(),
-						 massIneV*1E-6,
-						 lE,
-						 hE,
-						 (int)Attributes::getReal(itsAttr[AttributesT::MAGSYM]),
-						 Nint,
-						 Attributes::getString(itsAttr[AttributesT::FMAPFN]),
-						 Attributes::getReal(itsAttr[AttributesT::ORDERMAPS]),
-						 writeMap);
-
-
-      if(siggen->match(Attributes::getReal(itsAttr[AttributesT::RESIDUUM]),
-                       Attributes::getReal(itsAttr[AttributesT::MAXSTEPSSI]),
-                       Attributes::getReal(itsAttr[AttributesT::MAXSTEPSCO]),
-                       CyclotronElement->getPHIinit(),
-                       Attributes::getReal(itsAttr[AttributesT::RGUESS]),
-                       Attributes::getString(itsAttr[AttributesT::FMTYPE]),
-                       false))  {
-
-	std::array<double,3> Emit = siggen->getEmittances();
-
-	if (Attributes::getReal(itsAttr[AttributesT::RGUESS]) > 0)
-	  *gmsg << "* RGUESS " << Attributes::getReal(itsAttr[AttributesT::RGUESS])/1000.0 << " (m) " << endl;
-
-	*gmsg << "* Converged (Ex, Ey, Ez) = (" << Emit[0] << ", " << Emit[1] << ", "
-              << Emit[2] << ") pi mm mrad for E= " << E_m*1E-6 << " (MeV)" << endl;
-	*gmsg << "* Sigma-Matrix " << endl;
-
-	for(unsigned int i = 0; i < siggen->getSigma().size1(); ++ i) {
-	  *gmsg << std::setprecision(4)  << std::setw(11) << siggen->getSigma()(i,0);
-	  for(unsigned int j = 1; j < siggen->getSigma().size2(); ++ j) {
-	    *gmsg << " & " <<  std::setprecision(4)  << std::setw(11) << siggen->getSigma()(i,j);
-	  }
-	  *gmsg << " \\\\" << endl;
-	}
-
-	/*
-
-	  Now setup the distribution generator
-	  Units of the Sigma Matrix:
-
-	  spatial: mm
-	  moment:  rad
-
-	*/
-
-	if(Options::cloTuneOnly)
-	  throw OpalException("Do only CLO and tune calculation","... ");
-
-
-	auto sigma = siggen->getSigma();
-	// change units from mm to m
-	for (unsigned int i = 0; i < 3; ++ i) {
-	  for (unsigned int j = 0; j < 6; ++ j) {
-	    sigma(2 * i, j) *= 1e-3;
-	    sigma(j, 2 * i) *= 1e-3;
-	  }
-	}
-
-	for (unsigned int i = 0; i < 3; ++ i) {
-          if ( sigma(2 * i, 2 * i) < 0 || sigma(2 * i + 1, 2 * i + 1) < 0 )
-              throw OpalException("Distribution::CreateMatchedGaussDistribution()",
-                                  "Negative value on the diagonal of the sigma matrix.");
-
-	  sigmaR_m[i] = std::sqrt(sigma(2 * i, 2 * i));
-	  sigmaP_m[i] = std::sqrt(sigma(2 * i + 1, 2 * i + 1));
-
-
-	}
-
-	if (inputMoUnits_m == InputMomentumUnitsT::EV) {
-	  for (unsigned int i = 0; i < 3; ++ i) {
-	    sigmaP_m[i] = ConverteVToBetaGamma(sigmaP_m[i], massIneV);
-	  }
-	}
-
-	correlationMatrix_m(1, 0) = sigma(0, 1) / (sqrt(sigma(0, 0) * sigma(1, 1)));
-	correlationMatrix_m(3, 2) = sigma(2, 3) / (sqrt(sigma(2, 2) * sigma(3, 3)));
-	correlationMatrix_m(5, 4) = sigma(4, 5) / (sqrt(sigma(4, 4) * sigma(5, 5)));
-	correlationMatrix_m(4, 0) = sigma(0, 4) / (sqrt(sigma(0, 0) * sigma(4, 4)));
-	correlationMatrix_m(4, 1) = sigma(1, 4) / (sqrt(sigma(1, 1) * sigma(4, 4)));
-	correlationMatrix_m(5, 0) = sigma(0, 5) / (sqrt(sigma(0, 0) * sigma(5, 5)));
-	correlationMatrix_m(5, 1) = sigma(1, 5) / (sqrt(sigma(1, 1) * sigma(5, 5)));
-
-	CreateDistributionGauss(numberOfParticles, massIneV);
-      }
-      else {
-	*gmsg << "* Not converged for " << E_m*1E-6 << " MeV" << endl;
+                /*
 
-        if (siggen)
-            delete siggen;
+                  Now setup the distribution generator
+                  Units of the Sigma Matrix:
 
-        throw OpalException("Distribution::CreateMatchedGaussDistribution", "didn't find any matched distribution.");
-      }
+                  spatial: mm
+                  moment:  rad
 
-      if (siggen)
-	delete siggen;
+                */
+
+                if(Options::cloTuneOnly)
+                    throw OpalException("Do only CLO and tune calculation","... ");
+
+
+                auto sigma = siggen->getSigma();
+                // change units from mm to m
+                for (unsigned int i = 0; i < 3; ++ i) {
+                    for (unsigned int j = 0; j < 6; ++ j) {
+                        sigma(2 * i, j) *= 1e-3;
+                        sigma(j, 2 * i) *= 1e-3;
+                    }
+                }
+
+                for (unsigned int i = 0; i < 3; ++ i) {
+                    if ( sigma(2 * i, 2 * i) < 0 || sigma(2 * i + 1, 2 * i + 1) < 0 )
+                        throw OpalException("Distribution::CreateMatchedGaussDistribution()",
+                                            "Negative value on the diagonal of the sigma matrix.");
+
+                    sigmaR_m[i] = std::sqrt(sigma(2 * i, 2 * i));
+                    sigmaP_m[i] = std::sqrt(sigma(2 * i + 1, 2 * i + 1));
+                }
+
+                if (inputMoUnits_m == InputMomentumUnitsT::EV) {
+                    for (unsigned int i = 0; i < 3; ++ i) {
+                        sigmaP_m[i] = converteVToBetaGamma(sigmaP_m[i], massIneV);
+                    }
+                }
+
+                correlationMatrix_m(1, 0) = sigma(0, 1) / (sqrt(sigma(0, 0) * sigma(1, 1)));
+                correlationMatrix_m(3, 2) = sigma(2, 3) / (sqrt(sigma(2, 2) * sigma(3, 3)));
+                correlationMatrix_m(5, 4) = sigma(4, 5) / (sqrt(sigma(4, 4) * sigma(5, 5)));
+                correlationMatrix_m(4, 0) = sigma(0, 4) / (sqrt(sigma(0, 0) * sigma(4, 4)));
+                correlationMatrix_m(4, 1) = sigma(1, 4) / (sqrt(sigma(1, 1) * sigma(4, 4)));
+                correlationMatrix_m(5, 0) = sigma(0, 5) / (sqrt(sigma(0, 0) * sigma(5, 5)));
+                correlationMatrix_m(5, 1) = sigma(1, 5) / (sqrt(sigma(1, 1) * sigma(5, 5)));
+
+                createDistributionGauss(numberOfParticles, massIneV);
+            }
+            else {
+                *gmsg << "* Not converged for " << E_m*1E-6 << " MeV" << endl;
+
+                if (siggen)
+                    delete siggen;
+
+                throw OpalException("Distribution::CreateMatchedGaussDistribution",
+                                    "didn't find any matched distribution.");
+            }
+
+            if (siggen)
+                delete siggen;
+
+        }
+        else
+            throw OpalException("Distribution::CreateMatchedGaussDistribution",
+                                "didn't find any Cyclotron element in line");
     }
-    else
-      throw OpalException("Distribution::CreateMatchedGaussDistribution", "didn't find any Cyclotron element in line");
-  }
 }
 
-void Distribution::CreateDistributionGauss(size_t numberOfParticles, double massIneV) {
+void Distribution::createDistributionGauss(size_t numberOfParticles, double massIneV) {
 
-    SetDistParametersGauss(massIneV);
+    setDistParametersGauss(massIneV);
 
     if (emitting_m) {
-        GenerateTransverseGauss(numberOfParticles);
-        GenerateLongFlattopT(numberOfParticles);
+        generateTransverseGauss(numberOfParticles);
+        generateLongFlattopT(numberOfParticles);
     } else {
-        GenerateGaussZ(numberOfParticles);
+        generateGaussZ(numberOfParticles);
     }
 }
 
-void  Distribution::CreateBoundaryGeometry(PartBunch &beam, BoundaryGeometry &bg) {
+void  Distribution::createBoundaryGeometry(PartBunch &beam, BoundaryGeometry &bg) {
 
     int pc = 0;
     size_t N_mean = static_cast<size_t>(floor(bg.getN() / Ippl::getNodes()));
@@ -1485,7 +1566,6 @@ void  Distribution::CreateBoundaryGeometry(PartBunch &beam, BoundaryGeometry &bg
                     beam.PType[lowMark + count] = ParticleType::FIELDEMISSION;
                     beam.TriID[lowMark + count] = 0;
                     beam.Q[lowMark + count] = beam.getChargePerParticle();
-                    beam.LastSection[lowMark + count] = 0;
                     beam.Ef[lowMark + count] = Vector_t(0.0);
                     beam.Bf[lowMark + count] = Vector_t(0.0);
                     beam.dt[lowMark + count] = beam.getdT();
@@ -1502,7 +1582,7 @@ void  Distribution::CreateBoundaryGeometry(PartBunch &beam, BoundaryGeometry &bg
     *gmsg << &beam << endl;
 }
 
-void Distribution::CreateOpalCycl(PartBunch &beam,
+void Distribution::createOpalCycl(PartBunch &beam,
                                   size_t numberOfParticles,
                                   double current, const Beamline &bl,
                                   bool scan) {
@@ -1511,9 +1591,9 @@ void Distribution::CreateOpalCycl(PartBunch &beam,
      *  setup data for matched distribution generation
      */
 
-    E_m = (beam.getGamma()-1.0)*beam.getM();
+    E_m = (beam.getInitialGamma()-1.0)*beam.getM();
     I_m = current;
-    bega_m = beam.getGamma()*beam.getBeta();
+    bega_m = beam.getInitialGamma()*beam.getInitialBeta();
 
     /*
      * When scan mode is true, we need to destroy particles except
@@ -1526,6 +1606,7 @@ void Distribution::CreateOpalCycl(PartBunch &beam,
       avrgpz_m = beam.getP()/beam.getM();
     */
     size_t numberOfPartToCreate = numberOfParticles;
+    totalNumberParticles_m = numberOfParticles;
     if (beam.getTotalNum() != 0) {
         scan_m = scan;
         numberOfPartToCreate = beam.getLocalNum();
@@ -1537,19 +1618,19 @@ void Distribution::CreateOpalCycl(PartBunch &beam,
      * can create new particles.
      */
     if (scan_m)
-        DestroyBeam(beam);
+        destroyBeam(beam);
 
     // Setup particle bin structure.
-    SetupParticleBins(beam.getM(),beam);
+    setupParticleBins(beam.getM(),beam);
 
     /*
      * Set what units to use for input momentum units. Default is
      * eV.
      */
-    ChooseInputMomentumUnits(InputMomentumUnitsT::EV);
+    chooseInputMomentumUnits(InputMomentumUnitsT::EV);
 
     // Set distribution type.
-    SetDistType();
+    setDistType();
 
     // Emitting particles in not supported in OpalCyclT.
     emitting_m = false;
@@ -1564,31 +1645,31 @@ void Distribution::CreateOpalCycl(PartBunch &beam,
         numberOfPartToCreate /= 2;
 
     // Create distribution.
-    Create(numberOfPartToCreate, beam.getM());
+    create(numberOfPartToCreate, beam.getM());
 
     // Now reflect particles if Options::cZero is true.
     if (Options::cZero && !(distrTypeT_m == DistrTypeT::FROMFILE))
-        ReflectDistribution(numberOfPartToCreate);
+        reflectDistribution(numberOfPartToCreate);
 
-    ShiftDistCoordinates(beam.getM());
+    shiftDistCoordinates(beam.getM());
 
     // Setup energy bins.
     if (numberOfEnergyBins_m > 0) {
-        FillParticleBins();
+        fillParticleBins();
         beam.setPBins(energyBins_m);
     }
 
     // Check number of particles in distribution.
-    CheckParticleNumber(numberOfParticles);
+    checkParticleNumber(numberOfParticles);
 
-    InitializeBeam(beam);
-    WriteOutFileHeader();
+    initializeBeam(beam);
+    writeOutFileHeader();
 
-    InjectBeam(beam);
+    injectBeam(beam);
 
 }
 
-void Distribution::CreateOpalE(Beam *beam,
+void Distribution::createOpalE(Beam *beam,
                                std::vector<Distribution *> addedDistributions,
                                EnvelopeBunch *envelopeBunch,
                                double distCenter,
@@ -1603,32 +1684,32 @@ void Distribution::CreateOpalE(Beam *beam,
      * Set what units to use for input momentum units. Default is
      * unitless (i.e. BetaXGamma, BetaYGamma, BetaZGamma).
      */
-    ChooseInputMomentumUnits(InputMomentumUnitsT::NONE);
+    chooseInputMomentumUnits(InputMomentumUnitsT::NONE);
 
-    SetDistType();
+    setDistType();
 
     // Check if this is to be an emitted beam.
-    CheckIfEmitted();
+    checkIfEmitted();
 
     switch (distrTypeT_m) {
 
     case DistrTypeT::FLATTOP:
-        SetDistParametersFlattop(beam->getMass());
+        setDistParametersFlattop(beam->getMass());
         beamEnergy = Attributes::getReal(itsAttr[AttributesT::EKIN]);
         break;
     case DistrTypeT::GAUSS:
-        SetDistParametersGauss(beam->getMass());
+        setDistParametersGauss(beam->getMass());
         break;
     case DistrTypeT::GUNGAUSSFLATTOPTH:
         INFOMSG("GUNGAUSSFLATTOPTH"<<endl);
-        SetDistParametersFlattop(beam->getMass());
+        setDistParametersFlattop(beam->getMass());
         beamEnergy = Attributes::getReal(itsAttr[AttributesT::EKIN]);
         break;
     default:
         *gmsg << "Only GAUSS and GUNGAUSSFLATTOPTH distribution types supported " << endl
               << "in envelope mode. Assuming FLATTOP." << endl;
         distrTypeT_m = DistrTypeT::FLATTOP;
-        SetDistParametersFlattop(beam->getMass());
+        setDistParametersFlattop(beam->getMass());
         break;
     }
 
@@ -1655,16 +1736,16 @@ void Distribution::CreateOpalE(Beam *beam,
     IpplTimings::stopTimer(envelopeBunch->distrCreate_m);
 }
 
-void Distribution::CreateOpalT(PartBunch &beam,
+void Distribution::createOpalT(PartBunch &beam,
                                std::vector<Distribution *> addedDistributions,
                                size_t &numberOfParticles,
                                bool scan) {
 
     addedDistributions_m = addedDistributions;
-    CreateOpalT(beam, numberOfParticles, scan);
+    createOpalT(beam, numberOfParticles, scan);
 }
 
-void Distribution::CreateOpalT(PartBunch &beam,
+void Distribution::createOpalT(PartBunch &beam,
                                size_t &numberOfParticles,
                                bool scan) {
 
@@ -1673,36 +1754,28 @@ void Distribution::CreateOpalT(PartBunch &beam,
     // This is PC from BEAM
     avrgpz_m = beam.getP()/beam.getM();
 
+    totalNumberParticles_m = numberOfParticles;
+
     /*
      * If in scan mode, destroy existing beam so we
      * can create new particles.
      */
     scan_m = scan;
     if (scan_m)
-        DestroyBeam(beam);
+        destroyBeam(beam);
 
     /*
      * Set what units to use for input momentum units. Default is
      * unitless (i.e. BetaXGamma, BetaYGamma, BetaZGamma).
      */
-    ChooseInputMomentumUnits(InputMomentumUnitsT::NONE);
+    chooseInputMomentumUnits(InputMomentumUnitsT::NONE);
 
     // Set distribution type(s).
-    SetDistType();
+    setDistType();
     std::vector<Distribution *>::iterator addedDistIt;
     for (addedDistIt = addedDistributions_m.begin();
          addedDistIt != addedDistributions_m.end(); addedDistIt++)
-        (*addedDistIt)->SetDistType();
-
-    // Check if this is to be an emitted beam.
-    CheckIfEmitted();
-
-    if (emitting_m) {
-        CheckEmissionParameters();
-        SetupEmissionModel(beam);
-    } else {
-        pmean_m = Vector_t(0.0, 0.0, ConverteVToBetaGamma(GetEkin(), beam.getM()));
-    }
+        (*addedDistIt)->setDistType();
 
     /*
      * If Options::cZero is true than we reflect generated distribution
@@ -1719,7 +1792,10 @@ void Distribution::CreateOpalT(PartBunch &beam,
      * the number of particles in that file will override what is
      * determined here.
      */
-    CalcPartPerDist(numberOfParticles);
+    calcPartPerDist(numberOfParticles);
+
+    // Check if this is to be an emitted beam.
+    checkIfEmitted();
 
     /*
      * Force added distributions to the same emission condition as the main
@@ -1727,37 +1803,44 @@ void Distribution::CreateOpalT(PartBunch &beam,
      */
     for (addedDistIt = addedDistributions_m.begin();
          addedDistIt != addedDistributions_m.end(); addedDistIt++)
-        (*addedDistIt)->SetDistToEmitted(emitting_m);
+        (*addedDistIt)->setDistToEmitted(emitting_m);
 
     // Create distributions.
-    Create(particlesPerDist_m.at(0), beam.getM());
+    create(particlesPerDist_m.at(0), beam.getM());
 
     size_t distCount = 1;
     for (addedDistIt = addedDistributions_m.begin();
          addedDistIt != addedDistributions_m.end(); addedDistIt++) {
-        (*addedDistIt)->Create(particlesPerDist_m.at(distCount), beam.getM());
+        (*addedDistIt)->create(particlesPerDist_m.at(distCount), beam.getM());
         distCount++;
     }
 
     // Move added distribution particles to main distribution.
-    AddDistributions();
+    addDistributions();
 
     // Now reflect particles if Options::cZero is true
     if (Options::cZero && !(distrTypeT_m == DistrTypeT::FROMFILE))
-        ReflectDistribution(numberOfParticles);
-
-    ShiftDistCoordinates(beam.getM());
+        reflectDistribution(numberOfParticles);
 
     // Check number of particles in distribution.
-    CheckParticleNumber(numberOfParticles);
+    checkParticleNumber(numberOfParticles);
+
+    if (emitting_m) {
+        checkEmissionParameters();
+        setupEmissionModel(beam);
+    } else {
+        if (distrTypeT_m != DistrTypeT::FROMFILE) {
+            pmean_m = Vector_t(0.0, 0.0, converteVToBetaGamma(getEkin(), beam.getM()));
+        }
+    }
 
     /*
      * Find max. and min. particle positions in the bunch. For the
      * case of an emitted beam these will be in time (seconds). For
      * an injected beam in z (meters).
      */
-    double maxTOrZ = GetMaxTOrZ();
-    double minTOrZ = GetMinTOrZ();
+    double maxTOrZ = getMaxTOrZ();
+    double minTOrZ = getMinTOrZ();
 
     /*
      * Set emission time and/or shift distributions if necessary.
@@ -1765,18 +1848,20 @@ void Distribution::CreateOpalT(PartBunch &beam,
      * For an injected beam we just ensure that there are no
      * particles at z < 0.
      */
-    if (emitting_m)
-        SetEmissionTime(maxTOrZ, minTOrZ);
-    ShiftBeam(maxTOrZ, minTOrZ);
+    if (emitting_m) {
+        setEmissionTime(maxTOrZ, minTOrZ);
+    }
+    shiftBeam(maxTOrZ, minTOrZ);
+
+    shiftDistCoordinates(beam.getM());
 
     if (numberOfEnergyBins_m > 0) {
-        SetupEnergyBins(maxTOrZ, minTOrZ);
-        FillEBinHistogram();
-    } else
-        energyBins_m = NULL;
+        setupEnergyBins(maxTOrZ, minTOrZ);
+        fillEBinHistogram();
+    }
 
-    InitializeBeam(beam);
-    WriteOutFileHeader();
+    initializeBeam(beam);
+    writeOutFileHeader();
 
     if (emitting_m && Options::cZero) {
         std::vector<std::vector<double> > mirrored;
@@ -1793,12 +1878,12 @@ void Distribution::CreateOpalT(PartBunch &beam,
      * Emitted beams get created during the course of the simulation.
      */
     if (!emitting_m)
-        InjectBeam(beam);
+        injectBeam(beam);
 
     IpplTimings::stopTimer(beam.distrCreate_m);
 }
 
-void Distribution::DestroyBeam(PartBunch &beam) {
+void Distribution::destroyBeam(PartBunch &beam) {
 
     particlesPerDist_m.clear();
     xDist_m.clear();
@@ -1845,12 +1930,12 @@ void Distribution::DestroyBeam(PartBunch &beam) {
  exists in the simulation. For the next integration time step, the particle's time step is set back to the global time step,
  \f$\Delta t_{full-timestep}\f$.
 */
-size_t Distribution::EmitParticles(PartBunch &beam, double eZ) {
+size_t Distribution::emitParticles(PartBunch &beam, double eZ) {
 
     // Number of particles that have already been emitted and are on this processor.
     size_t numberOfEmittedParticles = beam.getLocalNum();
     size_t oldNumberOfEmittedParticles = numberOfEmittedParticles;
-
+    static size_t counter = 0;
     if (!tOrZDist_m.empty() && emitting_m) {
 
         /*
@@ -1882,10 +1967,10 @@ size_t Distribution::EmitParticles(PartBunch &beam, double eZ) {
                 if (additionalRNs_m.size() > particleIndex) {
                     additionalRNs = additionalRNs_m[particleIndex];
                 } else {
-                    additionalRNs = std::vector<double>({gsl_rng_uniform(randGenEmit_m),
-                                                         gsl_rng_uniform(randGenEmit_m)});
+                    additionalRNs = std::vector<double>({gsl_rng_uniform(randGen_m),
+                                                         gsl_rng_uniform(randGen_m)});
                 }
-                ApplyEmissionModel(eZ, px, py, pz, additionalRNs);
+                applyEmissionModel(eZ, px, py, pz, additionalRNs);
 
                 double particleGamma
                     = std::sqrt(1.0
@@ -1903,12 +1988,12 @@ size_t Distribution::EmitParticles(PartBunch &beam, double eZ) {
                     = Vector_t(px, py, pz);
                 beam.Bin[numberOfEmittedParticles] = currentEnergyBin_m - 1;
                 beam.Q[numberOfEmittedParticles] = beam.getChargePerParticle();
-                beam.LastSection[numberOfEmittedParticles] = -1;
                 beam.Ef[numberOfEmittedParticles] = Vector_t(0.0);
                 beam.Bf[numberOfEmittedParticles] = Vector_t(0.0);
                 beam.PType[numberOfEmittedParticles] = ParticleType::REGULAR;
                 beam.TriID[numberOfEmittedParticles] = 0;
                 numberOfEmittedParticles++;
+
                 beam.iterateEmittedBin(currentEnergyBin_m - 1);
 
                 // Save particles to vectors for writing initial distribution.
@@ -1991,72 +2076,60 @@ size_t Distribution::EmitParticles(PartBunch &beam, double eZ) {
     currentEmissionTime_m += beam.getdT();
 
     // Write emitted particles to file.
-    WriteOutFileEmission();
+    writeOutFileEmission();
 
-    return numberOfEmittedParticles - oldNumberOfEmittedParticles;
+    size_t currentEmittedParticles = numberOfEmittedParticles - oldNumberOfEmittedParticles;
+    reduce(currentEmittedParticles, currentEmittedParticles, OpAddAssign());
+    totalNumberEmittedParticles_m += currentEmittedParticles;
+    ++ counter;
+    return currentEmittedParticles;
 
 }
 
-void Distribution::EraseXDist() {
+void Distribution::eraseXDist() {
     xDist_m.erase(xDist_m.begin(), xDist_m.end());
 }
 
-void Distribution::EraseBGxDist() {
+void Distribution::eraseBGxDist() {
     pxDist_m.erase(pxDist_m.begin(), pxDist_m.end());
 }
 
-void Distribution::EraseYDist() {
+void Distribution::eraseYDist() {
     yDist_m.erase(yDist_m.begin(), yDist_m.end());
 }
 
-void Distribution::EraseBGyDist() {
+void Distribution::eraseBGyDist() {
     pyDist_m.erase(pyDist_m.begin(), pyDist_m.end());
 }
 
-void Distribution::EraseTOrZDist() {
+void Distribution::eraseTOrZDist() {
     tOrZDist_m.erase(tOrZDist_m.begin(), tOrZDist_m.end());
 }
 
-void Distribution::EraseBGzDist() {
+void Distribution::eraseBGzDist() {
     pzDist_m.erase(pzDist_m.begin(), pzDist_m.end());
 }
 
-void Distribution::FillEBinHistogram() {
+void Distribution::fillEBinHistogram() {
+    double upper = 0.0;
+    double lower = 0.0;
+    gsl_histogram_get_range(energyBinHist_m,
+                            gsl_histogram_bins(energyBinHist_m) - 1,
+                            &lower, &upper);
+    const size_t numberOfParticles = tOrZDist_m.size();
+    for (size_t partIndex = 0; partIndex < numberOfParticles; partIndex++) {
 
-    /*
-     * Loop over longitudinal beam coordinates and add them to the energy
-     * bin histogram. Because of how we defined the bin structure the maximum
-     * longitudinal coordinate will not be counted. So, we just force it in there
-     * by artificially incrementing the last bin.
-     */
-    for (int processor = 0; processor < Ippl::getNodes(); processor++) {
-
-        size_t numberOfParticles = 0;
-        if (Ippl::myNode() == processor)
-            numberOfParticles = tOrZDist_m.size();
-        reduce(numberOfParticles, numberOfParticles, OpAddAssign());
-
-        for (size_t partIndex = 0; partIndex < numberOfParticles; partIndex++) {
-
-            double tOrZ = 0.0;
-            if (Ippl::myNode() == processor)
-                tOrZ = tOrZDist_m.at(partIndex);
-            reduce(tOrZ, tOrZ, OpAddAssign());
-
-            if (gsl_histogram_increment(energyBinHist_m, tOrZ) == GSL_EDOM) {
-                double upper = 0.0;
-                double lower = 0.0;
-                gsl_histogram_get_range(energyBinHist_m,
-                                        gsl_histogram_bins(energyBinHist_m) - 1,
-                                        &lower, &upper);
-                gsl_histogram_increment(energyBinHist_m, lower);
-            }
+        double &tOrZ = tOrZDist_m.at(partIndex);
 
+        if (gsl_histogram_increment(energyBinHist_m, tOrZ) == GSL_EDOM) {
+            gsl_histogram_increment(energyBinHist_m, 0.5 * (lower + upper));
         }
     }
+
+    reduce(energyBinHist_m->bin, energyBinHist_m->bin + energyBinHist_m->n, energyBinHist_m->bin, OpAddAssign());
 }
 
-void Distribution::FillParticleBins() {
+void Distribution::fillParticleBins() {
 
     for (size_t particleIndex = 0; particleIndex < tOrZDist_m.size(); particleIndex++) {
 
@@ -2077,35 +2150,27 @@ void Distribution::FillParticleBins() {
     energyBins_m->sortArray();
 }
 
-size_t Distribution::FindEBin(double tOrZ) {
+size_t Distribution::findEBin(double tOrZ) {
 
     if (tOrZ <= gsl_histogram_min(energyBinHist_m)) {
         return 0;
     } else if (tOrZ >= gsl_histogram_max(energyBinHist_m)) {
         return numberOfEnergyBins_m - 1;
     } else {
-        gsl_histogram *energyBinHist = gsl_histogram_alloc(numberOfEnergyBins_m);
-        gsl_histogram_set_ranges_uniform(energyBinHist,
-                                         gsl_histogram_min(energyBinHist_m),
-                                         gsl_histogram_max(energyBinHist_m));
-
         size_t binNumber;
-        gsl_histogram_find(energyBinHist, tOrZ, &binNumber);
-        gsl_histogram_free(energyBinHist);
-        return binNumber;
+        gsl_histogram_find(energyBinHist_m, tOrZ, &binNumber);
+        return binNumber / numberOfSampleBins_m;
     }
 }
 
-void Distribution::GenerateAstraFlattopT(size_t numberOfParticles) {
+void Distribution::generateAstraFlattopT(size_t numberOfParticles) {
 
     /*
      * Legacy function to support the ASTRAFLATTOPOTH
      * distribution type.
      */
-    CheckEmissionParameters();
+    checkEmissionParameters();
 
-    gsl_rng_env_setup();
-    gsl_rng *randGen = gsl_rng_alloc(gsl_rng_1dhalton);
     gsl_qrng *quasiRandGen = gsl_qrng_alloc(gsl_qrng_halton, 2);
 
     int numberOfSampleBins
@@ -2186,7 +2251,7 @@ void Distribution::GenerateAstraFlattopT(size_t numberOfParticles) {
         for(int i = 0; i < numParticlesInBin[k]; i++) {
             double xx[2];
             gsl_qrng_get(quasiRandGen, xx);
-            tCoord = hi * (xx[1] + static_cast<int>(gsl_ran_discrete(randGen, table))
+            tCoord = hi * (xx[1] + static_cast<int>(gsl_ran_discrete(randGen_m, table))
                            - binTotal / 2 + k * numberOfSampleBins) / (binTotal / 2);
 
             saveProcessor++;
@@ -2201,13 +2266,12 @@ void Distribution::GenerateAstraFlattopT(size_t numberOfParticles) {
         gsl_ran_discrete_free(table);
     }
 
-    gsl_rng_free(randGen);
     gsl_qrng_free(quasiRandGen);
     delete [] distributionTable;
 
 }
 
-void Distribution::GenerateBinomial(size_t numberOfParticles) {
+void Distribution::generateBinomial(size_t numberOfParticles) {
 
     /*!
      *
@@ -2384,7 +2448,7 @@ void Distribution::GenerateBinomial(size_t numberOfParticles) {
     }
 }
 
-void Distribution::GenerateFlattopLaserProfile(size_t numberOfParticles) {
+void Distribution::generateFlattopLaserProfile(size_t numberOfParticles) {
 
     int saveProcessor = -1;
     for (size_t partIndex = 0; partIndex < numberOfParticles; partIndex++) {
@@ -2410,16 +2474,14 @@ void Distribution::GenerateFlattopLaserProfile(size_t numberOfParticles) {
     }
 
     if (distrTypeT_m == DistrTypeT::ASTRAFLATTOPTH)
-        GenerateAstraFlattopT(numberOfParticles);
+        generateAstraFlattopT(numberOfParticles);
     else
-        GenerateLongFlattopT(numberOfParticles);
+        generateLongFlattopT(numberOfParticles);
 
 }
 
-void Distribution::GenerateFlattopT(size_t numberOfParticles) {
+void Distribution::generateFlattopT(size_t numberOfParticles) {
 
-    gsl_rng_env_setup();
-    gsl_rng  *randGenStandard = gsl_rng_alloc(gsl_rng_default);
     gsl_qrng *quasiRandGen2D = NULL;
 
     if(Options::rngtype != std::string("RANDOM")) {
@@ -2453,8 +2515,8 @@ void Distribution::GenerateFlattopT(size_t numberOfParticles) {
                 x = -1.0 + 2.0 * randNums[0];
                 y = -1.0 + 2.0 * randNums[1];
             } else {
-                x = -1.0 + 2.0 * gsl_rng_uniform(randGenStandard);
-                y = -1.0 + 2.0 * gsl_rng_uniform(randGenStandard);
+                x = -1.0 + 2.0 * gsl_rng_uniform(randGen_m);
+                y = -1.0 + 2.0 * gsl_rng_uniform(randGen_m);
             }
 
             allow = (pow(x, 2.0) + pow(y, 2.0) <= 1.0);
@@ -2477,22 +2539,18 @@ void Distribution::GenerateFlattopT(size_t numberOfParticles) {
 
     }
 
-    gsl_rng_free(randGenStandard);
-
     if (quasiRandGen2D != NULL)
         gsl_qrng_free(quasiRandGen2D);
 
     if (distrTypeT_m == DistrTypeT::ASTRAFLATTOPTH)
-        GenerateAstraFlattopT(numberOfParticles);
+        generateAstraFlattopT(numberOfParticles);
     else
-        GenerateLongFlattopT(numberOfParticles);
+        generateLongFlattopT(numberOfParticles);
 
 }
 
-void Distribution::GenerateFlattopZ(size_t numberOfParticles) {
+void Distribution::generateFlattopZ(size_t numberOfParticles) {
 
-    gsl_rng_env_setup();
-    gsl_rng *randGenStandard = gsl_rng_alloc(gsl_rng_default);
     gsl_qrng *quasiRandGen1D = NULL;
     gsl_qrng *quasiRandGen2D = NULL;
     if(Options::rngtype != std::string("RANDOM")) {
@@ -2532,8 +2590,8 @@ void Distribution::GenerateFlattopZ(size_t numberOfParticles) {
                 x = -1.0 + 2.0 * randNums[0];
                 y = -1.0 + 2.0 * randNums[1];
             } else {
-                x = -1.0 + 2.0 * gsl_rng_uniform(randGenStandard);
-                y = -1.0 + 2.0 * gsl_rng_uniform(randGenStandard);
+                x = -1.0 + 2.0 * gsl_rng_uniform(randGen_m);
+                y = -1.0 + 2.0 * gsl_rng_uniform(randGen_m);
             }
 
             allow = (pow(x, 2.0) + pow(y, 2.0) <= 1.0);
@@ -2545,7 +2603,7 @@ void Distribution::GenerateFlattopZ(size_t numberOfParticles) {
         if (quasiRandGen1D != NULL)
             gsl_qrng_get(quasiRandGen1D, &z);
         else
-            z = gsl_rng_uniform(randGenStandard);
+            z = gsl_rng_uniform(randGen_m);
 
         z = (z - 0.5) * sigmaR_m[2];
 
@@ -2564,18 +2622,13 @@ void Distribution::GenerateFlattopZ(size_t numberOfParticles) {
         }
     }
 
-    gsl_rng_free(randGenStandard);
-
     if (quasiRandGen1D != NULL) {
         gsl_qrng_free(quasiRandGen1D);
         gsl_qrng_free(quasiRandGen2D);
     }
 }
 
-void Distribution::GenerateGaussZ(size_t numberOfParticles) {
-
-    gsl_rng_env_setup();
-    gsl_rng *randGen = gsl_rng_alloc(gsl_rng_default);
+void Distribution::generateGaussZ(size_t numberOfParticles) {
 
     gsl_matrix * corMat  = gsl_matrix_alloc (6, 6);
     gsl_vector * rx = gsl_vector_alloc(6);
@@ -2644,12 +2697,12 @@ void Distribution::GenerateGaussZ(size_t numberOfParticles) {
         double pz = 0.0;
 
         while (!allow) {
-            gsl_vector_set(rx, 0, gsl_ran_gaussian(randGen, 1.0));
-            gsl_vector_set(rx, 1, gsl_ran_gaussian(randGen, 1.0));
-            gsl_vector_set(rx, 2, gsl_ran_gaussian(randGen, 1.0));
-            gsl_vector_set(rx, 3, gsl_ran_gaussian(randGen, 1.0));
-            gsl_vector_set(rx, 4, gsl_ran_gaussian(randGen, 1.0));
-            gsl_vector_set(rx, 5, gsl_ran_gaussian(randGen, 1.0));
+            gsl_vector_set(rx, 0, gsl_ran_gaussian(randGen_m, 1.0));
+            gsl_vector_set(rx, 1, gsl_ran_gaussian(randGen_m, 1.0));
+            gsl_vector_set(rx, 2, gsl_ran_gaussian(randGen_m, 1.0));
+            gsl_vector_set(rx, 3, gsl_ran_gaussian(randGen_m, 1.0));
+            gsl_vector_set(rx, 4, gsl_ran_gaussian(randGen_m, 1.0));
+            gsl_vector_set(rx, 5, gsl_ran_gaussian(randGen_m, 1.0));
 
             gsl_blas_dgemv(CblasNoTrans, 1.0, corMat, rx, 0.0, ry);
 
@@ -2704,13 +2757,13 @@ void Distribution::GenerateGaussZ(size_t numberOfParticles) {
             pzDist_m.push_back(avrgpz_m + pz);
         }
     }
-    gsl_rng_free(randGen);
+
     gsl_vector_free(rx);
     gsl_vector_free(ry);
     gsl_matrix_free(corMat);
 }
 
-void Distribution::GenerateLongFlattopT(size_t numberOfParticles) {
+void Distribution::generateLongFlattopT(size_t numberOfParticles) {
 
     double flattopTime = tPulseLengthFWHM_m
         - sqrt(2.0 * log(2.0)) * (sigmaTRise_m + sigmaTFall_m);
@@ -2728,8 +2781,6 @@ void Distribution::GenerateLongFlattopT(size_t numberOfParticles) {
     size_t numFlat = numberOfParticles - numRise - numFall;
 
     // Generate particles in tail.
-    gsl_rng_env_setup();
-    gsl_rng *randGenGSL = gsl_rng_alloc(gsl_rng_default);
     int saveProcessor = -1;
 
     for (size_t partIndex = 0; partIndex < numFall; partIndex++) {
@@ -2739,7 +2790,7 @@ void Distribution::GenerateLongFlattopT(size_t numberOfParticles) {
 
         bool allow = false;
         while (!allow) {
-            t = gsl_ran_gaussian_tail(randGenGSL, 0, sigmaTFall_m);
+            t = gsl_ran_gaussian_tail(randGen_m, 0, sigmaTFall_m);
             if (t <= sigmaTRise_m * cutoffR_m[2]) {
                 t = -t + sigmaTFall_m * cutoffR_m[2];
                 allow = true;
@@ -2771,8 +2822,6 @@ void Distribution::GenerateLongFlattopT(size_t numberOfParticles) {
     if (numModulationPeriods != 0.0)
         modulationPeriod = flattopTime / numModulationPeriods;
 
-    gsl_rng_env_setup();
-    gsl_rng *randGen = gsl_rng_alloc(gsl_rng_default);
     gsl_qrng *quasiRandGen1D = NULL;
     gsl_qrng *quasiRandGen2D = NULL;
     if(Options::rngtype != std::string("RANDOM")) {
@@ -2803,7 +2852,7 @@ void Distribution::GenerateLongFlattopT(size_t numberOfParticles) {
             if (quasiRandGen1D != NULL)
                 gsl_qrng_get(quasiRandGen1D, &t);
             else
-                t = gsl_rng_uniform(randGen);
+                t = gsl_rng_uniform(randGen_m);
 
             t = flattopTime * t + sigmaTFall_m * cutoffR_m[2];
 
@@ -2818,8 +2867,8 @@ void Distribution::GenerateLongFlattopT(size_t numberOfParticles) {
                     t = randNums[0] * flattopTime;
                     funcAmp = randNums[1];
                 } else {
-                    t = gsl_rng_uniform(randGen)*flattopTime;
-                    funcAmp = gsl_rng_uniform(randGen);
+                    t = gsl_rng_uniform(randGen_m)*flattopTime;
+                    funcAmp = gsl_rng_uniform(randGen_m);
                 }
 
                 double funcValue = (1.0 + modulationAmp
@@ -2850,7 +2899,7 @@ void Distribution::GenerateLongFlattopT(size_t numberOfParticles) {
 
         bool allow = false;
         while (!allow) {
-            t = gsl_ran_gaussian_tail(randGenGSL, 0, sigmaTRise_m);
+            t = gsl_ran_gaussian_tail(randGen_m, 0, sigmaTRise_m);
             if (t <= sigmaTRise_m * cutoffR_m[2]) {
                 t += sigmaTFall_m * cutoffR_m[2] + flattopTime;
                 allow = true;
@@ -2868,20 +2917,15 @@ void Distribution::GenerateLongFlattopT(size_t numberOfParticles) {
         }
     }
 
-    gsl_rng_free(randGenGSL);
-    gsl_rng_free(randGen);
-
     if (quasiRandGen1D != NULL) {
         gsl_qrng_free(quasiRandGen1D);
         gsl_qrng_free(quasiRandGen2D);
     }
 }
 
-void Distribution::GenerateTransverseGauss(size_t numberOfParticles) {
+void Distribution::generateTransverseGauss(size_t numberOfParticles) {
 
     // Generate coordinates.
-    gsl_rng_env_setup();
-    gsl_rng *randGen = gsl_rng_alloc(gsl_rng_default);
     gsl_matrix * corMat  = gsl_matrix_alloc (4, 4);
     gsl_vector * rx = gsl_vector_alloc(4);
     gsl_vector * ry = gsl_vector_alloc(4);
@@ -2918,10 +2962,10 @@ void Distribution::GenerateTransverseGauss(size_t numberOfParticles) {
         bool allow = false;
         while (!allow) {
 
-            gsl_vector_set(rx, 0, gsl_ran_gaussian (randGen,1.0));
-            gsl_vector_set(rx, 1, gsl_ran_gaussian (randGen,1.0));
-            gsl_vector_set(rx, 2, gsl_ran_gaussian (randGen,1.0));
-            gsl_vector_set(rx, 3, gsl_ran_gaussian (randGen,1.0));
+            gsl_vector_set(rx, 0, gsl_ran_gaussian (randGen_m,1.0));
+            gsl_vector_set(rx, 1, gsl_ran_gaussian (randGen_m,1.0));
+            gsl_vector_set(rx, 2, gsl_ran_gaussian (randGen_m,1.0));
+            gsl_vector_set(rx, 3, gsl_ran_gaussian (randGen_m,1.0));
 
             gsl_blas_dgemv(CblasNoTrans, 1.0, corMat, rx, 0.0, ry);
             x = gsl_vector_get(ry, 0);
@@ -2970,13 +3014,12 @@ void Distribution::GenerateTransverseGauss(size_t numberOfParticles) {
         }
     }
 
-    gsl_rng_free(randGen);
     gsl_matrix_free(corMat);
     gsl_vector_free(rx);
     gsl_vector_free(ry);
 }
 
-void Distribution::InitializeBeam(PartBunch &beam) {
+void Distribution::initializeBeam(PartBunch &beam) {
 
     /*
      * Set emission time, the current beam bunch number and
@@ -2985,13 +3028,12 @@ void Distribution::InitializeBeam(PartBunch &beam) {
     beam.setTEmission(tEmission_m);
     beam.setNumBunch(1);
     if (numberOfEnergyBins_m > 0)
-        beam.SetEnergyBins(numberOfEnergyBins_m);
-    beam.LastSection = 0;
+        beam.setEnergyBins(numberOfEnergyBins_m);
 }
 
-void Distribution::InjectBeam(PartBunch &beam) {
+void Distribution::injectBeam(PartBunch &beam) {
 
-    WriteOutFileInjection();
+    writeOutFileInjection();
 
     std::vector<double> id1 = Attributes::getRealArray(itsAttr[AttributesT::ID1]);
     std::vector<double> id2 = Attributes::getRealArray(itsAttr[AttributesT::ID2]);
@@ -3022,7 +3064,7 @@ void Distribution::InjectBeam(PartBunch &beam) {
         beam.TriID[partIndex] = 0;
 
         if (numberOfEnergyBins_m > 0) {
-            size_t binNumber = FindEBin(tOrZDist_m.at(partIndex));
+            size_t binNumber = findEBin(tOrZDist_m.at(partIndex));
             beam.Bin[partIndex] = binNumber;
             beam.iterateEmittedBin(binNumber);
         } else
@@ -3057,125 +3099,87 @@ void Distribution::InjectBeam(PartBunch &beam) {
     beam.calcEMean();
 }
 
-bool Distribution::GetIfDistEmitting() {
+bool Distribution::getIfDistEmitting() {
     return emitting_m;
 }
 
-int Distribution::GetLastEmittedEnergyBin() {
+int Distribution::getLastEmittedEnergyBin() {
     return currentEnergyBin_m;
 }
 
-double Distribution::GetMaxTOrZ() {
+double Distribution::getMaxTOrZ() {
 
-    double maxTOrZ = 0.0;
-    std::vector<double>::iterator longIt;
-    for (longIt = tOrZDist_m.begin(); longIt != tOrZDist_m.end(); longIt++) {
-        if (longIt == tOrZDist_m.begin())
+    std::vector<double>::iterator longIt = tOrZDist_m.begin();
+    double maxTOrZ = *longIt;
+    for (++longIt; longIt != tOrZDist_m.end(); longIt++) {
+        if (maxTOrZ < *longIt)
             maxTOrZ = *longIt;
-        else
-            if (maxTOrZ < *longIt)
-                maxTOrZ = *longIt;
     }
 
-    std::vector<double> maxTOrZs;
-    for (int nodeIndex = 0; nodeIndex < Ippl::getNodes(); nodeIndex++) {
-        if (nodeIndex == Ippl::myNode())
-            maxTOrZs.push_back(maxTOrZ);
-        else
-            maxTOrZs.push_back(0.0);
-
-        reduce(maxTOrZs.at(nodeIndex), maxTOrZs.at(nodeIndex), OpAddAssign());
-    }
-
-    std::vector<double>::iterator maxIt;
-    for (maxIt = maxTOrZs.begin(); maxIt != maxTOrZs.end(); maxIt++) {
-        if (maxIt == maxTOrZs.begin())
-            maxTOrZ = *maxIt;
-        else if (maxTOrZ < *maxIt)
-            maxTOrZ = *maxIt;
-    }
+    reduce(maxTOrZ, maxTOrZ, OpMaxAssign());
 
     return maxTOrZ;
 }
 
-double Distribution::GetMinTOrZ() {
+double Distribution::getMinTOrZ() {
 
-    double minTOrZ = 0.0;
-    std::vector<double>::iterator longIt;
-    for (longIt = tOrZDist_m.begin(); longIt != tOrZDist_m.end(); longIt++) {
-        if (longIt == tOrZDist_m.begin())
+    std::vector<double>::iterator longIt = tOrZDist_m.begin();
+    double minTOrZ = *longIt;
+    for (++longIt; longIt != tOrZDist_m.end(); longIt++) {
+        if (minTOrZ > *longIt)
             minTOrZ = *longIt;
-        else
-            if (minTOrZ > *longIt)
-                minTOrZ = *longIt;
     }
 
-    std::vector<double> minTOrZs;
-    for (int nodeIndex = 0; nodeIndex < Ippl::getNodes(); nodeIndex++) {
-        if (nodeIndex == Ippl::myNode())
-            minTOrZs.push_back(minTOrZ);
-        else
-            minTOrZs.push_back(0.0);
-
-        reduce(minTOrZs.at(nodeIndex), minTOrZs.at(nodeIndex), OpAddAssign());
-    }
-
-    std::vector<double>::iterator minIt;
-    for (minIt = minTOrZs.begin(); minIt != minTOrZs.end(); minIt++) {
-        if (minIt == minTOrZs.begin())
-            minTOrZ = *minIt;
-        else if (minTOrZ > *minIt)
-            minTOrZ = *minIt;
-    }
+    reduce(minTOrZ, minTOrZ, OpMinAssign());
 
     return minTOrZ;
 }
 
-size_t Distribution::GetNumberOfEmissionSteps() {
+size_t Distribution::getNumberOfEmissionSteps() {
     return static_cast<size_t> (numberOfEnergyBins_m * numberOfSampleBins_m);
 }
 
-int Distribution::GetNumberOfEnergyBins() {
+int Distribution::getNumberOfEnergyBins() {
     return numberOfEnergyBins_m;
 }
 
-double Distribution::GetEmissionDeltaT() {
+double Distribution::getEmissionDeltaT() {
     return tBin_m / numberOfSampleBins_m;
 }
 
-double Distribution::GetEnergyBinDeltaT() {
+double Distribution::getEnergyBinDeltaT() {
     return tBin_m;
 }
 
-double Distribution::GetWeight() {
+double Distribution::getWeight() {
     return std::abs(Attributes::getReal(itsAttr[AttributesT::WEIGHT]));
 }
 
-std::vector<double>& Distribution::GetXDist() {
+std::vector<double>& Distribution::getXDist() {
     return xDist_m;
 }
 
-std::vector<double>& Distribution::GetBGxDist() {
+std::vector<double>& Distribution::getBGxDist() {
     return pxDist_m;
 }
 
-std::vector<double>& Distribution::GetYDist() {
+std::vector<double>& Distribution::getYDist() {
     return yDist_m;
 }
 
-std::vector<double>& Distribution::GetBGyDist() {
+std::vector<double>& Distribution::getBGyDist() {
     return pyDist_m;
 }
 
-std::vector<double>& Distribution::GetTOrZDist() {
+std::vector<double>& Distribution::getTOrZDist() {
     return tOrZDist_m;
 }
 
-std::vector<double>& Distribution::GetBGzDist() {
+std::vector<double>& Distribution::getBGzDist() {
     return pzDist_m;
 }
 
-void Distribution::PrintDist(Inform &os, size_t numberOfParticles) const {
+void Distribution::printDist(Inform &os, size_t numberOfParticles) const {
 
     if (numberOfParticles > 0) {
         os << "* Number of particles: "
@@ -3187,31 +3191,31 @@ void Distribution::PrintDist(Inform &os, size_t numberOfParticles) const {
     switch (distrTypeT_m) {
 
     case DistrTypeT::FROMFILE:
-        PrintDistFromFile(os);
+        printDistFromFile(os);
         break;
     case DistrTypeT::GAUSS:
-        PrintDistGauss(os);
+        printDistGauss(os);
         break;
     case DistrTypeT::BINOMIAL:
-        PrintDistBinomial(os);
+        printDistBinomial(os);
         break;
     case DistrTypeT::FLATTOP:
-        PrintDistFlattop(os);
+        printDistFlattop(os);
         break;
     case DistrTypeT::SURFACEEMISSION:
-        PrintDistSurfEmission(os);
+        printDistSurfEmission(os);
         break;
     case DistrTypeT::SURFACERANDCREATE:
-        PrintDistSurfAndCreate(os);
+        printDistSurfAndCreate(os);
         break;
     case DistrTypeT::GUNGAUSSFLATTOPTH:
-        PrintDistFlattop(os);
+        printDistFlattop(os);
         break;
     case DistrTypeT::ASTRAFLATTOPTH:
-        PrintDistFlattop(os);
+        printDistFlattop(os);
         break;
     case DistrTypeT::MATCHEDGAUSS:
-        PrintDistMatchedGauss(os);
+        printDistMatchedGauss(os);
         break;
     default:
         INFOMSG("Distribution unknown." << endl;);
@@ -3220,7 +3224,7 @@ void Distribution::PrintDist(Inform &os, size_t numberOfParticles) const {
 
 }
 
-void Distribution::PrintDistBinomial(Inform &os) const {
+void Distribution::printDistBinomial(Inform &os) const {
 
     os << "* Distribution type: BINOMIAL" << endl;
     os << "* " << endl;
@@ -3248,7 +3252,7 @@ void Distribution::PrintDistBinomial(Inform &os) const {
     os << "* R52      = " << correlationMatrix_m(4, 1) << endl;
 }
 
-void Distribution::PrintDistFlattop(Inform &os) const {
+void Distribution::printDistFlattop(Inform &os) const {
 
     switch (distrTypeT_m) {
 
@@ -3313,7 +3317,7 @@ void Distribution::PrintDistFlattop(Inform &os) const {
            << " [m]" << endl;
 }
 
-void Distribution::PrintDistFromFile(Inform &os) const {
+void Distribution::printDistFromFile(Inform &os) const {
     os << "* Distribution type: FROMFILE" << endl;
     os << "* " << endl;
     os << "* Input file:        "
@@ -3321,7 +3325,7 @@ void Distribution::PrintDistFromFile(Inform &os) const {
 }
 
 
-void Distribution::PrintDistMatchedGauss(Inform &os) const {
+void Distribution::printDistMatchedGauss(Inform &os) const {
     os << "* Distribution type: MATCHEDGAUSS" << endl;
     os << "* SIGMAX   = " << sigmaR_m[0] << " [m]" << endl;
     os << "* SIGMAY   = " << sigmaR_m[1] << " [m]" << endl;
@@ -3346,7 +3350,7 @@ void Distribution::PrintDistMatchedGauss(Inform &os) const {
     os << "* CUTOFFPZ = " << cutoffP_m[2] << " [units of SIGMAPY]" << endl;
 }
 
-void Distribution::PrintDistGauss(Inform &os) const {
+void Distribution::printDistGauss(Inform &os) const {
     os << "* Distribution type: GAUSS" << endl;
     os << "* " << endl;
     if (emitting_m) {
@@ -3405,7 +3409,7 @@ void Distribution::PrintDistGauss(Inform &os) const {
     }
 }
 
-void Distribution::PrintDistSurfEmission(Inform &os) const {
+void Distribution::printDistSurfEmission(Inform &os) const {
 
     os << "* Distribution type: SURFACEEMISION" << endl;
     os << "* " << endl;
@@ -3466,7 +3470,7 @@ void Distribution::PrintDistSurfEmission(Inform &os) const {
        <<  Attributes::getReal(itsAttr[AttributesT::SURFMATERIAL]) << endl;
 }
 
-void Distribution::PrintDistSurfAndCreate(Inform &os) const {
+void Distribution::printDistSurfAndCreate(Inform &os) const {
 
     os << "* Distribution type: SURFACERANDCREATE" << endl;
     os << "* " << endl;
@@ -3479,20 +3483,20 @@ void Distribution::PrintDistSurfAndCreate(Inform &os) const {
        << Attributes::getReal(itsAttr[AttributesT::EINITHR]) << endl;
 }
 
-void Distribution::PrintEmissionModel(Inform &os) const {
+void Distribution::printEmissionModel(Inform &os) const {
 
     os << "* ------------- THERMAL EMITTANCE MODEL --------------------------------------------" << endl;
 
     switch (emissionModel_m) {
 
     case EmissionModelT::NONE:
-        PrintEmissionModelNone(os);
+        printEmissionModelNone(os);
         break;
     case EmissionModelT::ASTRA:
-        PrintEmissionModelAstra(os);
+        printEmissionModelAstra(os);
         break;
     case EmissionModelT::NONEQUIL:
-        PrintEmissionModelNonEquil(os);
+        printEmissionModelNonEquil(os);
         break;
     default:
         break;
@@ -3502,21 +3506,21 @@ void Distribution::PrintEmissionModel(Inform &os) const {
 
 }
 
-void Distribution::PrintEmissionModelAstra(Inform &os) const {
+void Distribution::printEmissionModelAstra(Inform &os) const {
     os << "*  THERMAL EMITTANCE in ASTRA MODE" << endl;
     os << "*  Kinetic energy (thermal emittance) = "
        << std::abs(Attributes::getReal(itsAttr[AttributesT::EKIN]))
        << " [eV]  " << endl;
 }
 
-void Distribution::PrintEmissionModelNone(Inform &os) const {
+void Distribution::printEmissionModelNone(Inform &os) const {
     os << "*  THERMAL EMITTANCE in NONE MODE" << endl;
     os << "*  Kinetic energy added to longitudinal momentum = "
        << std::abs(Attributes::getReal(itsAttr[AttributesT::EKIN]))
        << " [eV]  " << endl;
 }
 
-void Distribution::PrintEmissionModelNonEquil(Inform &os) const {
+void Distribution::printEmissionModelNonEquil(Inform &os) const {
     os << "*  THERMAL EMITTANCE in NONEQUIL MODE" << endl;
     os << "*  Cathode work function     = " << cathodeWorkFunc_m << " [eV]  " << endl;
     os << "*  Cathode Fermi energy      = " << cathodeFermiEnergy_m << " [eV]  " << endl;
@@ -3524,7 +3528,7 @@ void Distribution::PrintEmissionModelNonEquil(Inform &os) const {
     os << "*  Photocathode laser energy = " << laserEnergy_m << " [eV]  " << endl;
 }
 
-void Distribution::PrintEnergyBins(Inform &os) const {
+void Distribution::printEnergyBins(Inform &os) const {
 
     os << "* " << endl;
     for (int binIndex = numberOfEnergyBins_m - 1; binIndex >=0; binIndex--) {
@@ -3553,7 +3557,7 @@ bool Distribution::Rebin() {
     }
 }
 
-void Distribution::ReflectDistribution(size_t &numberOfParticles) {
+void Distribution::reflectDistribution(size_t &numberOfParticles) {
 
     size_t currentNumPart = tOrZDist_m.size();
     for (size_t partIndex = 0; partIndex < currentNumPart; partIndex++) {
@@ -3568,7 +3572,7 @@ void Distribution::ReflectDistribution(size_t &numberOfParticles) {
     reduce(numberOfParticles, numberOfParticles, OpAddAssign());
 }
 
-void Distribution::ScaleDistCoordinates() {
+void Distribution::scaleDistCoordinates() {
 
     for (size_t particleIndex = 0; particleIndex < tOrZDist_m.size(); particleIndex++) {
         xDist_m.at(particleIndex) *= Attributes::getReal(itsAttr[AttributesT::XMULT]);
@@ -3585,7 +3589,7 @@ void Distribution::ScaleDistCoordinates() {
     }
 }
 
-void Distribution::SetAttributes() {
+void Distribution::setAttributes() {
     itsAttr[AttributesT::DISTRIBUTION]
         = Attributes::makeString("DISTRIBUTION","Distribution type: FROMFILE, "
                                  "GAUSS, "
@@ -3619,24 +3623,26 @@ void Distribution::SetAttributes() {
     itsAttr[AttributesT::MAXSTEPSSI]
         = Attributes::makeReal("MAXSTEPSSI", "Maximum steps used to find matched distribution ",2000);
     itsAttr[AttributesT::ORDERMAPS]
-      = Attributes::makeReal("ORDERMAPS", "Order used in the field expansion ", 7);
+        = Attributes::makeReal("ORDERMAPS", "Order used in the field expansion ", 7);
     itsAttr[AttributesT::MAGSYM]
-      = Attributes::makeReal("MAGSYM", "Number of sector magnets ", 0);
+        = Attributes::makeReal("MAGSYM", "Number of sector magnets ", 0);
+
     itsAttr[AttributesT::RGUESS]
-      = Attributes::makeReal("RGUESS", "Guess value of radius (m) for closed orbit finder ", -1);
+        = Attributes::makeReal("RGUESS", "Guess value of radius (m) for closed orbit finder ", -1);
+
 
     itsAttr[AttributesT::FNAME]
-      = Attributes::makeString("FNAME", "File for reading in 6D particle "
-			       "coordinates.", "");
+        = Attributes::makeString("FNAME", "File for reading in 6D particle "
+                                 "coordinates.", "");
 
 
     itsAttr[AttributesT::WRITETOFILE]
-      = Attributes::makeBool("WRITETOFILE", "Write initial distribution to file.",
-			     false);
+        = Attributes::makeBool("WRITETOFILE", "Write initial distribution to file.",
+                               false);
 
     itsAttr[AttributesT::WEIGHT]
-      = Attributes::makeReal("WEIGHT", "Weight of distribution when used in a "
-			     "distribution list.", 1.0);
+        = Attributes::makeReal("WEIGHT", "Weight of distribution when used in a "
+                               "distribution list.", 1.0);
 
     itsAttr[AttributesT::INPUTMOUNITS]
         = Attributes::makeString("INPUTMOUNITS", "Tell OPAL what input units are for momentum."
@@ -3962,7 +3968,7 @@ void Distribution::SetAttributes() {
         = Attributes::makeReal("DDY", "First derivative of DY.", 0.0);
 }
 
-void Distribution::SetFieldEmissionParameters() {
+void Distribution::setFieldEmissionParameters() {
 
     darkCurrentParts_m = static_cast<size_t> (Attributes::getReal(itsAttr[AttributesT::NPDARKCUR]));
     darkInwardMargin_m = Attributes::getReal(itsAttr[AttributesT::INWARDMARGIN]);
@@ -3982,13 +3988,13 @@ void Distribution::SetFieldEmissionParameters() {
 
 }
 
-void Distribution::SetDistToEmitted(bool emitted) {
+void Distribution::setDistToEmitted(bool emitted) {
     emitting_m = emitted;
 }
 
-void Distribution::SetDistType() {
+void Distribution::setDistType() {
 
-    distT_m = Attributes::getString(itsAttr[AttributesT::DISTRIBUTION]);
+    distT_m = Util::toUpper(Attributes::getString(itsAttr[AttributesT::DISTRIBUTION]));
     if (distT_m == "FROMFILE")
         distrTypeT_m = DistrTypeT::FROMFILE;
     else if(distT_m == "GAUSS")
@@ -4010,7 +4016,7 @@ void Distribution::SetDistType() {
 
 }
 
-void Distribution::SetEmissionTime(double &maxT, double &minT) {
+void Distribution::setEmissionTime(double &maxT, double &minT) {
 
     if (addedDistributions_m.size() == 0) {
 
@@ -4068,7 +4074,7 @@ void Distribution::SetEmissionTime(double &maxT, double &minT) {
     tBin_m = tEmission_m / numberOfEnergyBins_m;
 }
 
-void Distribution::SetDistParametersBinomial(double massIneV) {
+void Distribution::setDistParametersBinomial(double massIneV) {
 
     /*
      * Set Distribution parameters. Do all the necessary checks depending
@@ -4107,9 +4113,9 @@ void Distribution::SetDistParametersBinomial(double massIneV) {
     switch (inputMoUnits_m) {
 
     case InputMomentumUnitsT::EV:
-        sigmaP_m[0] = ConverteVToBetaGamma(sigmaP_m[0], massIneV);
-        sigmaP_m[1] = ConverteVToBetaGamma(sigmaP_m[1], massIneV);
-        sigmaP_m[2] = ConverteVToBetaGamma(sigmaP_m[2], massIneV);
+        sigmaP_m[0] = converteVToBetaGamma(sigmaP_m[0], massIneV);
+        sigmaP_m[1] = converteVToBetaGamma(sigmaP_m[1], massIneV);
+        sigmaP_m[2] = converteVToBetaGamma(sigmaP_m[2], massIneV);
         break;
 
     default:
@@ -4139,7 +4145,7 @@ void Distribution::SetDistParametersBinomial(double massIneV) {
     }
 }
 
-void Distribution::SetDistParametersFlattop(double massIneV) {
+void Distribution::setDistParametersFlattop(double massIneV) {
 
     /*
      * Set distribution parameters. Do all the necessary checks depending
@@ -4153,9 +4159,9 @@ void Distribution::SetDistParametersFlattop(double massIneV) {
     switch (inputMoUnits_m) {
 
     case InputMomentumUnitsT::EV:
-        sigmaP_m[0] = ConverteVToBetaGamma(sigmaP_m[0], massIneV);
-        sigmaP_m[1] = ConverteVToBetaGamma(sigmaP_m[1], massIneV);
-        sigmaP_m[2] = ConverteVToBetaGamma(sigmaP_m[2], massIneV);
+        sigmaP_m[0] = converteVToBetaGamma(sigmaP_m[0], massIneV);
+        sigmaP_m[1] = converteVToBetaGamma(sigmaP_m[1], massIneV);
+        sigmaP_m[2] = converteVToBetaGamma(sigmaP_m[2], massIneV);
         break;
 
     default:
@@ -4245,7 +4251,7 @@ void Distribution::SetDistParametersFlattop(double massIneV) {
 
 }
 
-void Distribution::SetDistParametersGauss(double massIneV) {
+void Distribution::setDistParametersGauss(double massIneV) {
 
     /*
      * Set distribution parameters. Do all the necessary checks depending
@@ -4276,9 +4282,9 @@ void Distribution::SetDistParametersGauss(double massIneV) {
         switch (inputMoUnits_m) {
 
         case InputMomentumUnitsT::EV:
-            sigmaP_m[0] = ConverteVToBetaGamma(sigmaP_m[0], massIneV);
-            sigmaP_m[1] = ConverteVToBetaGamma(sigmaP_m[1], massIneV);
-            sigmaP_m[2] = ConverteVToBetaGamma(sigmaP_m[2], massIneV);
+            sigmaP_m[0] = converteVToBetaGamma(sigmaP_m[0], massIneV);
+            sigmaP_m[1] = converteVToBetaGamma(sigmaP_m[1], massIneV);
+            sigmaP_m[2] = converteVToBetaGamma(sigmaP_m[2], massIneV);
             break;
 
         default:
@@ -4372,9 +4378,9 @@ void Distribution::SetDistParametersGauss(double massIneV) {
     }
 }
 
-void Distribution::SetupEmissionModel(PartBunch &beam) {
+void Distribution::setupEmissionModel(PartBunch &beam) {
 
-    std::string model = Attributes::getString(itsAttr[AttributesT::EMISSIONMODEL]);
+    std::string model = Util::toUpper(Attributes::getString(itsAttr[AttributesT::EMISSIONMODEL]));
     if (model == "ASTRA")
         emissionModel_m = EmissionModelT::ASTRA;
     else if (model == "NONEQUIL")
@@ -4393,13 +4399,13 @@ void Distribution::SetupEmissionModel(PartBunch &beam) {
     switch (emissionModel_m) {
 
     case EmissionModelT::NONE:
-        SetupEmissionModelNone(beam);
+        setupEmissionModelNone(beam);
         break;
     case EmissionModelT::ASTRA:
-        SetupEmissionModelAstra(beam);
+        setupEmissionModelAstra(beam);
         break;
     case EmissionModelT::NONEQUIL:
-        SetupEmissionModelNonEquil();
+        setupEmissionModelNonEquil();
         break;
     default:
         break;
@@ -4407,29 +4413,27 @@ void Distribution::SetupEmissionModel(PartBunch &beam) {
 
 }
 
-void Distribution::SetupEmissionModelAstra(PartBunch &beam) {
+void Distribution::setupEmissionModelAstra(PartBunch &beam) {
 
     double wThermal = std::abs(Attributes::getReal(itsAttr[AttributesT::EKIN]));
-    pTotThermal_m = ConverteVToBetaGamma(wThermal, beam.getM());
+    pTotThermal_m = converteVToBetaGamma(wThermal, beam.getM());
     pmean_m = Vector_t(0.0, 0.0, 0.5 * pTotThermal_m);
-
-    gsl_rng_env_setup();
-    randGenEmit_m = gsl_rng_alloc(gsl_rng_default);
 }
 
-void Distribution::SetupEmissionModelNone(PartBunch &beam) {
+void Distribution::setupEmissionModelNone(PartBunch &beam) {
 
     double wThermal = std::abs(Attributes::getReal(itsAttr[AttributesT::EKIN]));
-    pTotThermal_m = ConverteVToBetaGamma(wThermal, beam.getM());
+    pTotThermal_m = converteVToBetaGamma(wThermal, beam.getM());
     double avgPz = std::accumulate(pzDist_m.begin(), pzDist_m.end(), 0.0);
     size_t numParticles = pzDist_m.size();
     reduce(avgPz, avgPz, OpAddAssign());
     reduce(numParticles, numParticles, OpAddAssign());
+    avgPz /= numParticles;
 
-    pmean_m = Vector_t(0.0, 0.0, pTotThermal_m + avgPz / numParticles);
+    pmean_m = Vector_t(0.0, 0.0, pTotThermal_m + avgPz);
 }
 
-void Distribution::SetupEmissionModelNonEquil() {
+void Distribution::setupEmissionModelNonEquil() {
 
     cathodeWorkFunc_m = std::abs(Attributes::getReal(itsAttr[AttributesT::W]));
     laserEnergy_m = std::abs(Attributes::getReal(itsAttr[AttributesT::ELASER]));
@@ -4443,14 +4447,11 @@ void Distribution::SetupEmissionModelNonEquil() {
     emitEnergyUpperLimit_m = cathodeFermiEnergy_m
         + Physics::kB * cathodeTemp_m * log(1.0e9 - 1.0);
 
-    gsl_rng_env_setup();
-    randGenEmit_m = gsl_rng_alloc(gsl_rng_default);
-
     // TODO: get better estimate of pmean
     pmean_m = 0.5 * (cathodeWorkFunc_m + emitEnergyUpperLimit_m);
 }
 
-void Distribution::SetupEnergyBins(double maxTOrZ, double minTOrZ) {
+void Distribution::setupEnergyBins(double maxTOrZ, double minTOrZ) {
 
     energyBinHist_m = gsl_histogram_alloc(numberOfSampleBins_m * numberOfEnergyBins_m);
 
@@ -4461,7 +4462,7 @@ void Distribution::SetupEnergyBins(double maxTOrZ, double minTOrZ) {
 
 }
 
-void Distribution::SetupParticleBins(double massIneV, PartBunch &beam) {
+void Distribution::setupParticleBins(double massIneV, PartBunch &beam) {
 
     numberOfEnergyBins_m
         = static_cast<int>(std::abs(Attributes::getReal(itsAttr[AttributesT::NBIN])));
@@ -4490,7 +4491,7 @@ void Distribution::SetupParticleBins(double massIneV, PartBunch &beam) {
     }
 }
 
-void Distribution::ShiftBeam(double &maxTOrZ, double &minTOrZ) {
+void Distribution::shiftBeam(double &maxTOrZ, double &minTOrZ) {
 
     std::vector<double>::iterator tOrZIt;
     if (emitting_m) {
@@ -4528,18 +4529,27 @@ void Distribution::ShiftBeam(double &maxTOrZ, double &minTOrZ) {
         }
 
     } else {
-        if (minTOrZ < 0.0) {
-            for (tOrZIt = tOrZDist_m.begin(); tOrZIt != tOrZDist_m.end(); tOrZIt++)
-                *tOrZIt -= minTOrZ;
-            maxTOrZ -= minTOrZ;
-            minTOrZ -= minTOrZ;
-        }
+        double avgZ[] = {0.0, 1.0 * tOrZDist_m.size()};
+        for (tOrZIt = tOrZDist_m.begin(); tOrZIt != tOrZDist_m.end(); tOrZIt++)
+            avgZ[0] += *tOrZIt;
+
+        reduce(avgZ, avgZ + 2, avgZ, OpAddAssign());
+        avgZ[0] /= avgZ[1];
+
+        for (tOrZIt = tOrZDist_m.begin(); tOrZIt != tOrZDist_m.end(); tOrZIt++)
+            *tOrZIt -= avgZ[0];
     }
 
 }
 
-void Distribution::ShiftDistCoordinates(double massIneV) {
+double Distribution::getEmissionTimeShift() const {
+    if (emitting_m)
+        return Attributes::getReal(itsAttr[AttributesT::OFFSETT]);
+
+    return 0.0;
+}
 
+void Distribution::shiftDistCoordinates(double massIneV) {
     double deltaX = Attributes::getReal(itsAttr[AttributesT::OFFSETX]);
     double deltaY = Attributes::getReal(itsAttr[AttributesT::OFFSETY]);
 
@@ -4550,7 +4560,7 @@ void Distribution::ShiftDistCoordinates(double massIneV) {
      */
     double deltaTOrZ = Attributes::getReal(itsAttr[ LegacyAttributesT::T]);
     if (emitting_m)
-        deltaTOrZ = Attributes::getReal(itsAttr[AttributesT::OFFSETT]);
+        deltaTOrZ = 0.0;
     else {
         if (Attributes::getReal(itsAttr[AttributesT::OFFSETZ]) != 0.0)
             deltaTOrZ = Attributes::getReal(itsAttr[AttributesT::OFFSETZ]);
@@ -4566,9 +4576,9 @@ void Distribution::ShiftDistCoordinates(double massIneV) {
     // Check input momentum units.
     switch (inputMoUnits_m) {
     case InputMomentumUnitsT::EV:
-        deltaPx = ConverteVToBetaGamma(deltaPx, massIneV);
-        deltaPy = ConverteVToBetaGamma(deltaPy, massIneV);
-        deltaPz = ConverteVToBetaGamma(deltaPz, massIneV);
+        deltaPx = converteVToBetaGamma(deltaPx, massIneV);
+        deltaPy = converteVToBetaGamma(deltaPy, massIneV);
+        deltaPz = converteVToBetaGamma(deltaPz, massIneV);
         break;
     default:
         break;
@@ -4584,17 +4594,20 @@ void Distribution::ShiftDistCoordinates(double massIneV) {
     }
 }
 
-void Distribution::WriteOutFileHeader() {
+void Distribution::writeOutFileHeader() {
 
     if (Attributes::getBool(itsAttr[AttributesT::WRITETOFILE])) {
 
+        unsigned int totalNum = tOrZDist_m.size();
+        reduce(totalNum, totalNum, OpAddAssign());
         if (Ippl::myNode() == 0) {
+            std::string fname = "data/" + OpalData::getInstance()->getInputBasename() + "_" + getOpalName() + ".dat";
             *gmsg << "* **********************************************************************************" << endl;
-            *gmsg << "* Write initial distribution to file \"data/distribution.data\"" << endl;
+            *gmsg << "* Write initial distribution to file \"" << fname << "\"" << endl;
             *gmsg << "* **********************************************************************************" << endl;
-            std::ofstream outputFile("data/distribution.data");
+            std::ofstream outputFile(fname);
             if (outputFile.bad()) {
-                *gmsg << "Unable to open output file \"data/distribution.data\"" << endl;
+                *gmsg << "Unable to open output file \"" << fname << "\"" << endl;
             } else {
                 outputFile.setf(std::ios::left);
                 outputFile << "# ";
@@ -4623,7 +4636,7 @@ void Distribution::WriteOutFileHeader() {
                     outputFile.width(17);
                     outputFile << "py [betay gamma]";
                     outputFile.width(17);
-                    outputFile << "t [s]";
+                    outputFile << "z [m]";
                     outputFile.width(17);
                     outputFile << "pz [betaz gamma]";
                     if (numberOfEnergyBins_m > 0) {
@@ -4631,6 +4644,8 @@ void Distribution::WriteOutFileHeader() {
                         outputFile << "Bin Number";
                     }
                     outputFile << std::endl;
+
+                    outputFile << "# " << totalNum << std::endl;
                 }
             }
             outputFile.close();
@@ -4638,93 +4653,118 @@ void Distribution::WriteOutFileHeader() {
     }
 }
 
-void Distribution::WriteOutFileEmission() {
+void Distribution::writeOutFileEmission() {
 
-    if (Attributes::getBool(itsAttr[AttributesT::WRITETOFILE])) {
+    if (!Attributes::getBool(itsAttr[AttributesT::WRITETOFILE])) {
+        xWrite_m.clear();
+        pxWrite_m.clear();
+        yWrite_m.clear();
+        pyWrite_m.clear();
+        tOrZWrite_m.clear();
+        pzWrite_m.clear();
+        binWrite_m.clear();
 
-        // Gather particles to be written onto node 0.
-        int currentNode = 1;
-        for (int nodeIndex = 1; nodeIndex < Ippl::getNodes(); nodeIndex++) {
+        return;
+    }
 
-            size_t numberOfParticles = 0;
-            if (Ippl::myNode() == currentNode) {
-                if (!xWrite_m.empty())
-                    numberOfParticles = xWrite_m.size();
-            }
-            reduce(numberOfParticles, numberOfParticles, OpAddAssign());
+    // Gather particles to be written onto node 0.
+    std::vector<char> msgbuf;
+    const size_t bitsPerParticle = (6 * sizeof(double) + sizeof(size_t));
+    size_t totalSendBits = xWrite_m.size() * bitsPerParticle;
 
-            for (size_t partIndex = 0; partIndex < numberOfParticles; partIndex++) {
-
-                double x = 0.0;
-                double px = 0.0;
-                double y = 0.0;
-                double py = 0.0;
-                double tOrZ = 0.0;
-                double pz = 0.0;
-                size_t bin = 0;
-                if (Ippl::myNode() == currentNode) {
-                    x = xWrite_m.at(partIndex);
-                    px = pxWrite_m.at(partIndex);
-                    y = yWrite_m.at(partIndex);
-                    py = pyWrite_m.at(partIndex);
-                    tOrZ = tOrZWrite_m.at(partIndex);
-                    pz = pzWrite_m.at(partIndex);
-                    bin = binWrite_m.at(partIndex);
-                }
-                reduce(x, x, OpAddAssign());
-                reduce(px, px, OpAddAssign());
-                reduce(y, y, OpAddAssign());
-                reduce(py, py, OpAddAssign());
-                reduce(tOrZ, tOrZ, OpAddAssign());
-                reduce(pz, pz, OpAddAssign());
-                reduce(bin, bin, OpAddAssign());
-
-                if (Ippl::myNode() == 0) {
-                    xWrite_m.push_back(x);
-                    pxWrite_m.push_back(px);
-                    yWrite_m.push_back(y);
-                    pyWrite_m.push_back(py);
-                    tOrZWrite_m.push_back(tOrZ);
-                    pzWrite_m.push_back(pz);
-                    binWrite_m.push_back(bin);
-                }
+    std::vector<long> numberOfBits(Ippl::getNodes(), 0);
+    numberOfBits[Ippl::myNode()] = totalSendBits;
 
+    if (Ippl::myNode() == 0) {
+        MPI_Reduce(MPI_IN_PLACE, &(numberOfBits[0]), Ippl::getNodes(), MPI_UNSIGNED_LONG, MPI_SUM, 0, Ippl::getComm());
+    } else {
+        MPI_Reduce(&(numberOfBits[0]), NULL, Ippl::getNodes(), MPI_UNSIGNED_LONG, MPI_SUM, 0, Ippl::getComm());
+    }
+
+    Ippl::Comm->barrier();
+    int tag = Ippl::Comm->next_tag(IPPL_APP_TAG2, IPPL_APP_CYCLE);
+    if (Ippl::myNode() > 0) {
+        if (totalSendBits > 0) {
+            msgbuf.reserve(totalSendBits);
+            const char *buffer;
+            for (size_t idx = 0; idx < xWrite_m.size(); ++ idx) {
+                buffer = reinterpret_cast<const char*>(&(xWrite_m[idx]));
+                msgbuf.insert(msgbuf.end(), buffer, buffer + sizeof(double));
+                buffer = reinterpret_cast<const char*>(&(pxWrite_m[idx]));
+                msgbuf.insert(msgbuf.end(), buffer, buffer + sizeof(double));
+                buffer = reinterpret_cast<const char*>(&(yWrite_m[idx]));
+                msgbuf.insert(msgbuf.end(), buffer, buffer + sizeof(double));
+                buffer = reinterpret_cast<const char*>(&(pyWrite_m[idx]));
+                msgbuf.insert(msgbuf.end(), buffer, buffer + sizeof(double));
+                buffer = reinterpret_cast<const char*>(&(tOrZWrite_m[idx]));
+                msgbuf.insert(msgbuf.end(), buffer, buffer + sizeof(double));
+                buffer = reinterpret_cast<const char*>(&(pzWrite_m[idx]));
+                msgbuf.insert(msgbuf.end(), buffer, buffer + sizeof(double));
+                buffer = reinterpret_cast<const char*>(&(binWrite_m[idx]));
+                msgbuf.insert(msgbuf.end(), buffer, buffer + sizeof(size_t));
             }
-            currentNode++;
+
+            Ippl::Comm->raw_send(&(msgbuf[0]), totalSendBits, 0, tag);
         }
+    } else {
+        std::string fname = "data/" + OpalData::getInstance()->getInputBasename() + "_" + getOpalName() + ".dat";
+        std::ofstream outputFile(fname, std::fstream::app);
+        if (outputFile.bad()) {
+            ERRORMSG(level1 << "Unable to write to file \"" << fname << "\"" << endl);
+            for (int node = 1; node < Ippl::getNodes(); ++ node) {
+                if (numberOfBits[node] == 0) continue;
+                char *recvbuf = new char[numberOfBits[node]];
+                Ippl::Comm->raw_receive(recvbuf, numberOfBits[node], node, tag);
+                delete[] recvbuf;
+            }
+        } else {
 
-        // Write to file only on node 0.
-        if (Ippl::myNode() == 0 && !xWrite_m.empty() > 0) {
-            std::ofstream outputFile("data/distribution.data", std::fstream::app);
-            if (outputFile.bad()) {
-                *gmsg << "Unable to write to file \"data/distribution.data\"" << endl;
-            } else {
+            outputFile.precision(9);
+            outputFile.setf(std::ios::scientific);
+            outputFile.setf(std::ios::right);
 
-                outputFile.precision(9);
-                outputFile.setf(std::ios::scientific);
-                outputFile.setf(std::ios::right);
-                for (size_t partIndex = 0; partIndex < xWrite_m.size(); partIndex++) {
+            for (size_t partIndex = 0; partIndex < xWrite_m.size(); partIndex++) {
 
-                    outputFile.width(17);
-                    outputFile << xWrite_m.at(partIndex);
-                    outputFile.width(17);
-                    outputFile << pxWrite_m.at(partIndex);
-                    outputFile.width(17);
-                    outputFile << yWrite_m.at(partIndex);
-                    outputFile.width(17);
-                    outputFile << pyWrite_m.at(partIndex);
-                    outputFile.width(17);
-                    outputFile << tOrZWrite_m.at(partIndex);
-                    outputFile.width(17);
-                    outputFile << pzWrite_m.at(partIndex);
-                    outputFile.width(17);
-                    outputFile << binWrite_m.at(partIndex) << std::endl;
+                outputFile << std::setw(17) << xWrite_m.at(partIndex)
+                           << std::setw(17) << pxWrite_m.at(partIndex)
+                           << std::setw(17) << yWrite_m.at(partIndex)
+                           << std::setw(17) << pyWrite_m.at(partIndex)
+                           << std::setw(17) << tOrZWrite_m.at(partIndex)
+                           << std::setw(17) << pzWrite_m.at(partIndex)
+                           << std::setw(17) << binWrite_m.at(partIndex) << std::endl;
+            }
 
+            int numSenders = 0;
+            for (int i = 1; i < Ippl::getNodes(); ++ i) {
+                if (numberOfBits[i] > 0) numSenders ++;
+            }
+
+            for (int i = 0; i < numSenders; ++ i) {
+                int node = Communicate::COMM_ANY_NODE;
+                char *recvbuf;
+                const int bufsize = Ippl::Comm->raw_probe_receive(recvbuf, node, tag);
+
+                int j = 0;
+                while (j < bufsize) {
+                    const double *dbuffer = reinterpret_cast<const double*>(recvbuf + j);
+                    const size_t *sbuffer = reinterpret_cast<const size_t*>(recvbuf + j + 6 * sizeof(double));
+                    outputFile << std::setw(17) << dbuffer[0]
+                               << std::setw(17) << dbuffer[1]
+                               << std::setw(17) << dbuffer[2]
+                               << std::setw(17) << dbuffer[3]
+                               << std::setw(17) << dbuffer[4]
+                               << std::setw(17) << dbuffer[5]
+                               << std::setw(17) << sbuffer[0]
+                               << std::endl;
+                    j += bitsPerParticle;
                 }
 
+                delete[] recvbuf;
+
             }
-            outputFile.close();
         }
+        outputFile.close();
+
     }
 
     // Clear write vectors.
@@ -4738,7 +4778,7 @@ void Distribution::WriteOutFileEmission() {
 
 }
 
-void Distribution::WriteOutFileInjection() {
+void Distribution::writeOutFileInjection() {
 
     if (Attributes::getBool(itsAttr[AttributesT::WRITETOFILE])) {
 
@@ -4748,12 +4788,11 @@ void Distribution::WriteOutFileInjection() {
             // Write to file if its our turn.
             size_t numberOfParticles = 0;
             if (Ippl::myNode() == nodeIndex) {
-
-                std::ofstream outputFile("data/distribution.data", std::fstream::app);
+                std::string fname = "data/" + OpalData::getInstance()->getInputBasename() + "_" + getOpalName() + ".dat";
+                std::ofstream outputFile(fname, std::fstream::app);
                 if (outputFile.bad()) {
-		     *gmsg << "Node " << Ippl::myNode()
-			   << " unable to write to file \"data/distribution.data\""
-			   << endl;
+                    *gmsg << "Node " << Ippl::myNode() << " unable to write"
+                          << "to file \"" << fname << "\"" << endl;
                 } else {
 
                     outputFile.precision(9);
@@ -4776,7 +4815,7 @@ void Distribution::WriteOutFileInjection() {
                         outputFile.width(17);
                         outputFile << pzDist_m.at(partIndex);
                         if (numberOfEnergyBins_m > 0) {
-                            size_t binNumber = FindEBin(tOrZDist_m.at(partIndex));
+                            size_t binNumber = findEBin(tOrZDist_m.at(partIndex));
                             outputFile.width(17);
                             outputFile << binNumber;
                         }
@@ -4797,4 +4836,4 @@ void Distribution::WriteOutFileInjection() {
 // mode:c
 // c-basic-offset: 4
 // indent-tabs-mode:nil
-// End:
+// End:
\ No newline at end of file
diff --git a/src/Distribution/Distribution.h b/src/Distribution/Distribution.h
index 92382bfb2727ace97544f3de283697d710ac6eed..a99e7dcc38921ca01ccf92271d930c66b99bca08 100644
--- a/src/Distribution/Distribution.h
+++ b/src/Distribution/Distribution.h
@@ -97,93 +97,95 @@ public:
     virtual void execute();
     virtual void update();
 
-    void CreateBoundaryGeometry(PartBunch &p, BoundaryGeometry &bg);
-    void CreateOpalCycl(PartBunch &beam,
+    void createBoundaryGeometry(PartBunch &p, BoundaryGeometry &bg);
+    void createOpalCycl(PartBunch &beam,
                         size_t numberOfParticles,
 			double current, const Beamline &bl,
                         bool scan);
-    void CreateOpalE(Beam *beam,
+    void createOpalE(Beam *beam,
                      std::vector<Distribution *> addedDistributions,
                      EnvelopeBunch *envelopeBunch,
                      double distCenter,
                      double Bz0);
-    void CreateOpalT(PartBunch &beam,
+    void createOpalT(PartBunch &beam,
                      std::vector<Distribution *> addedDistributions,
                      size_t &numberOfParticles,
                      bool scan);
-    void CreateOpalT(PartBunch &beam, size_t &numberOfParticles, bool scan);
-    void CreatePriPart(PartBunch *beam, BoundaryGeometry &bg);
-    void DoRestartOpalT(PartBunch &p, size_t Np, int restartStep, H5PartWrapper *h5wrapper);
-    void DoRestartOpalCycl(PartBunch &p, size_t Np, int restartStep,
+    void createOpalT(PartBunch &beam, size_t &numberOfParticles, bool scan);
+    void createPriPart(PartBunch *beam, BoundaryGeometry &bg);
+    void doRestartOpalT(PartBunch &p, size_t Np, int restartStep, H5PartWrapper *h5wrapper);
+    void doRestartOpalCycl(PartBunch &p, size_t Np, int restartStep,
                         const int specifiedNumBunch, H5PartWrapper *h5wrapper);
-    void DoRestartOpalE(EnvelopeBunch &p, size_t Np, int restartStep, H5PartWrapper *h5wrapper);
-    size_t EmitParticles(PartBunch &beam, double eZ);
+    void doRestartOpalE(EnvelopeBunch &p, size_t Np, int restartStep, H5PartWrapper *h5wrapper);
+    size_t emitParticles(PartBunch &beam, double eZ);
+    double getPercentageEmitted() const;
     static Distribution *find(const std::string &name);
 
-    void EraseXDist();
-    void EraseBGxDist();
-    void EraseYDist();
-    void EraseBGyDist();
-    void EraseTOrZDist();
-    void EraseBGzDist();
-    bool GetIfDistEmitting();
-    int GetLastEmittedEnergyBin();
-    double GetMaxTOrZ();
-    double GetMinTOrZ();
-    size_t GetNumberOfEmissionSteps();
-    int GetNumberOfEnergyBins();
-    double GetEmissionDeltaT();
-    double GetEnergyBinDeltaT();
-    double GetWeight();
-    std::vector<double>& GetXDist();
-    std::vector<double>& GetBGxDist();
-    std::vector<double>& GetYDist();
-    std::vector<double>& GetBGyDist();
-    std::vector<double>& GetTOrZDist();
-    std::vector<double>& GetBGzDist();
+    void eraseXDist();
+    void eraseBGxDist();
+    void eraseYDist();
+    void eraseBGyDist();
+    void eraseTOrZDist();
+    void eraseBGzDist();
+    bool getIfDistEmitting();
+    int getLastEmittedEnergyBin();
+    double getMaxTOrZ();
+    double getMinTOrZ();
+    size_t getNumberOfEmissionSteps();
+    int getNumberOfEnergyBins();
+    double getEmissionDeltaT();
+    double getEnergyBinDeltaT();
+    double getWeight();
+    std::vector<double>& getXDist();
+    std::vector<double>& getBGxDist();
+    std::vector<double>& getYDist();
+    std::vector<double>& getBGyDist();
+    std::vector<double>& getTOrZDist();
+    std::vector<double>& getBGzDist();
 
     /// Return the embedded CLASSIC PartData.
-    const PartData &GetReference() const;
-    double GetTEmission();
+    const PartData &getReference() const;
+    double getTEmission();
 
     Vector_t get_pmean() const;
-    double GetEkin() const;
-    double GetLaserEnergy() const;
-    double GetWorkFunctionRf() const;
-
-    size_t GetNumberOfDarkCurrentParticles();
-    double GetDarkCurrentParticlesInwardMargin();
-    double GetEInitThreshold();
-    double GetWorkFunction();
-    double GetFieldEnhancement();
-    size_t GetMaxFNemissionPartPerTri();
-    double GetFieldFNThreshold();
-    double GetFNParameterA();
-    double GetFNParameterB();
-    double GetFNParameterY();
-    double GetFNParameterVYZero();
-    double GetFNParameterVYSecond();
-    int    GetSecondaryEmissionFlag();
-    bool   GetEmissionMode() ;
-
-    std::string GetTypeofDistribution();
-
-    double GetvSeyZero();//return sey_0 in Vaughan's model
-    double GetvEZero();//return the energy related to sey_0 in Vaughan's model
-    double GetvSeyMax();//return sey max in Vaughan's model
-    double GetvEmax();//return Emax in Vaughan's model
-    double GetvKenergy();//return fitting parameter denotes the roughness of surface for impact energy in Vaughan's model
-    double GetvKtheta();//return fitting parameter denotes the roughness of surface for impact angle in Vaughan's model
-    double GetvVThermal();//return thermal velocity of Maxwellian distribution of secondaries in Vaughan's model
-    double GetVw();//return velocity scalar for parallel plate benchmark;
-    int GetSurfMaterial();//material type for Furman-Pivi's model 0 for copper, 1 for stainless steel
+    double getEkin() const;
+    double getLaserEnergy() const;
+    double getWorkFunctionRf() const;
+
+    size_t getNumberOfDarkCurrentParticles();
+    double getDarkCurrentParticlesInwardMargin();
+    double getEInitThreshold();
+    double getWorkFunction();
+    double getFieldEnhancement();
+    size_t getMaxFNemissionPartPerTri();
+    double getFieldFNThreshold();
+    double getFNParameterA();
+    double getFNParameterB();
+    double getFNParameterY();
+    double getFNParameterVYZero();
+    double getFNParameterVYSecond();
+    int    getSecondaryEmissionFlag();
+    bool   getEmissionMode() ;
+
+    std::string getTypeofDistribution();
+
+    double getvSeyZero();//return sey_0 in Vaughan's model
+    double getvEZero();//return the energy related to sey_0 in Vaughan's model
+    double getvSeyMax();//return sey max in Vaughan's model
+    double getvEmax();//return Emax in Vaughan's model
+    double getvKenergy();//return fitting parameter denotes the roughness of surface for impact energy in Vaughan's model
+    double getvKtheta();//return fitting parameter denotes the roughness of surface for impact angle in Vaughan's model
+    double getvVThermal();//return thermal velocity of Maxwellian distribution of secondaries in Vaughan's model
+    double getVw();//return velocity scalar for parallel plate benchmark;
+    int getSurfMaterial();//material type for Furman-Pivi's model 0 for copper, 1 for stainless steel
 
     Inform &printInfo(Inform &os) const;
 
     bool Rebin();
-    void SetDistToEmitted(bool emitted);
-    void SetDistType();
-    void ShiftBeam(double &maxTOrZ, double &minTOrZ);
+    void setDistToEmitted(bool emitted);
+    void setDistType();
+    void shiftBeam(double &maxTOrZ, double &minTOrZ);
+    double getEmissionTimeShift() const;
 
     // in case if OPAL-cycl in restart mode
     double GetBeGa() {return bega_m;}
@@ -199,6 +201,8 @@ public:
     bool GetPreviousH5Local() {return previousH5Local_m;}
 
     void setNumberOfDistributions(unsigned int n) { numberOfDistributions_m = n; }
+
+    DistrTypeT::DistrTypeT getType() const;
 private:
 #ifdef WITH_UNIT_TESTS
     FRIEND_TEST(GaussTest, FullSigmaTest1);
@@ -214,71 +218,71 @@ private:
 
     //    void printSigma(SigmaGenerator<double,unsigned int>::matrix_type& M, Inform& out);
 
-    void AddDistributions();
-    void ApplyEmissionModel(double eZ, double &px, double &py, double &pz, const std::vector<double> &additionalRNs);
-    void ApplyEmissModelAstra(double &px, double &py, double &pz, const std::vector<double> &additionalRNs);
-    void ApplyEmissModelNone(double &pz);
-    void ApplyEmissModelNonEquil(double eZ, double &px, double &py, double &pz);
-    void Create(size_t &numberOfParticles, double massIneV);
-    void CalcPartPerDist(size_t numberOfParticles);
-    void CheckEmissionParameters();
-    void CheckIfEmitted();
-    void CheckParticleNumber(size_t &numberOfParticles);
-    void ChooseInputMomentumUnits(InputMomentumUnitsT::InputMomentumUnitsT inputMoUnits);
-    double ConvertBetaGammaToeV(double valueInbega, double mass);
-    double ConverteVToBetaGamma(double valueIneV, double massIneV);
-    double ConvertMeVPerCToBetaGamma(double valueInMeVPerC, double massIneV);
-    void CreateDistributionBinomial(size_t numberOfParticles, double massIneV);
-    void CreateDistributionFlattop(size_t numberOfParticles, double massIneV);
-    void CreateDistributionFromFile(size_t numberOfParticles, double massIneV);
-    void CreateDistributionGauss(size_t numberOfParticles, double massIneV);
-    void CreateMatchedGaussDistribution(size_t numberOfParticles, double massIneV);
-    void DestroyBeam(PartBunch &beam);
-    void FillEBinHistogram();
-    void FillParticleBins();
-    size_t FindEBin(double tOrZ);
-    void GenerateAstraFlattopT(size_t numberOfParticles);
-    void GenerateBinomial(size_t numberOfParticles);
-    void GenerateFlattopLaserProfile(size_t numberOfParticles);
-    void GenerateFlattopT(size_t numberOfParticles);
-    void GenerateFlattopZ(size_t numberOfParticles);
-    void GenerateGaussZ(size_t numberOfParticles);
-    void GenerateLongFlattopT(size_t numberOfParticles);
-    void GenerateTransverseGauss(size_t numberOfParticles);
-    void InitializeBeam(PartBunch &beam);
-    void InjectBeam(PartBunch &beam);
-    void PrintDist(Inform &os, size_t numberOfParticles) const;
-    void PrintDistBinomial(Inform &os) const;
-    void PrintDistFlattop(Inform &os) const;
-    void PrintDistFromFile(Inform &os) const;
-    void PrintDistGauss(Inform &os) const;
-    void PrintDistMatchedGauss(Inform &os) const;
-    void PrintDistSurfEmission(Inform &os) const;
-    void PrintDistSurfAndCreate(Inform &os) const;
-    void PrintEmissionModel(Inform &os) const;
-    void PrintEmissionModelAstra(Inform &os) const;
-    void PrintEmissionModelNone(Inform &os) const;
-    void PrintEmissionModelNonEquil(Inform &os) const;
-    void PrintEnergyBins(Inform &os) const;
-    void ReflectDistribution(size_t &numberOfParticles);
-    void ScaleDistCoordinates();
-    void SetAttributes();
-    void SetDistParametersBinomial(double massIneV);
-    void SetDistParametersFlattop(double massIneV);
-    void SetDistParametersGauss(double massIneV);
-    void SetEmissionTime(double &maxT, double &minT);
-    void SetFieldEmissionParameters();
-    void SetupEmissionModel(PartBunch &beam);
-    void SetupEmissionModelAstra(PartBunch &beam);
-    void SetupEmissionModelNone(PartBunch &beam);
-    void SetupEmissionModelNonEquil();
-    void SetupEnergyBins(double maxTOrZ, double minTOrZ);
-    void SetupParticleBins(double massIneV, PartBunch &beam);
-    void ShiftDistCoordinates(double massIneV);
-    void WriteOutFileHeader();
-    void WriteOutFileEmission();
-    void WriteOutFileInjection();
-    void WriteToFile();
+    void addDistributions();
+    void applyEmissionModel(double eZ, double &px, double &py, double &pz, const std::vector<double> &additionalRNs);
+    void applyEmissModelAstra(double &px, double &py, double &pz, const std::vector<double> &additionalRNs);
+    void applyEmissModelNone(double &pz);
+    void applyEmissModelNonEquil(double eZ, double &px, double &py, double &pz);
+    void create(size_t &numberOfParticles, double massIneV);
+    void calcPartPerDist(size_t numberOfParticles);
+    void checkEmissionParameters();
+    void checkIfEmitted();
+    void checkParticleNumber(size_t &numberOfParticles);
+    void chooseInputMomentumUnits(InputMomentumUnitsT::InputMomentumUnitsT inputMoUnits);
+    double convertBetaGammaToeV(double valueInbega, double mass);
+    double converteVToBetaGamma(double valueIneV, double massIneV);
+    double convertMeVPerCToBetaGamma(double valueInMeVPerC, double massIneV);
+    void createDistributionBinomial(size_t numberOfParticles, double massIneV);
+    void createDistributionFlattop(size_t numberOfParticles, double massIneV);
+    void createDistributionFromFile(size_t numberOfParticles, double massIneV);
+    void createDistributionGauss(size_t numberOfParticles, double massIneV);
+    void createMatchedGaussDistribution(size_t numberOfParticles, double massIneV);
+    void destroyBeam(PartBunch &beam);
+    void fillEBinHistogram();
+    void fillParticleBins();
+    size_t findEBin(double tOrZ);
+    void generateAstraFlattopT(size_t numberOfParticles);
+    void generateBinomial(size_t numberOfParticles);
+    void generateFlattopLaserProfile(size_t numberOfParticles);
+    void generateFlattopT(size_t numberOfParticles);
+    void generateFlattopZ(size_t numberOfParticles);
+    void generateGaussZ(size_t numberOfParticles);
+    void generateLongFlattopT(size_t numberOfParticles);
+    void generateTransverseGauss(size_t numberOfParticles);
+    void initializeBeam(PartBunch &beam);
+    void injectBeam(PartBunch &beam);
+    void printDist(Inform &os, size_t numberOfParticles) const;
+    void printDistBinomial(Inform &os) const;
+    void printDistFlattop(Inform &os) const;
+    void printDistFromFile(Inform &os) const;
+    void printDistGauss(Inform &os) const;
+    void printDistMatchedGauss(Inform &os) const;
+    void printDistSurfEmission(Inform &os) const;
+    void printDistSurfAndCreate(Inform &os) const;
+    void printEmissionModel(Inform &os) const;
+    void printEmissionModelAstra(Inform &os) const;
+    void printEmissionModelNone(Inform &os) const;
+    void printEmissionModelNonEquil(Inform &os) const;
+    void printEnergyBins(Inform &os) const;
+    void reflectDistribution(size_t &numberOfParticles);
+    void scaleDistCoordinates();
+    void setAttributes();
+    void setDistParametersBinomial(double massIneV);
+    void setDistParametersFlattop(double massIneV);
+    void setDistParametersGauss(double massIneV);
+    void setEmissionTime(double &maxT, double &minT);
+    void setFieldEmissionParameters();
+    void setupEmissionModel(PartBunch &beam);
+    void setupEmissionModelAstra(PartBunch &beam);
+    void setupEmissionModelNone(PartBunch &beam);
+    void setupEmissionModelNonEquil();
+    void setupEnergyBins(double maxTOrZ, double minTOrZ);
+    void setupParticleBins(double massIneV, PartBunch &beam);
+    void shiftDistCoordinates(double massIneV);
+    void writeOutFileHeader();
+    void writeOutFileEmission();
+    void writeOutFileInjection();
+    void writeToFile();
 
     std::string distT_m;                 /// Distribution type. Declared as string
     DistrTypeT::DistrTypeT distrTypeT_m; /// and list type for switch statements.
@@ -318,8 +322,7 @@ private:
     gsl_histogram *energyBinHist_m; /// GSL histogram used to define energy bin
                                     /// structure.
 
-    gsl_rng *randGenEmit_m;         /// Random number generator for thermal emission
-                                    /// models.
+    gsl_rng *randGen_m;             /// Random number generator
 
     // ASTRA and NONE photo emission model.
     double pTotThermal_m;           /// Total thermal momentum.
@@ -334,6 +337,9 @@ private:
 
     std::vector<std::vector<double> > additionalRNs_m;
 
+    size_t totalNumberParticles_m;
+    size_t totalNumberEmittedParticles_m;
+
     // Beam coordinate containers.
     std::vector<double> xDist_m;
     std::vector<double> pxDist_m;
@@ -458,4 +464,13 @@ Vector_t Distribution::get_pmean() const {
     return pmean_m;
 }
 
+inline
+DistrTypeT::DistrTypeT Distribution::getType() const {
+    return distrTypeT_m;
+}
+
+inline double Distribution::getPercentageEmitted() const {
+    return (double)totalNumberEmittedParticles_m / (double)totalNumberParticles_m;
+}
+
 #endif // OPAL_Distribution_HH
\ No newline at end of file
diff --git a/src/Distribution/Harmonics.h b/src/Distribution/Harmonics.h
index 14dd64ad0087d64db506d724515d47d7cff55f60..11b53e3332b95f7e82360c770fa685e40fcfe7c5 100644
--- a/src/Distribution/Harmonics.h
+++ b/src/Distribution/Harmonics.h
@@ -529,9 +529,9 @@ typename Harmonics<Value_type, Size_type>::matrix_type Harmonics<Value_type, Siz
     M(1,0) = - s * fx / r;
     M(2,2) = M(3,3) = C;
     M(2,3) = S * r / fy;
-    
+
     value_type sign = (std::signbit(k)) ? value_type(-1) : value_type(1);
-    
+
     M(3,2) = sign * S * fy / r;
     M(4,5) = l / gam2 - r / (1.0 + k) * (phi - s / fx);
     M(4,0)= - (M(1,5) = s / fx);
diff --git a/src/Editor/CMakeLists.txt b/src/Editor/CMakeLists.txt
index a467f3d2df8d0a3bac4e04c9232424df67e3a8ba..69e1e0e5012fac5ec89531cc49785bf812cf0878 100644
--- a/src/Editor/CMakeLists.txt
+++ b/src/Editor/CMakeLists.txt
@@ -17,4 +17,21 @@ include_directories (
   ${CMAKE_CURRENT_SOURCE_DIR}
 )
 
-add_sources(${_SRCS})
+add_opal_sources(${_SRCS})
+
+set (HDRS
+    EditCmd.h
+    EditCycle.h
+    EditEnd.h
+    EditFlatten.h
+    Edit.h
+    EditInstall.h
+    EditMove.h
+    EditParser.h
+    EditReflect.h
+    EditRemove.h
+    EditReplace.h
+    EditSelect.h
+)
+
+install (FILES ${HDRS} DESTINATION "${CMAKE_INSTALL_PREFIX}/include/Editor")
\ No newline at end of file
diff --git a/src/Elements/CMakeLists.txt b/src/Elements/CMakeLists.txt
index aa2f17f50d98638c5d6aab2a299c588cf52b8d36..4590e64a7811101c23e1245ee4f9819918c168c6 100644
--- a/src/Elements/CMakeLists.txt
+++ b/src/Elements/CMakeLists.txt
@@ -29,6 +29,7 @@ set (_SRCS
   OpalPolynomialTimeDependence.cpp
   OpalQuadrupole.cpp
   OpalRBend.cpp
+  OpalRBend3D.cpp
   OpalRCollimator.cpp
   OpalRingDefinition.cpp
   OpalSBend.cpp
@@ -38,6 +39,7 @@ set (_SRCS
   OpalSextupole.cpp
   OpalSlit.cpp
   OpalSolenoid.cpp
+  OpalSource.cpp
   OpalSRot.cpp
   OpalVariableRFCavity.cpp
   OpalVKicker.cpp
@@ -54,4 +56,60 @@ include_directories (
   ${CMAKE_CURRENT_SOURCE_DIR}
 )
 
-add_sources(${_SRCS})
+add_opal_sources(${_SRCS})
+
+set (HDRS
+    AttCell.h
+    OpalBeamBeam3D.h
+    OpalBeamBeam.h
+    OpalBeamline.h
+    OpalBend.h
+    OpalCavity.h
+    OpalCCollimator.h
+    OpalCyclotron.h
+    OpalCyclotronValley.h
+    OpalDegrader.h
+    OpalDrift.h
+    OpalECollimator.h
+    OpalElement.h
+    OpalHKicker.h
+    OpalHMonitor.h
+    OpalInstrument.h
+    OpalKicker.h
+    OpalMarker.h
+    OpalMonitor.h
+    OpalMultipole.h
+    OpalOctupole.h
+    OpalParallelPlate.h
+    OpalPatch.h
+    OpalPepperPot.h
+    OpalPolynomialTimeDependence.h
+    OpalProbe.h
+    OpalQuadrupole.h
+    OpalRBend.h
+    OpalRBend3D.h
+    OpalRCollimator.h
+    OpalRingDefinition.h
+    OpalSBend3D.h
+    OpalSBend.h
+    OpalSeparator.h
+    OpalSeptum.h
+    OpalSextupole.h
+    OpalSlit.h
+    OpalSolenoid.h
+    OpalSource.h
+    OpalSRot.h
+    OpalStripper.h
+    OpalTravelingWave.h
+    OpalVariableRFCavity.h
+    OpalVKicker.h
+    OpalVMonitor.h
+    OpalWire.h
+    OpalYRot.h
+    OpalOffset/OpalGlobalCartesianOffset.h
+    OpalOffset/OpalGlobalCylindricalOffset.h
+    OpalOffset/OpalLocalCartesianOffset.h
+    OpalOffset/OpalLocalCylindricalOffset.h
+)
+
+install (FILES ${HDRS} DESTINATION "${CMAKE_INSTALL_PREFIX}/include/Elements/OpalOffset")
\ No newline at end of file
diff --git a/src/Elements/OpalBeamline.cpp b/src/Elements/OpalBeamline.cpp
index 4032c552f32f64c6aaca4723738e3a586df5fa20..ce90f6fa5319c9f480e2bec391613a49d8ae33e5 100644
--- a/src/Elements/OpalBeamline.cpp
+++ b/src/Elements/OpalBeamline.cpp
@@ -1,316 +1,108 @@
 #include "Elements/OpalBeamline.h"
 #include "Utilities/OpalException.h"
-
+#include "Utilities/Options.h"
+#include "Utilities/Util.h"
+#include "AbstractObjects/OpalData.h"
+#include "AbsBeamline/Bend.h"
+#include "Structure/MeshGenerator.h"
+
+#include <boost/filesystem.hpp>
+#include <boost/regex.hpp>
+#include <fstream>
+#include <regex>
 using namespace std;
 
 extern Inform *gmsg;
 
 OpalBeamline::OpalBeamline():
-    sections_m(),
     elements_m(),
     prepared_m(false),
-    online_secs_m(NULL)
+    containsSource_m(false)
+{
+}
+
+OpalBeamline::OpalBeamline(const Vector_t& origin,
+                           const Quaternion& coordTransformationTo):
+    elements_m(),
+    prepared_m(false),
+    containsSource_m(false),
+    coordTransformationTo_m(origin, coordTransformationTo)
 {
-    online_sections_m = new int[5 * Ippl::getNodes()];
-    // This is needed to communicate across the nodes which sections are online. We should allocate memory to store
-    // (# of nodes) * (max # of sections which are online) integers.
-    // While we know the first number the second depends on many things. It is *ASSUMED* that the bunch isn't ever
-    // in more than 5 sections at the same time. Though it might be that this assumption is wrong. Then the
-    // the communication between the nodes has to be adjusted to a scheme which works always or by using any higher
-    // number.
 }
 
 OpalBeamline::~OpalBeamline() {
     elements_m.clear();
-    sections_m.clear();
-    delete[] online_sections_m;
-    if(online_secs_m)
-        delete[] online_secs_m;
 }
 
 CompVec OpalBeamline::dummy_list_m = CompVec();
 OpalSection OpalBeamline::dummy_section_m = OpalSection(dummy_list_m, 0., 0.);
 
-CompVec &OpalBeamline::getPredecessors(std::shared_ptr<const Component> element) {
-    size_t index;
-    bool found = false;
-    for(index = 0; index < sections_m.size(); ++ index) {
-        if(sections_m[index].find(element)) {
-            found = true;
-            break;
-        }
-    }
-
-    if(found && index > 0) {
-        return sections_m[index - 1].getElements();
-    } else {
-        if(dummy_list_m.size() != 0) {
-            dummy_list_m.erase(dummy_list_m.begin(), dummy_list_m.end());
-        }
-        return dummy_list_m;
-    }
-
-}
-
-CompVec &OpalBeamline::getSuccessors(std::shared_ptr<const Component> element) {
-    size_t index;
-    bool found = false;
-
-    if (sections_m.size() == 0)
-        return dummy_list_m;
+std::set<std::shared_ptr<Component>> OpalBeamline::getElements(const Vector_t &x) {
+    std::set<std::shared_ptr<Component> > elementSet;
+    FieldList::iterator it = elements_m.begin();
+    const FieldList::iterator end = elements_m.end();
+    for (; it != end; ++ it) {
+        std::shared_ptr<Component> element = (*it).getElement();
+        Vector_t r = (*it).getCoordTransformationTo().transformTo(x);
 
-    if (element == NULL)
-        return sections_m[0].getElements();
-
-    for(index = 0; index < sections_m.size(); ++ index) {
-        if(sections_m[index].find(element)) {
-            found = true;
-            break;
-        }
-    }
-
-    if(found && index + 1 < sections_m.size()) {
-        return sections_m[index + 1].getElements();
-    } else {
-        if(dummy_list_m.size() != 0) {
-            dummy_list_m.erase(dummy_list_m.begin(), dummy_list_m.end());
+        if (element->isInside(r)) {
+            elementSet.insert(element);
         }
-        return dummy_list_m;
     }
-}
-
-OpalSection &OpalBeamline::getSectionAt(const Vector_t &pos, long &sectionIndex) {
-    if(sectionIndex >= (long) sections_m.size()) sectionIndex = static_cast<long>(sections_m.size()) - 1;
-
-    if(prepared_m) {
-        if(pos(2) < sections_m[0].getStart(pos(0), pos(1))) return dummy_section_m;
-        if(pos(2) > sections_m.back().getEnd(pos(0), pos(1))) {
-            sectionIndex = BEAMLINE_EOL;
-            return dummy_section_m;
-        }
-        if(sectionIndex == -1) sectionIndex = sections_m.size() - 1;
 
-        while(pos(2) < sections_m[sectionIndex].getStart(pos(0), pos(1))) --sectionIndex;
-        while(pos(2) > sections_m[sectionIndex].getEnd(pos(0), pos(1))) ++sectionIndex;
-
-        if(pos(2) >= sections_m[sectionIndex].getStart(pos(0), pos(1)) &&
-           pos(2) <= sections_m[sectionIndex].getEnd(pos(0), pos(1))) return sections_m[sectionIndex];
-
-        return dummy_section_m;
-    }
-    *gmsg << "** WARNING *************************************\n"
-          << "in OpalBeamline::getSectionAt(): section list not prepared\n"
-          << "************************************************" << endl;
-    return dummy_section_m;
-}
-
-OpalSection &OpalBeamline::getSection(const unsigned int &index) {
-    if(index < sections_m.size()) {
-        return sections_m[index];
-    }
-
-    return dummy_section_m;
-}
-
-void OpalBeamline::getSectionIndexAt(const Vector_t &pos, long &initial_guess) const {
-    if(initial_guess > -1 && (size_t) initial_guess >= sections_m.size()) initial_guess = static_cast<long>(sections_m.size()) - 1;
-
-    if(prepared_m) {
-        if (sections_m.size() == 0) return;
-
-        if(initial_guess == -1 && pos(2) > sections_m[0].getStart(pos(0), pos(1)))
-            initial_guess = 0;
-
-        if(initial_guess > -1) {
-            if(pos(2) < sections_m[initial_guess].getStart(pos(0), pos(1))) {
-                do {
-                    -- initial_guess;
-                } while(initial_guess > -1 && pos(2) < sections_m[initial_guess].getEnd(pos(0), pos(1)));
-                ++ initial_guess;
-            } else {
-                while(initial_guess < (long) sections_m.size() && pos(2) > sections_m[initial_guess].getEnd(pos(0), pos(1))) {
-                    ++ initial_guess;
-                }
-                if(pos(2) > sections_m.back().getEnd(pos(0), pos(1))) {
-                    initial_guess = BEAMLINE_EOL;
-                } else {
-                    if(pos(2) < sections_m[initial_guess].getStart(pos(0), pos(1))) {
-                        -- initial_guess;
-                    }
-                }
-            }
-        }
-        return;
-    }
-    *gmsg << "** WARNING *************************************\n"
-          << "in OpalBeamline::getSectionIndexAt(): section list not prepared\n"
-          << "************************************************" << endl;
+    return elementSet;
 }
 
 void OpalBeamline::getKFactors(const unsigned int &index, const Vector_t &pos, const long &sindex, const double &t, Vector_t &KR, Vector_t &KT) {
 
-    if(sindex > -1 && (size_t) sindex < sections_m.size()) {
-        OpalSection &section = getSection(sindex);
-        setStatus(sindex, true);
-        if(pos(2) >= section.getStart(pos(0), pos(1)) && pos(2) < section.getEnd(pos(0), pos(1))) {
-            const CompVec &elements = section.getElements();
-            for(CompVec::const_iterator elit = elements.begin(); elit != elements.end(); elit++) {
-                (*elit)->addKR(index, t, KR);
-                (*elit)->addKT(index, t, KT);
-            }
-        }
-    }
 }
 
 unsigned long OpalBeamline::getFieldAt(const unsigned int &index, const Vector_t &pos, const long &sindex, const double &t, Vector_t &E, Vector_t &B) {
 
-    /*
-      If one uses static rtv has
-      after the first particles enters the Collimator
-      always 16384
-
-      static unsigned int rtv = 0x00;
-     */
-
-    if(sindex >= (long) sections_m.size()) return BEAMLINE_EOL;
-    if(sindex < 0) return 0x00;
-
     unsigned long rtv = 0x00;
 
-    B = Vector_t(0.0);
-    E = Vector_t(0.0);
-
-    OpalSection &section = getSection(sindex);
-    setStatus(sindex, true);
-    if(pos(2) < section.getStart(pos(0), pos(1)) || pos(2) > section.getEnd(pos(0), pos(1))) return 0x00;
-
-    const CompVec &elements = section.getElements();
-    for(CompVec::const_iterator elit = elements.begin(); elit != elements.end(); ++ elit) {
-        if((*elit)->apply(index, t, E, B)) {
-            return BEAMLINE_OOB;
-        }
-    }
-
-    const Vector_t &ori = section.getOrientation();
-    if(fabs(ori(0)) > 1.e-10 || fabs(ori(1)) > 1.e-10 || fabs(ori(2)) > 1.e-10) {
+    return rtv;
+}
 
-        // Rotate field out of the element's local coordinate system and back to lab frame.
-        //
-        // 1) Rotate about the x axis by angle -ori(1).
-        // 2) Rotate about the y axis by angle ori(0).
-        // 3) Rotate about the z axis by angle ori(3).
+unsigned long OpalBeamline::getFieldAt(const Vector_t &position,
+                                       const Vector_t &momentum,
+                                       const double &t,
+                                       Vector_t &Ef,
+                                       Vector_t &Bf) {
+    unsigned long rtv = 0x00;
 
-        // Tenzor<double, 3> rota(cos(ori(0)), 0, sin(ori(0)), 0, 1, 0, -sin(ori(0)), 0, cos(ori(0)));
-        // Tenzor<double, 3> rotb(1, 0, 0, 0, cos(ori(1)), sin(ori(1)), 0, -sin(ori(1)), cos(ori(1)));
-        // Tenzor<double, 3> rotc(cos(ori(2)), -sin(ori(2)), 0, sin(ori(2)), cos(ori(2)), 0, 0, 0, 1);
+    std::set<std::shared_ptr<Component>> elements = getElements(position);
 
-        // Tenzor<double, 3> orientation = dot(rotc, dot(rota, rotb));
-        // E = dot(orientation, E);
-        // B = dot(orientation, B);
+    std::set<std::shared_ptr<Component>>::const_iterator it = elements.begin();
+    const std::set<std::shared_ptr<Component>>::const_iterator end = elements.end();
 
-        const  double sina = sin(ori(0)),
-                      cosa = cos(ori(0)),
-                      sinb = sin(ori(1)),
-                      cosb = cos(ori(1)),
-                      sinc = sin(ori(2)),
-                      cosc = cos(ori(2));
+    for (; it != end; ++ it) {
+        ElementBase::ElementType type = (*it)->getType();
+        if (type == ElementBase::MONITOR ||
+            type == ElementBase::MARKER ||
+            type == ElementBase::COLLIMATOR ||
+            type == ElementBase::DIAGNOSTIC) continue;
 
-        Vector_t temp = E;
+        Vector_t localR = transformToLocalCS(*it, position);
+        Vector_t localP = rotateToLocalCS(*it, momentum);
+        Vector_t localE(0.0), localB(0.0);
 
-        E(0) =  cosa * cosc * temp(0) + (-sina * sinb * cosc - cosb * sinc) * temp(1) + (sina * cosb * cosc - sinb * sinc) * temp(2);
-        E(1) =  cosa * sinc * temp(0) + (-sina * sinb * sinc + cosb * cosc) * temp(1) + (sina * cosb * sinc + sinb * cosc) * temp(2);
-        E(2) = -sina *        temp(0) + (-cosa * sinb) * temp(1) + (cosa * cosb) * temp(2);
-        temp = B;
-        B(0) =  cosa * cosc * temp(0) + (-sina * sinb * cosc - cosb * sinc) * temp(1) + (sina * cosb * cosc - sinb * sinc) * temp(2);
-        B(1) =  cosa * sinc * temp(0) + (-sina * sinb * sinc + cosb * cosc) * temp(1) + (sina * cosb * sinc + sinb * cosc) * temp(2);
-        B(2) = -sina *        temp(0) + (-cosa * sinb) * temp(1) + (cosa * cosb) * temp(2);
+        (*it)->applyToReferenceParticle(localR, localP, t, localE, localB);
 
+        Ef += rotateFromLocalCS(*it, localE);
+        Bf += rotateFromLocalCS(*it, localB);
     }
 
-    if(section.doesBend()) {
-        rtv |= BEAMLINE_BEND;
-    }
-    if(section.hasWake()) {
-        rtv |= BEAMLINE_WAKE;
-    }
-    if(section.hasSurfacePhysics()) {
-        rtv |= BEAMLINE_SURFACEPHYSICS;
-    }
+    //         if(section.hasWake()) {
+    //             rtv |= BEAMLINE_WAKE;
+    //         }
+    //         if(section.hasSurfacePhysics()) {
+    //             rtv |= BEAMLINE_SURFACEPHYSICS;
+    //         }
 
     return rtv;
 }
 
-unsigned long OpalBeamline::getFieldAt(const Vector_t &pos, const Vector_t &centroid, const double &t, Vector_t &E, Vector_t &B) {
-    unsigned long rtv = 0x00;
-
-    long initial_guess = -1;
-    B = Vector_t(0.0);
-    E = Vector_t(0.0);
-
-    OpalSection &section = getSectionAt(pos, initial_guess);
-    if(!(initial_guess & BEAMLINE_EOL || initial_guess < 0)) {
-        unsigned int ini_guess = initial_guess;
-        setStatus(ini_guess, true);
-
-        if(pos(2) >= section.getStart(pos(0), pos(1)) && pos(2) <= section.getEnd(pos(0), pos(1))) {
-            const CompVec &elements = section.getElements();
-            for(CompVec::const_iterator elit = elements.begin(); elit != elements.end(); ++ elit) {
-                if((*elit)->apply(pos, centroid, t, E, B)) {
-
-                    rtv |= BEAMLINE_OOB;
-                }
-            }
-            if(! (rtv & BEAMLINE_OOB)) {
-
-                const Vector_t &ori = section.getOrientation();
-                if(fabs(ori(0)) > 1.e-10 || fabs(ori(1)) > 1.e-10 || fabs(ori(2)) > 1.e-10) {
-
-                    // Rotate field out of the element's local coordinate system and back to lab frame.
-                    //
-                    // 1) Rotate about the x axis by angle ori(1).
-                    // 2) Rotate about the y axis by angle ori(0).
-                    // 3) Rotate about the z axis by angle negative ori(3).
-
-                    const  double sina = sin(ori(0)),
-                                  cosa = cos(ori(0)),
-                                  sinb = sin(ori(1)),
-                                  cosb = cos(ori(1)),
-                                  sinc = sin(ori(2)),
-                                  cosc = cos(ori(2));
-
-                    Vector_t temp = E;
-
-                    E(0) =  cosa * cosc * temp(0) + (-sina * sinb * cosc - cosb * sinc) * temp(1) + (sina * cosb * cosc - sinb * sinc) * temp(2);
-                    E(1) =  cosa * sinc * temp(0) + (-sina * sinb * sinc + cosb * cosc) * temp(1) + (sina * cosb * sinc + sinb * cosc) * temp(2);
-                    E(2) = -sina *        temp(0) + (-cosa * sinb) * temp(1) + (cosa * cosb) * temp(2);
-                    temp = B;
-                    B(0) =  cosa * cosc * temp(0) + (-sina * sinb * cosc - cosb * sinc) * temp(1) + (sina * cosb * cosc - sinb * sinc) * temp(2);
-                    B(1) =  cosa * sinc * temp(0) + (-sina * sinb * sinc + cosb * cosc) * temp(1) + (sina * cosb * sinc + sinb * cosc) * temp(2);
-                    B(2) = -sina *        temp(0) + (-cosa * sinb) * temp(1) + (cosa * cosb) * temp(2);
-                }
-            }
-            if(section.doesBend()) {
-                rtv |= BEAMLINE_BEND;
-            }
-            if(section.hasWake()) {
-                rtv |= BEAMLINE_WAKE;
-            }
-            if(section.hasSurfacePhysics()) {
-                rtv |= BEAMLINE_SURFACEPHYSICS;
-            }
-
-            return rtv;
-        }
-        return 0x00;
-    } else {
-        if(initial_guess > -1) {
-            return BEAMLINE_EOL;
-        }
-        return 0x00;
-    }
-}
-
-
 void OpalBeamline::switchElements(const double &min, const double &max, const double &kineticEnergy, const bool &nomonitors) {
 
     FieldList::iterator fprev;
@@ -326,27 +118,21 @@ void OpalBeamline::switchElements(const double &min, const double &max, const do
             }
 
         } else {
-	  if(!(*flit).isOn() && max > (*flit).getStart() && min < (*flit).getEnd()) {
+            if(!(*flit).isOn() && max > (*flit).getStart() && min < (*flit).getEnd()) {
                 (*flit).setOn(kineticEnergy);
             }
 
-	  //check if multiple degraders follow one another with no other elements in between
-	  //if element is off and it is a degrader
-	  if (!(*flit).isOn() && flit->getElement()->getType() == ElementBase::DEGRADER) {
-	    //check if previous element: is on, is a degrader, ends where new element starts
-	    if ( (*fprev).isOn() && fprev->getElement()->getType() == ElementBase::DEGRADER 
-		 && ((*fprev).getEnd() + 0.01 > (*flit).getStart()) )
-	      {
-		(*flit).setOn(kineticEnergy);
-	      }
-	  }
+            //check if multiple degraders follow one another with no other elements in between
+            //if element is off and it is a degrader
+            if (!(*flit).isOn() && flit->getElement()->getType() == ElementBase::DEGRADER) {
+                //check if previous element: is on, is a degrader, ends where new element starts
+                if ((*fprev).isOn() && fprev->getElement()->getType() == ElementBase::DEGRADER &&
+                    ((*fprev).getEnd() + 0.01 > (*flit).getStart()) ) {
+                    (*flit).setOn(kineticEnergy);
+                }
+            }
         }
-        /////////////////////////
-        // does not work like that
-        //         if (min > (*flit).getEnd()) {
-        //             (*flit).setOff();
-        //         }
-        /////////////////////////
+
 	fprev = flit;
     }
 }
@@ -384,163 +170,602 @@ void OpalBeamline::switchElementsOff() {
 }
 
 void OpalBeamline::prepareSections() {
-    list<double> start_end;
-    CompVec tmp;
-    FieldList::iterator flit;
-    list<double>::iterator pos_it, next_it, last_it;
-    const double tolerance = 1.e-5;
-
     if (elements_m.size() == 0) {
         prepared_m = true;
         return;
     }
+    prepared_m = true;
+}
+
+void OpalBeamline::print(Inform &msg) const {
+}
 
-    /* there might be elements with length zero or extremely short ones.
-       we delete them such that they don't appear in the simulation
-     */
-    elements_m.sort(ClassicField::SortAsc);
-    for(flit = elements_m.begin();  flit != elements_m.end(); ++ flit) {
-        while(flit != elements_m.end() && (*flit).getLength() < tolerance) {
-            FieldList::iterator temp = flit;
-            ++temp;
-            elements_m.erase(flit);
-            flit = temp;
-        }
-        if(flit != elements_m.end()) {
-            start_end.push_back((*flit).getStart());
-            start_end.push_back((*flit).getEnd());
-        }
-    }
-    start_end.sort();
 
-    if(start_end.size() == 0) {
-        throw OpalException("OpalBeamline::prepareSections",
-                            "no valid elements found");
+double OpalBeamline::calcBeamlineLength() {
+    return 0.0;
+}
+
+void OpalBeamline::swap(OpalBeamline & rhs) {
+    std::swap(elements_m, rhs.elements_m);
+    std::swap(prepared_m, rhs.prepared_m);
+    std::swap(coordTransformationTo_m, rhs.coordTransformationTo_m);
+}
+
+void OpalBeamline::merge(OpalBeamline &rhs) {
+    elements_m.insert(elements_m.end(),
+                      rhs.elements_m.begin(),
+                      rhs.elements_m.end());
+    prepared_m = false;
+    containsSource_m = containsSource_m || rhs.containsSource_m;
+}
+
+
+FieldList OpalBeamline::getElementByType(ElementBase::ElementType type) {
+    if (type == ElementBase::ANY) {
+        return elements_m;
     }
 
-    next_it = start_end.begin();
-    ++next_it;
-    for(pos_it = start_end.begin(); next_it != start_end.end(); ++ pos_it, ++ next_it) {
-        if(*next_it - *pos_it < tolerance) {
-            *next_it = *pos_it;
+    FieldList elements_of_requested_type;
+    for(FieldList::iterator fit = elements_m.begin(); fit != elements_m.end(); ++ fit) {
+        if((*fit).getElement()->getType() == type) {
+            elements_of_requested_type.push_back((*fit));
         }
     }
+    return elements_of_requested_type;
+}
 
-    start_end.unique();  // remove duplicate entries
-
-    next_it = start_end.begin();
-    ++next_it;
-    for(pos_it = start_end.begin(); next_it != start_end.end(); ++ pos_it, ++ next_it) {
-        tmp.clear();
-        for(flit = elements_m.begin(); flit != elements_m.end(); ++ flit) {
-            if((*flit).getStart() <= *pos_it  + tolerance && (*flit).getEnd()   >= *next_it - tolerance) {
-                tmp.push_back((*flit).getElement());
-            } else {
-                if((*flit).getStart() >= *next_it) {
-                    break;
+void OpalBeamline::compute3DLattice() {
+    static unsigned int order = 0;
+    FieldList::iterator it = elements_m.begin();
+    const FieldList::iterator end = elements_m.end();
+
+    unsigned int minOrder = order;
+    {
+        double endPriorPathLength = 0.0;
+        CoordinateSystemTrafo currentCoordTrafo = coordTransformationTo_m;
+
+        elements_m.sort([](const ClassicField& a, const ClassicField& b) {
+                double edgeA = a.getElement()->getAttribute("ELEMEDGE");
+                double edgeB = b.getElement()->getAttribute("ELEMEDGE");
+
+                return edgeA < edgeB;
+            });
+        it = elements_m.begin();
+        for (; it != end; ++ it) {
+            if ((*it).isPositioned()) {
+                continue;
+            }
+            (*it).order_m = minOrder;
+            std::shared_ptr<Component> element = (*it).getElement();
+            if (element->getType() == ElementBase::SBEND ||
+                element->getType() == ElementBase::RBEND ||
+                element->getType() == ElementBase::RBEND3D) {
+
+                double beginThisPathLength = element->getAttribute("ELEMEDGE");
+                Vector_t beginThis3D(0, 0, beginThisPathLength - endPriorPathLength);
+                BendBase * bendElement = static_cast<BendBase*>(element.get());
+                double thisLength = bendElement->getChordLength();
+                double bendAngle = bendElement->getBendAngle();
+                double entranceAngle = bendElement->getEntranceAngle();
+                double arcLength = (thisLength * std::abs(bendAngle) / (2 * sin(std::abs(bendAngle) / 2)));
+
+                double rotationAngleAboutZ = bendElement->getRotationAboutZ();
+                Quaternion_t rotationAboutZ(cos(0.5 * rotationAngleAboutZ),
+                                            sin(-0.5 * rotationAngleAboutZ) * Vector_t(0, 0, 1));
+
+                Vector_t effectiveRotationAxis = rotationAboutZ.rotate(Vector_t(0, -1, 0));
+                effectiveRotationAxis /= euclidian_norm(effectiveRotationAxis);
+
+                Quaternion_t rotationAboutAxis(cos(0.5 * bendAngle),
+                                               sin(0.5 * bendAngle) * effectiveRotationAxis);
+                Quaternion_t halfRotationAboutAxis(cos(0.25 * bendAngle),
+                                                   sin(0.25 * bendAngle) * effectiveRotationAxis);
+                Quaternion_t entryFaceRotation(cos(0.5 * entranceAngle),
+                                               sin(0.5 * entranceAngle) * effectiveRotationAxis);
+
+                if (!Options::idealized) {
+                    std::vector<Vector_t> truePath = bendElement->getDesignPath();
+                    Quaternion_t directionExitHardEdge(cos(0.5 * (0.5 * bendAngle - entranceAngle)),
+                                                       sin(0.5 * (0.5 * bendAngle - entranceAngle)) * effectiveRotationAxis);
+                    Vector_t exitHardEdge = thisLength * directionExitHardEdge.rotate(Vector_t(0, 0, 1));
+                    double distanceEntryHETruePath = euclidian_norm(truePath.front());
+                    double distanceExitHETruePath = euclidian_norm(truePath.back() - exitHardEdge);
+                    double pathLengthTruePath = (*it).getEnd() - (*it).getStart();
+                    arcLength = pathLengthTruePath - distanceEntryHETruePath - distanceExitHETruePath;
                 }
+
+                Vector_t chord = thisLength * halfRotationAboutAxis.rotate(Vector_t(0, 0, 1));
+                Vector_t endThis3D = beginThis3D + chord;
+                double endThisPathLength = beginThisPathLength + arcLength;
+
+                CoordinateSystemTrafo fromEndLastToBeginThis(beginThis3D,
+                                                             (entryFaceRotation * rotationAboutZ).conjugate());
+                CoordinateSystemTrafo fromEndLastToEndThis(endThis3D,
+                                                           rotationAboutAxis.conjugate());
+
+                (*it).setCoordTransformationTo(fromEndLastToBeginThis * currentCoordTrafo);
+
+                currentCoordTrafo = (fromEndLastToEndThis * currentCoordTrafo);
+
+                endPriorPathLength = endThisPathLength;
             }
         }
-        if(tmp.size() > 0) {
-            sections_m.push_back(OpalSection(tmp, *pos_it, *next_it));
-        }
     }
 
-    for(int i = 0; i < -1 + static_cast<long>(sections_m.size()); ++ i) {
-        if(sections_m[i].doesBend()) {
-            const CompVec &els = sections_m[i].getElements();
-            int num_bending_elements = 0;
-            for(CompVec::const_iterator elit = els.begin(); elit != els.end(); ++ elit) {
-                if((*elit)->bends()) {
-                    ++ num_bending_elements;
-                }
-            }
-            if(num_bending_elements > 1) {
-                if(els.size() == 2) {
-                    // TODO:
-                    // set end of section i - 1 to (End_{i-1} + End_{i})/2 and
-                    // set start of section i + 1 to (Start_{i+1} + Start_{i})/2
-                    //
-                    // mark section i for deletion
-                }
+    double endPriorPathLength = 0.0;
+    CoordinateSystemTrafo currentCoordTrafo = coordTransformationTo_m;
+
+    it = elements_m.begin();
+    for (; it != end; ++ it) {
+        if ((*it).isPositioned()) continue;
+
+        (*it).order_m = order ++;
+
+        std::shared_ptr<Component> element = (*it).getElement();
+        double beginThisPathLength = element->getAttribute("ELEMEDGE");
+        double thisLength = element->getElementLength();
+        Vector_t beginThis3D(0, 0, beginThisPathLength - endPriorPathLength);
+
+        if (element->getType() == ElementBase::MONITOR) {
+            beginThis3D(2) -= 0.5 * thisLength;
+        }
+
+        Vector_t endThis3D;
+        if (element->getType() == ElementBase::SBEND ||
+            element->getType() == ElementBase::RBEND ||
+            element->getType() == ElementBase::RBEND3D) {
+
+            BendBase * bendElement = static_cast<BendBase*>(element.get());
+            thisLength = bendElement->getChordLength();
+            double bendAngle = bendElement->getBendAngle();
+
+            double rotationAngleAboutZ = bendElement->getRotationAboutZ();
+            Quaternion_t rotationAboutZ(cos(0.5 * rotationAngleAboutZ),
+                                        sin(0.5 * rotationAngleAboutZ) * Vector_t(0, 0, 1));
+
+            Vector_t rotationAxis = rotationAboutZ.rotate(Vector_t(0, -1, 0));
+            rotationAxis /= euclidian_norm(rotationAxis);
+            Quaternion_t rotationAboutAxis(cos(0.5 * bendAngle),
+                                           sin(0.5 * bendAngle) * rotationAxis);
+            Quaternion halfRotationAboutAxis(cos(0.25 * bendAngle),
+                                             sin(0.25 * bendAngle) * rotationAxis);
+
+            double arcLength = (thisLength * std::abs(bendAngle) /
+                                (2 * sin(bendAngle / 2)));
+            if (!Options::idealized) {
+                std::vector<Vector_t> truePath = bendElement->getDesignPath();
+                double entranceAngle = bendElement->getEntranceAngle();
+                Quaternion_t directionExitHardEdge(cos(0.5 * (0.5 * bendAngle - entranceAngle)),
+                                                   sin(0.5 * (0.5 * bendAngle - entranceAngle)) * rotationAxis);
+                Vector_t exitHardEdge = thisLength * directionExitHardEdge.rotate(Vector_t(0, 0, 1));
+                double distanceEntryHETruePath = euclidian_norm(truePath.front());
+                double distanceExitHETruePath = euclidian_norm(truePath.back() - exitHardEdge);
+                double pathLengthTruePath = (*it).getEnd() - (*it).getStart();
+                arcLength = pathLengthTruePath - distanceEntryHETruePath - distanceExitHETruePath;
             }
+
+            endThis3D = (beginThis3D +
+                         halfRotationAboutAxis.rotate(Vector_t(0, 0, thisLength)));
+            CoordinateSystemTrafo fromEndLastToEndThis(endThis3D,
+                                                       rotationAboutAxis.conjugate());
+            currentCoordTrafo = fromEndLastToEndThis * currentCoordTrafo;
+
+            endPriorPathLength = beginThisPathLength + arcLength;
+        } else {
+            Quaternion rotation(1, 0, 0, 0);
+
+            // FieldList::iterator priorDipole = partiallyInsideDipole(it, elements_m.begin(), elements_m.end(), minOrder);
+
+            // if (priorDipole != it) {
+            //     Bend * bendElement = static_cast<Bend*>((*priorDipole).getElement().get());
+            //     double pathDifference = beginThisPathLength - bendElement->getAttribute("ELEMEDGE");
+
+            //     auto secant = bendElement->getDesignPathSecant(pathDifference, thisLength);
+            //     Vector_t position = (*priorDipole).getCoordTransformationTo().transformFrom(secant.first);
+            //     Vector_t orientation = (*priorDipole).getCoordTransformationTo().rotateFrom(secant.second);
+
+            //     beginThis3D = currentCoordTrafo.transformTo(position);
+            //     rotation = getQuaternion(orientation,
+            //                              currentCoordTrafo.rotateFrom(Vector_t(0, 0, 1)));
+
+            //     CoordinateSystemTrafo fromLastToThis(beginThis3D, rotation);
+            //     fromLastToThis *= currentCoordTrafo;
+            //     Vector_t origin = fromLastToThis.getOrigin();
+            //     Vector_t end = origin + thisLength * fromLastToThis.rotateFrom(Vector_t(0,0,1));
+            // }
+
+            double rotationAngleAboutZ = (*it).getElement()->getRotationAboutZ();
+            Quaternion_t rotationAboutZ(cos(0.5 * rotationAngleAboutZ),
+                                        sin(-0.5 * rotationAngleAboutZ) * Vector_t(0, 0, 1));
+
+            CoordinateSystemTrafo fromLastToThis(beginThis3D, rotationAboutZ * rotation);
+
+            (*it).setCoordTransformationTo(fromLastToThis * currentCoordTrafo);
         }
-        if (sections_m[i].doDipoleFieldsOverlap()) {
-            const CompVec &elements = sections_m[i].getElements();
-            auto it = elements.begin();
-            std::stringstream elementNamesStream;
-            std::string elementNames;
-            for (; it != elements.end(); ++ it) {
-                double start, end;
-                (*it)->getDimensions(start, end);
-                elementNamesStream << (*it)->getName() << ": "
-                                   << "start= " << start << " m, "
-                                   << "end= " << end << " m,\n";
+
+        (*it).fixPosition();
+    }
+
+    elements_m.sort(ClassicField::SortAsc);
+}
+
+void OpalBeamline::plot3DLattice() {
+    if (Ippl::myNode() != 0) return;
+
+    elements_m.sort([](const ClassicField& a, const ClassicField& b) {
+            return a.getElement()->getAttribute("ELEMEDGE") < b.getElement()->getAttribute("ELEMEDGE");
+            //return a.order_m < b.order_m;
+        });
+
+    FieldList::iterator it = elements_m.begin();
+    FieldList::iterator end = elements_m.end();
+
+    Quaternion rotDiagonal(0.5, 0.5 * Vector_t(-1, 1, -1));
+
+    Vector_t origin = rotDiagonal.rotate(coordTransformationTo_m.getOrigin());
+    Vector_t direction = rotDiagonal.rotate(coordTransformationTo_m.rotateFrom(Vector_t(0, 0, 1)));
+    Vector_t minX = Vector_t(999999.9), maxX(-999999.9);
+    std::map<std::string, std::vector<Vector_t > > elementCorners;
+
+    for (; it != end; ++ it) {
+        std::shared_ptr<Component> element = (*it).getElement();
+        CoordinateSystemTrafo toBegin = (*it).getCoordTransformationTo();
+        std::vector<Vector_t> corners;
+
+        if (element->getType() == ElementBase::RBEND || element->getType() == ElementBase::SBEND) {
+            std::vector<Vector_t> outline = static_cast<const Bend*>(element.get())->getOutline();
+
+            for (auto point: outline) {
+                corners.push_back(rotDiagonal.rotate(toBegin.transformFrom(point)));
             }
-            elementNames = elementNamesStream.str();
-            elementNames.erase(elementNames.length() - 2, 1);
-            throw OpalException("OpalBeamline::prepareSections",
-                                "Fields overlap with dipole fields; not supported yet;\n*** affected elements:\n" + elementNames +
-                                "***");
+        } else {
+            CoordinateSystemTrafo toEnd = element->getBeginToEnd() * toBegin;
+            auto aperture = element->getAperture();
+            double elementHeightFront = aperture.second[0];
+            double elementHeightBack = aperture.second[0] * aperture.second[2];
+
+            corners.push_back(rotDiagonal.rotate(toEnd.transformFrom(Vector_t(0.0))));
+            corners.push_back(rotDiagonal.rotate(toBegin.transformFrom(Vector_t(0))));
+            corners.push_back(rotDiagonal.rotate(toBegin.transformFrom(-elementHeightFront * Vector_t(1, 0, 0))));
+            corners.push_back(rotDiagonal.rotate(toEnd.transformFrom(-elementHeightBack * Vector_t(1, 0, 0))));
+            corners.push_back(rotDiagonal.rotate(toEnd.transformFrom(Vector_t(0.0))));
+            corners.push_back(rotDiagonal.rotate(toEnd.transformFrom(elementHeightBack * Vector_t(1, 0, 0))));
+            corners.push_back(rotDiagonal.rotate(toBegin.transformFrom(elementHeightFront * Vector_t(1, 0, 0))));
+            corners.push_back(rotDiagonal.rotate(toBegin.transformFrom(Vector_t(0))));
+        }
+
+        elementCorners.insert(std::make_pair(element->getName(), corners));
+        const unsigned int numCorners = corners.size();
+        for (unsigned int i = 0 ; i < numCorners; ++ i) {
+            const Vector_t & X = corners[i];
+
+            if (X(0) < minX(0)) minX(0) = X(0);
+            else if (X(0) > maxX(0)) maxX(0) = X(0);
+
+            if (X(1) < minX(1)) minX(1) = X(1);
+            else if (X(1) > maxX(1)) maxX(1) = X(1);
         }
     }
 
+    it = elements_m.begin();
 
-    for(int i = 0; i < static_cast<long>(sections_m.size()) - 1; ++ i) {
-        if(sections_m[i].doesBend() && sections_m[i + 1].doesBend()) {
-
-            if(fabs(sections_m[i].getEnd(0.0, 0.0) - sections_m[i + 1].getStart(0.0, 0.0)) < 1.e-12) {
-                // TODO:
-                // check that elements realy overlap
-                const CompVec &els = sections_m[i].getElements();
-                for(CompVec::const_iterator elit = els.begin(); elit != els.end(); ++ elit) {
-                    if((*elit)->bends()) {
-                        if(sections_m[i + 1].find(*elit)) {
-                            sections_m[i].glue_to(&sections_m[i + 1]);
-                            sections_m[i + 1].previous_is_glued();
-                        }
-                    }
-                }
+    double tau = (minX(0) - origin(0) - 0.3) / direction(0);
+    origin += tau * direction;
+    if (origin(0) < minX(0)) minX(0) = origin(0);
+    if (origin(1) < minX(1)) minX(1) = origin(1);
+
+    std::ofstream gpl;
+    std::string fileName = OpalData::getInstance()->getInputBasename() + "_ElementPositions.gpl";
+    if (Options::openMode == Options::APPEND && boost::filesystem::exists(fileName)) {
+        gpl.open(fileName, std::ios_base::app);
+    } else {
+        gpl.open(fileName);
+    }
+    gpl.precision(8);
+
+    for (; it != end; ++ it) {
+        std::shared_ptr<Component> element = (*it).getElement();
+
+        if (element->getType() != ElementBase::DRIFT) {
+            const std::vector<Vector_t> &corners = elementCorners[element->getName()];
+            const unsigned int numCorners = corners.size();
+
+            gpl << "# " << element->getName() << "\n";
+            for (unsigned int i = 0; i < numCorners; ++ i) {
+                gpl << std::setw(18) << corners[i](0)
+                    << std::setw(18) << -corners[i](1) << "\n";
             }
+            gpl << std::setw(18) << corners.front()(0)
+                << std::setw(18) << -corners.front()(1) << "\n\n";
         }
     }
 
-    online_secs_m = new bool[sections_m.size()];
-    for(size_t i = 0; i < sections_m.size(); ++ i) {
-        online_secs_m[i] = false;
+    elements_m.sort(ClassicField::SortAsc);
+}
+
+void OpalBeamline::save3DLattice() {
+    if (Ippl::myNode() != 0) return;
+
+    elements_m.sort([](const ClassicField& a, const ClassicField& b) {
+            return a.order_m < b.order_m;
+        });
+
+    FieldList::iterator it = elements_m.begin();
+    FieldList::iterator end = elements_m.end();
+
+    std::ofstream pos;
+    std::string fileName = OpalData::getInstance()->getInputBasename() + "_ElementPositions.txt";
+    if (Options::openMode == Options::APPEND && boost::filesystem::exists(fileName)) {
+        pos.open(fileName, std::ios_base::app);
+    } else {
+        pos.open(fileName);
+    }
+
+    MeshGenerator mesh;
+    for (; it != end; ++ it) {
+        std::shared_ptr<Component> element = (*it).getElement();
+        CoordinateSystemTrafo toEnd = element->getBeginToEnd() * (*it).getCoordTransformationTo();
+        Vector_t entry3D = (*it).getCoordTransformationTo().getOrigin();
+        Vector_t exit3D = toEnd.getOrigin();
+
+        mesh.add(*(element.get()));
+
+        if (element->getType() == ElementBase::SBEND ||
+            element->getType() == ElementBase::RBEND) {
+
+            Bend * bendElement = static_cast<Bend*>(element.get());
+            std::vector<Vector_t> designPath = bendElement->getDesignPath();
+
+            unsigned int size = designPath.size();
+            unsigned int minNumSteps = std::max(20.0,
+                                                std::abs(bendElement->getBendAngle() / Physics::pi * 180));
+            unsigned int frequency = std::floor((double)size / minNumSteps);
+
+            pos << std::setw(30) << std::left << std::string("\"ENTRY EDGE: ") + element->getName() + std::string("\"")
+                << std::setw(18) << std::setprecision(10) << entry3D(2)
+                << std::setw(18) << std::setprecision(10) << entry3D(0)
+                << std::setw(18) << std::setprecision(10) << entry3D(1)
+                << "\n";
+
+            Vector_t position = (*it).getCoordTransformationTo().transformFrom(designPath.front());
+            pos << std::setw(30) << std::left << std::string("\"BEGIN: ") + element->getName() + std::string("\"")
+                << std::setw(18) << std::setprecision(10) << position(2)
+                << std::setw(18) << std::setprecision(10) << position(0)
+                << std::setw(18) << std::setprecision(10) << position(1)
+                << std::endl;
+
+            for (unsigned int i = frequency; i + 1 < size; i += frequency) {
+
+                Vector_t position = (*it).getCoordTransformationTo().transformFrom(designPath[i]);
+                pos << std::setw(30) << std::left << std::string("\"MID: ") + element->getName() + std::string("\"")
+                    << std::setw(18) << std::setprecision(10) << position(2)
+                    << std::setw(18) << std::setprecision(10) << position(0)
+                    << std::setw(18) << std::setprecision(10) << position(1)
+                    << endl;
+            }
+
+            position = (*it).getCoordTransformationTo().transformFrom(designPath.back());
+            pos << std::setw(30) << std::left << std::string("\"END: ") + element->getName() + std::string("\"")
+                << std::setw(18) << std::setprecision(10) << position(2)
+                << std::setw(18) << std::setprecision(10) << position(0)
+                << std::setw(18) << std::setprecision(10) << position(1)
+                << std::endl;
+
+            pos << std::setw(30) << std::left << std::string("\"EXIT EDGE: ") + element->getName() + std::string("\"")
+                << std::setw(18) << std::setprecision(10) << exit3D(2)
+                << std::setw(18) << std::setprecision(10) << exit3D(0)
+                << std::setw(18) << std::setprecision(10) << exit3D(1)
+                << std::endl;
+        } else {
+            pos << std::setw(30) << std::left << std::string("\"BEGIN: ") + element->getName() + std::string("\"")
+                << std::setw(18) << std::setprecision(10) << entry3D(2)
+                << std::setw(18) << std::setprecision(10) << entry3D(0)
+                << std::setw(18) << std::setprecision(10) << entry3D(1)
+                << "\n";
+
+            pos << std::setw(30) << std::left << std::string("\"END: ") + element->getName() + std::string("\"")
+                << std::setw(18) << std::setprecision(10) << exit3D(2)
+                << std::setw(18) << std::setprecision(10) << exit3D(0)
+                << std::setw(18) << std::setprecision(10) << exit3D(1)
+                << std::endl;
+        }
     }
-    prepared_m = true;
+    elements_m.sort(ClassicField::SortAsc);
+    mesh.write(OpalData::getInstance()->getInputBasename());
 }
 
-void OpalBeamline::print(Inform &msg) const {
-    SectionList::const_iterator sec_it;
+std::string parseInput() {
+
+    std::ifstream in(OpalData::getInstance()->getInputFn());
+    std::string source("");
+    std::string str;
+    char testBit;
+    const std::string commentFormat("");
+    const boost::regex empty("^[ \t]*$");
+    const boost::regex lineEnd(";");
+    const std::string lineEndFormat(";\n");
+    const boost::regex cppCommentExpr("//.*");
+    const boost::regex cCommentExpr("/\\*.*?\\*/"); // "/\\*(?>[^*/]+|\\*[^/]|/[^*])*(?>(?R)(?>[^*/]+|\\*[^/]|/[^*])*)*\\*/"
+    bool priorEmpty = true;
+
+    in.get(testBit);
+    while (!in.eof()) {
+        in.putback(testBit);
+
+        std::getline(in, str);
+        str = boost::regex_replace(str, cppCommentExpr, commentFormat);
+        str = boost::regex_replace(str, empty, commentFormat);
+        if (str.size() > 0) {
+            source += str;// + '\n';
+            priorEmpty = false;
+        } else if (!priorEmpty) {
+            source += "##EMPTY_LINE##";
+            priorEmpty = true;
+        }
+
+        in.get(testBit);
+    }
 
-    msg << level1 << "\n--- BEGIN FIELD LIST ---------------------------------------------------------------\n\n";
-    for(sec_it = sections_m.begin(); sec_it != sections_m.end(); ++ sec_it) {
-        (*sec_it).print(msg);
+    source = boost::regex_replace(source, cCommentExpr, commentFormat);
+    source = boost::regex_replace(source, lineEnd, lineEndFormat, boost::match_default | boost::format_all);
+
+    return source;
+}
+
+unsigned int getMinimalSignificantDigits(double num, const unsigned int maxDigits) {
+    char buf[32];
+    snprintf(buf, 32, "%.*f", maxDigits + 1, num);
+    string numStr(buf);
+    unsigned int length = numStr.length();
+
+    unsigned int numDigits = maxDigits;
+    unsigned int i = 2;
+    while (i < maxDigits + 1 && numStr[length - i] == '0') {
+        --numDigits;
+        ++ i;
     }
-    msg << level1 << "\n--- END FIELD LIST -----------------------------------------------------------------\n" << endl;
+
+    return numDigits;
+}
+
+std::string round2string(double num, const unsigned int maxDigits) {
+    char buf[64];
+
+    snprintf(buf, 64, "%.*f", getMinimalSignificantDigits(num, maxDigits), num);
+
+    return std::string(buf);
 }
 
+void OpalBeamline::save3DInput() {
+    if (Ippl::myNode() != 0) return;
+
+    FieldList::iterator it = elements_m.begin();
+    FieldList::iterator end = elements_m.end();
+
+    std::string input = parseInput();
+    std::ofstream pos(OpalData::getInstance()->getInputBasename() + "_3D.opal");
+
+    for (; it != end; ++ it) {
+        std::string element = (*it).getElement()->getName();
+        const boost::regex replacePSI("(" + element + "\\s*:[^\\n]*)PSI\\s*=[^,;]*,?", boost::regex::icase);
+        input = boost::regex_replace(input, replacePSI, "\\1\\2");
+
+        const boost::regex replaceELEMEDGE("(" + element + "\\s*:[^\\n]*)ELEMEDGE\\s*=[^,;]*(.)", boost::regex::icase);
+
+        CoordinateSystemTrafo cst = (*it).getCoordTransformationTo();
+        Vector_t origin = cst.getOrigin();
+        Vector_t orient = Util::getTaitBryantAngles(cst.getRotation().conjugate(), element);
+        for (unsigned int d = 0; d < 3; ++ d)
+            orient(d) *= Physics::rad2deg;
+
+        std::string x = (std::abs(origin(0)) > 1e-10? "X = " + round2string(origin(0), 10) + ", ": "");
+        std::string y = (std::abs(origin(1)) > 1e-10? "Y = " + round2string(origin(1), 10) + ", ": "");
+        std::string z = (std::abs(origin(2)) > 1e-10? "Z = " + round2string(origin(2), 10) + ", ": "");
 
-double OpalBeamline::calcBeamlineLenght() {
-    SectionList::const_iterator sec_it;
-    double l = -1000000000.0;
-    for(sec_it = sections_m.begin(); sec_it != sections_m.end(); ++ sec_it) {
-        double tmp = (*sec_it).getEnd();
-        if(tmp > l)
-            l = tmp;
+        std::string theta = (orient(0) > 1e-10? "THETA = " + round2string(orient(0), 6) + " * PI / 180, ": "");
+        std::string phi = (orient(1) > 1e-10? "PHI = " + round2string(orient(1), 6) + " * PI / 180, ": "");
+        std::string psi = (orient(2) > 1e-10? "PSI = " + round2string(orient(2), 6) + " * PI / 180, ": "");
+        std::string coordTrafo = x + y + z + theta + phi + psi;
+        if (coordTrafo.length() > 2) {
+            coordTrafo = coordTrafo.substr(0, coordTrafo.length() - 2); // remove last ', '
+        }
+
+        std::string position = ("\\1" + coordTrafo + "\\2");
+
+        input = boost::regex_replace(input, replaceELEMEDGE, position);
+
+        if ((*it).getElement()->getType() == ElementBase::RBEND ||
+            (*it).getElement()->getType() == ElementBase::SBEND) {
+            const Bend* dipole = static_cast<const Bend*>((*it).getElement().get());
+            double angle = dipole->getBendAngle();
+            double E1 = dipole->getEntranceAngle();
+            double E2 = dipole->getExitAngle();
+
+            const boost::regex angleR("(" + element + "\\s*:[^\\n]*ANGLE\\s*=)[^,;]*(.)");
+            const std::string angleF("\\1 " + round2string(angle * 180 / Physics::pi, 6) + " / 180 * PI\\2");
+            const boost::regex E1R("(" + element + "\\s*:[^\\n]*E1\\s*=)[^,;]*(.)");
+            const std::string E1F("\\1 " + round2string(E1 * 180 / Physics::pi, 6) + " / 180 * PI\\2");
+            const boost::regex E2R("(" + element + "\\s*:[^\\n]*E2\\s*=)[^,;]*(.)");
+            const std::string E2F("\\1 " + round2string(E2 * 180 / Physics::pi, 6) + " / 180 * PI\\2");
+            const boost::regex noRotation("(" + element + "\\s*:[^\\n]*),\\s*ROTATION\\s*=[^,;]*(.)");
+            const std::string noRotationFormat("\\1\\2  ");
+
+            input = boost::regex_replace(input, angleR, angleF);
+            input = boost::regex_replace(input, E1R, E1F);
+            input = boost::regex_replace(input, E2R, E2F);
+            input = boost::regex_replace(input, noRotation, noRotationFormat);
+        }
     }
-    return l;
+
+    const boost::regex empty("##EMPTY_LINE##");
+    const std::string emptyFormat("\n");
+    input = boost::regex_replace(input, empty, emptyFormat);
+
+    pos << input << std::endl;
 }
 
+FieldList::iterator OpalBeamline::partiallyInsideDipole(const FieldList::iterator &it,
+                                                        const FieldList::iterator &begin,
+                                                        const FieldList::iterator &end,
+                                                        const unsigned int &minOrder) {
+    if (it == begin) return it;
 
-FieldList OpalBeamline::getElementByType(ElementBase::ElementType type) {
-    FieldList elements_of_requested_type;
-    for(FieldList::iterator fit = elements_m.begin(); fit != elements_m.end(); ++ fit) {
-        if((*fit).getElement()->getType() == type) {
-            elements_of_requested_type.push_back((*fit));
+    FieldList::iterator prior = it;
+    -- prior;
+
+    while (true) {
+        std::shared_ptr<Component> element = (*prior).getElement();
+
+        if ((*prior).getEnd() > /*(*it).getStart()*/ (*it).getElement()->getAttribute("ELEMEDGE") &&
+            (element->getType() == ElementBase::SBEND ||
+             element->getType() == ElementBase::RBEND)) {
+
+            if ((*prior).order_m >= minOrder)
+                return prior;
         }
+
+        if (prior == begin) break;
+        -- prior;
     }
-    return elements_of_requested_type;
+
+    if (it == end) return it;
+    FieldList::iterator next = it;
+    ++ next;
+    if (next == end) return it;
+
+    while (true) {
+        std::shared_ptr<Component> element = (*next).getElement();
+
+        if ((element->getType() == ElementBase::SBEND ||
+             element->getType() == ElementBase::RBEND) &&
+            (*it).getElement()->getAttribute("ELEMEDGE") > (*next).getStart() &&
+            (*it).getElement()->getAttribute("ELEMEDGE") < (*next).getEnd()) {
+
+            if ((*next).order_m >= minOrder)
+                return next;
+        }
+
+        ++ next;
+
+        if (next == end) break;
+    }
+
+    return it;
 }
+
+void OpalBeamline::activateElements() {
+    auto it = elements_m.begin();
+    const auto end = elements_m.end();
+
+    double designEnergy = 0.0;
+    for (; it != end; ++ it) {
+        std::shared_ptr<Component> element = (*it).getElement();
+        if (element->getType() == ElementBase::SBEND ||
+            element->getType() == ElementBase::RBEND) {
+            Bend * bendElement = static_cast<Bend*>(element.get());
+            designEnergy = bendElement->getDesignEnergy() * 1e-6;
+        }
+        (*it).setOn(designEnergy);
+        // element->goOnline(designEnergy);
+    }
+}
\ No newline at end of file
diff --git a/src/Elements/OpalBeamline.h b/src/Elements/OpalBeamline.h
index 537866a35aca0bc4fdf325648e59331e9b06f7d7..9cf790067a509f6b8367081b50854ed27d76498a 100644
--- a/src/Elements/OpalBeamline.h
+++ b/src/Elements/OpalBeamline.h
@@ -17,18 +17,21 @@
 #include "AbsBeamline/RFQuadrupole.h"
 #include "AbsBeamline/Separator.h"
 #include "AbsBeamline/Septum.h"
+#include "AbsBeamline/Source.h"
 
 #include "BasicActions/Option.h"
 #include "Utilities/Options.h"
-#include "Utilities/Options.h"
 #include "Utilities/OpalSection.h"
 #include "Utilities/ClassicField.h"
 
+#include "Algorithms/CoordinateSystemTrafo.h"
+
 class Tracker;
 class PartBunch;
 class SurfacePhysicsHandler;
 class BoundaryGeometry;
 class WakeFunction;
+class Bend;
 
 #define BEAMLINE_EOL  0x80000000   // end of line
 #define BEAMLINE_OOB  0x40000000   // out of bounds
@@ -41,30 +44,49 @@ class OpalBeamline {
 
 public:
     OpalBeamline();
+    OpalBeamline(const Vector_t& origin,
+                 const Quaternion& coordTrafoTo);
     ~OpalBeamline();
 
-    CompVec &getPredecessors(std::shared_ptr<const Component>);
-    CompVec &getSuccessors(std::shared_ptr<const Component>);
     OpalSection &getSectionAt(const Vector_t &, long &);
     OpalSection &getSection(const unsigned int &);
-    void getSectionIndexAt(const Vector_t &, long &) const;
-    double getSectionStart(const long &) const;
-    double getSectionEnd(const unsigned int &) const;
-    double getSectionEnd(const Vector_t &, long);
+
+    void activateElements();
+    std::set<std::shared_ptr<Component>> getElements(const Vector_t &x);
+    Vector_t transformTo(const Vector_t &r) const;
+    Vector_t transformFrom(const Vector_t &r) const;
+    Vector_t rotateTo(const Vector_t &r) const;
+    Vector_t rotateFrom(const Vector_t &r) const;
+
+    Vector_t transformToLocalCS(const std::shared_ptr<Component> &comp,
+                                const Vector_t &r) const;
+    Vector_t transformFromLocalCS(const std::shared_ptr<Component> &comp,
+                                  const Vector_t &r) const;
+    Vector_t rotateToLocalCS(const std::shared_ptr<Component> &comp,
+                             const Vector_t &r) const;
+    Vector_t rotateFromLocalCS(const std::shared_ptr<Component> &comp,
+                               const Vector_t &r) const;
+    CoordinateSystemTrafo getCSTrafoLab2Local(const std::shared_ptr<Component> &comp) const;
+    CoordinateSystemTrafo getCSTrafoLab2Local() const;
+    CoordinateSystemTrafo getMisalignment(const std::shared_ptr<Component> &comp) const;
+    // void getSectionIndexAt(const Vector_t &, long &) const;
+    // double getSectionStart(const long &) const;
+    // double getSectionEnd(const unsigned int &) const;
+    // double getSectionEnd(const Vector_t &, long);
 
     double getStart(const Vector_t &) const;
     double getEnd(const Vector_t &) const;
 
-    void setOrientation(const Vector_t &, const Vector_t &);
-    void setOrientation(const Vector_t &, const unsigned int &);
-    void updateOrientation(const Vector_t &, const Vector_t &, const double &, const double &);
+    // void setOrientation(const Vector_t &, const Vector_t &);
+    // void setOrientation(const Vector_t &, const unsigned int &);
+    // void updateOrientation(const Vector_t &, const Vector_t &, const double &, const double &);
 
-    const Vector_t &getOrientation(const Vector_t &) const;
-    const Vector_t &getOrientation(const long &) const;
+    // const Vector_t &getOrientation(const Vector_t &) const;
+    // const Vector_t &getOrientation(const long &) const;
 
-    void resetStatus();
-    void setStatus(const unsigned int &, const bool &);
-    const bool &getStatus(const unsigned int &) const;
+    // void resetStatus();
+    // void setStatus(const unsigned int &, const bool &);
+    // const bool &getStatus(const unsigned int &) const;
 
     void switchElements(const double &, const double &, const double &kineticEnergy, const bool &nomonitors = false);
     void switchAllElements();
@@ -87,266 +109,105 @@ public:
     void visit(const T &, BeamlineVisitor &, PartBunch *);
 
     void prepareSections();
+    void compute3DLattice();
+    void plot3DLattice();
+    void save3DLattice();
+    void save3DInput();
     void print(Inform &) const;
 
-    bool section_is_glued_to(const long &i, const long &j) const;
-
     FieldList getElementByType(ElementBase::ElementType);
 
     // need this for autophasing in case we have multiple tracks
-    double calcBeamlineLenght();
-    SectionList sections_m;
+    double calcBeamlineLength();
 
     void removeElement(const std::string &ElName);
 
+    void swap(OpalBeamline & rhs);
+    void merge(OpalBeamline &rhs);
+
+    bool containsSource();
 private:
+    FieldList::iterator partiallyInsideDipole(const FieldList::iterator &it,
+                                              const FieldList::iterator &begin,
+                                              const FieldList::iterator &end,
+                                              const unsigned int &minOrder);
+
     FieldList elements_m;
     bool prepared_m;
-    int *online_sections_m;
-    bool *online_secs_m;
+    bool containsSource_m;
+
+    CoordinateSystemTrafo coordTransformationTo_m;
 
     static CompVec dummy_list_m;
     static OpalSection dummy_section_m;
 };
 
-inline void OpalBeamline::resetStatus() {
-    for(unsigned int i = 0; i < sections_m.size(); ++ i) {
-        sections_m[i].setStatus(false);
-    }
-}
-
-inline void OpalBeamline::setStatus(const unsigned int &index, const bool &status) {
-    if(index < sections_m.size()) {
-        sections_m[index].setStatus(status);
-    }
-}
-
-inline const bool &OpalBeamline::getStatus(const unsigned int &index) const {
-    static const bool default_value = false;
-    if(index < sections_m.size()) {
-        return sections_m[index].getStatus();
-    }
-    return default_value;
-}
-
-inline WakeFunction *OpalBeamline::getWakeFunction(const unsigned int &index) {
-    if(index < sections_m.size()) {
-        return sections_m[index].getWakeFunction();
-    }
-    return NULL;
-}
-
-inline std::shared_ptr<const ElementBase> OpalBeamline::getWakeFunctionOwner(const unsigned int &index) {
-    if(index < sections_m.size()) {
-        return sections_m[index].getWakeFunctionOwner();
-    }
-    return NULL;
-}
-
-inline BoundaryGeometry *OpalBeamline::getBoundaryGeometry(const unsigned int &index) {
-    if(index < sections_m.size()) {
-        return sections_m[index].getBoundaryGeometry();
-    }
-    return NULL;
-}
-
-inline SurfacePhysicsHandler *OpalBeamline::getSurfacePhysicsHandler(const unsigned int &index) {
-    if(index < sections_m.size()) {
-        return sections_m[index].getSurfacePhysicsHandler();
-    }
-    return 0;
-}
-
-inline double OpalBeamline::getSectionStart(const long &index) const {
-    if(index > -1 && (unsigned long) index < sections_m.size())
-        return sections_m[index].getStart(0., 0.);
-
-    return std::numeric_limits<double>::max();
-}
-
-inline double OpalBeamline::getSectionEnd(const unsigned int &index) const {
-    if(index < sections_m.size())
-        return sections_m[index].getEnd(0., 0.);
-
-    return std::numeric_limits<double>::min();
-}
-
-inline double OpalBeamline::getSectionEnd(const Vector_t &pos, long sindex) {
-    if(sindex > -1 && (unsigned int) sindex < sections_m.size()) {
-        OpalSection &section = getSectionAt(pos, sindex);
-        if(!(sindex & BEAMLINE_EOL || sindex < 0)) {
-            return section.getEnd(pos(0), pos(2));
-        }
-    }
-    return -1.0;
-}
-
-inline void OpalBeamline::setOrientation(const Vector_t &angle, const Vector_t &pos) {
-    long index = 0;
-    getSectionIndexAt(pos, index);
-    if(index > -1 && (unsigned long) index < sections_m.size()) {
-        sections_m[index].setOrientation(angle);
-    }
-}
-
-inline void OpalBeamline::setOrientation(const Vector_t &angle, const unsigned int &index) {
-    if(index < sections_m.size()) {
-        sections_m[index].setOrientation(angle);
-    }
-}
-
-inline void OpalBeamline::updateOrientation(const Vector_t &angle, const Vector_t &centroid, const double &smin, const double &smax) {
-
-    // Determine which sections are online.
-    int j = 0;
-    for(int i = 0; i < 5 * Ippl::getNodes(); ++ i) {
-        online_sections_m[i] = 0;
-    }
-
-    for(unsigned int i = 0; i < sections_m.size(); ++ i) {
-        if(sections_m[i].getStatus()) {
-            if(i > 0 && sections_m[i - 1].getStatus() && sections_m[i - 1].is_glued_to(&sections_m[i])) {
-                continue;
-            } else {
-                online_sections_m[j + 5 * Ippl::myNode()] = i + 1;
-                ++ j;
-            }
-        }
-        if(j == 5) {
-            break;
-        }
-    }
-
-    reduce(online_sections_m, online_sections_m + 5 * Ippl::getNodes(), online_sections_m, OpAddAssign());
-
-    bool anyOnline = false;
-    size_t lastSectionOnline = 0;
-    for(int i = 0; i < 5 * Ippl::getNodes(); ++ i) {
-        if(online_sections_m[i] > 0) {
-            online_secs_m[online_sections_m[i] - 1] = true;
-            anyOnline = true;
-            lastSectionOnline = std::max(lastSectionOnline, (size_t) online_sections_m[i]);
-        }
-    }
-
-    if (!anyOnline) return;
-    lastSectionOnline = std::min(lastSectionOnline, sections_m.size());
-
-    // Update orientation of online sections.
-    for(unsigned int i = 0; i < lastSectionOnline; ++ i) {
-        if (i > 0 && sections_m[i-1].is_glued_to(&sections_m[i])) continue;
-
-        online_secs_m[i] = false;
-        Vector_t oldAngle = sections_m[i].getOrientation();
-
-        // Rotate about z axis before changing section's Euler angles.
-        Vector_t newAngle;
-        double cosc = cos(oldAngle(2));
-        double sinc = -sin(oldAngle(2));
-
-        newAngle(0) = oldAngle(0) + cosc * angle(0) - sinc * angle(1);
-        newAngle(1) = oldAngle(1) + sinc * angle(0) + cosc * angle(1);
-        newAngle(2) = oldAngle(2);
-
-        sections_m[i].setOrientation(newAngle);
-
-        if(smin < sections_m[i].getStart(0.0, 0.0)) {
-            double dist = sections_m[i].getStart(0.0, 0.0) - centroid(2);
-            double newdist = dist / (1. - tan(oldAngle(0)) * angle(0));  // * cos(oldAngle(0)) / cos(newAngle(0));
-            sections_m[i].setStart(centroid(2) + newdist);
-        } else if(smax > sections_m[i].getEnd(0.0, 0.0)) {
-            double dist = sections_m[i].getEnd(0.0, 0.0) - centroid(2);
-            double newdist = dist / (1. - tan(oldAngle(0)) * angle(0)); // * cos(oldAngle(0)) / cos(newAngle(0));
-            sections_m[i].setEnd(centroid(2) + newdist);
-            if(i + 1 < sections_m.size() && sections_m[i].is_glued_to(&sections_m[i + 1])) {
-                sections_m[i + 1].setStart(centroid(2) + newdist);
-            }
-        }
-    }
-}
-
-inline const Vector_t &OpalBeamline::getOrientation(const Vector_t &pos) const {
-    static const Vector_t dummy(0.0);
-    long index = 0;
-    getSectionIndexAt(pos, index);
-    if(index > -1 && (unsigned long) index < sections_m.size()) {
-        return sections_m[index].getOrientation();
-    } else {
-        return dummy;
-    }
-}
-
-inline const Vector_t &OpalBeamline::getOrientation(const long &i) const {
-    static const Vector_t dummy(0.0);
-    if(i > -1 && (unsigned long) i < sections_m.size()) {
-        return sections_m[i].getOrientation();
-    } else {
-        return dummy;
-    }
-}
 
-inline bool OpalBeamline::section_is_glued_to(const long &i, const long &j) const {
-    if(i > -1 && i < j && (unsigned long) j < sections_m.size()) {
-        for(int k = i; k < j; ++ k) {
-            if(!sections_m[k].is_glued_to(&sections_m[k + 1])) {
-                return false;
-            }
-        }
-        return true;
-    }
-    return false;
-}
+// inline WakeFunction *OpalBeamline::getWakeFunction(const unsigned int &index) {
+//     if(index < sections_m.size()) {
+//         return sections_m[index].getWakeFunction();
+//     }
+//     return NULL;
+// }
+
+// inline std::shared_ptr<const ElementBase> OpalBeamline::getWakeFunctionOwner(const unsigned int &index) {
+//     if(index < sections_m.size()) {
+//         return sections_m[index].getWakeFunctionOwner();
+//     }
+//     return NULL;
+// }
+
+// inline BoundaryGeometry *OpalBeamline::getBoundaryGeometry(const unsigned int &index) {
+//     if(index < sections_m.size()) {
+//         return sections_m[index].getBoundaryGeometry();
+//     }
+//     return NULL;
+// }
+
+// inline SurfacePhysicsHandler *OpalBeamline::getSurfacePhysicsHandler(const unsigned int &index) {
+//     if(index < sections_m.size()) {
+//         return sections_m[index].getSurfacePhysicsHandler();
+//     }
+//     return 0;
+// }
 
 template<class T> inline
 void OpalBeamline::visit(const T &element, BeamlineVisitor &, PartBunch *bunch) {
     Inform msg("OPAL ");
+    double startField = 0.0;
+    double endField = 0.0;
     std::shared_ptr<T> elptr(dynamic_cast<T *>(element.clone()->removeWrappers()));
-    if(!elptr->hasAttribute("ELEMEDGE")) {
-        msg << elptr->getType() << ": no position of the element given!" << endl;
-        return;
+
+    if (elptr->hasAttribute("ELEMEDGE")) {
+        startField = elptr->getAttribute("ELEMEDGE");
     }
-    //     if (elptr->hasWake()) {
-    //         const Wake *wf = elptr->getWake();
-    //     }
 
-    double startField = elptr->getAttribute("ELEMEDGE");
-    double endField;
-    elptr->initialise(bunch, startField, endField, 1.0);
+    elptr->initialise(bunch, startField, endField);
     elements_m.push_back(ClassicField(elptr, startField, endField));
 }
 
 template<> inline
-void OpalBeamline::visit<AlignWrapper>(const AlignWrapper &wrap, BeamlineVisitor &visitor, PartBunch *) {
-    if(wrap.getType() == ElementBase::BEAMLINE) {
-        Beamline *bl = dynamic_cast<Beamline *>(wrap.getElement());
-        bl->iterate(visitor, false);
-    } else {
-        wrap.getElement()->accept(visitor);
-    }
+void OpalBeamline::visit<Source>(const Source &element, BeamlineVisitor &, PartBunch *bunch) {
+    // Inform msg("OPAL ");
+    // double startField = 0.0;
+    // double endField = 0.0;
+    // std::shared_ptr<Source> elptr(static_cast<Source*>(element.clone()->removeWrappers()));
+
+    // if(!elptr->hasAttribute("ELEMEDGE")) {
+    //     startField = elptr->getAttribute("ELEMEDGE");
+    // }
+
+    // elptr->initialise(bunch, startField, endField);
+    // elptr->setBeamline(this);
+    // elements_m.push_back(ClassicField(elptr, startField, endField));
+    containsSource_m = true;
 }
 
-/*
 template<> inline
-void OpalBeamline::visit<Corrector>(const Corrector &element, BeamlineVisitor &, PartBunch *bunch) {
-    Inform msg("visit<Corrector ");
-
-    Corrector *elptr = dynamic_cast<Corrector *>(element.clone()->removeWrappers());
-    if(!elptr->hasAttribute("ELEMEDGE")) {
-        msg << elptr->getType() << ": no position of the element given!" << endl;
-        return;
-    }
-    //     if (elptr->hasWake()) {
-    //         const Wake *wf = elptr->getWake();
-    //     }
-
-    double startField = elptr->getAttribute("ELEMEDGE");
-    double endField;
-    elptr->initialise(bunch, startField, endField, 1.0);
-    elements_m.push_back(ClassicField(elptr, startField, endField));
-
-    msg << element.getType() << " ELEMEDGE=" << startField << endl;
+void OpalBeamline::visit<AlignWrapper>(const AlignWrapper &wrap, BeamlineVisitor &visitor, PartBunch *) {
+    wrap.getElement()->accept(visitor);
 }
-*/
+
 template<> inline
 void OpalBeamline::visit<BeamBeam>(const BeamBeam &element, BeamlineVisitor &, PartBunch *) {
     WARNMSG(element.getTypeString() << " not implemented yet!" << endl);
@@ -391,4 +252,67 @@ void OpalBeamline::removeElement(const std::string &ElName) {
     }
 }
 
-#endif // OPAL_BEAMLINE_H
+inline
+Vector_t OpalBeamline::transformTo(const Vector_t &r) const {
+    return coordTransformationTo_m.transformTo(r);
+}
+
+inline
+Vector_t OpalBeamline::transformFrom(const Vector_t &r) const {
+    return coordTransformationTo_m.transformFrom(r);
+}
+
+inline
+Vector_t OpalBeamline::rotateTo(const Vector_t &r) const {
+    return coordTransformationTo_m.rotateTo(r);
+}
+
+inline
+Vector_t OpalBeamline::rotateFrom(const Vector_t &r) const {
+    return coordTransformationTo_m.rotateFrom(r);
+}
+
+inline
+Vector_t OpalBeamline::transformToLocalCS(const std::shared_ptr<Component> &comp,
+                                          const Vector_t &r) const {
+    return comp->getCSTrafoGlobal2Local().transformTo(r);
+}
+
+inline
+Vector_t OpalBeamline::transformFromLocalCS(const std::shared_ptr<Component> &comp,
+                                            const Vector_t &r) const {
+    return comp->getCSTrafoGlobal2Local().transformFrom(r);
+}
+
+inline
+Vector_t OpalBeamline::rotateToLocalCS(const std::shared_ptr<Component> &comp,
+                                       const Vector_t &r) const {
+    return comp->getCSTrafoGlobal2Local().rotateTo(r);
+}
+
+inline
+Vector_t OpalBeamline::rotateFromLocalCS(const std::shared_ptr<Component> &comp,
+                                         const Vector_t &r) const {
+    return comp->getCSTrafoGlobal2Local().rotateFrom(r);
+}
+
+inline
+CoordinateSystemTrafo OpalBeamline::getCSTrafoLab2Local(const std::shared_ptr<Component> &comp) const {
+    return comp->getCSTrafoGlobal2Local();
+}
+
+inline
+CoordinateSystemTrafo OpalBeamline::getCSTrafoLab2Local() const {
+    return coordTransformationTo_m;
+}
+
+inline
+CoordinateSystemTrafo OpalBeamline::getMisalignment(const std::shared_ptr<Component> &comp) const {
+    return comp->getMisalignment();
+}
+
+inline
+bool OpalBeamline::containsSource() {
+    return containsSource_m;
+}
+#endif // OPAL_BEAMLINE_H
\ No newline at end of file
diff --git a/src/Elements/OpalBend.cpp b/src/Elements/OpalBend.cpp
index 2ceabd8718be6aa2f43451963f7120afb98d9429..c5ac92c9d49deb706e2ef8a7e8814ef098bef342 100644
--- a/src/Elements/OpalBend.cpp
+++ b/src/Elements/OpalBend.cpp
@@ -48,9 +48,9 @@ OpalBend::OpalBend(const char *name, const char *help):
     itsAttr[K3S] = Attributes::makeReal
                    ("K3S", "Skew octupole coefficient in m^(-4)");
     itsAttr[E1] = Attributes::makeReal
-                  ("E1", "Entry pole face angle in rad");
+        ("E1", "Entry pole face angle in rad", 0.0);
     itsAttr[E2] = Attributes::makeReal
-                  ("E2", "Exit pole face angle in rad");
+        ("E2", "Exit pole face angle in rad", 0.0);
     itsAttr[H1] = Attributes::makeReal
                   ("H1", "Entry pole face curvature in m^(-1)");
     itsAttr[H2] = Attributes::makeReal
@@ -68,25 +68,14 @@ OpalBend::OpalBend(const char *name, const char *help):
     itsAttr[GAP] = Attributes::makeReal
                    ("GAP", "Full gap height of the magnet (m)", 0.0);
     itsAttr[HAPERT] = Attributes::makeReal
-                      ("HAPERT", "Non-bend plane magnet aperture (m)", 0.0);
+                      ("HAPERT", "Bend plane magnet aperture (m)", 0.0);
     itsAttr[ROTATION] = Attributes::makeReal
-                        ("ROTATION", "Magnet rotation about z axis in degrees");
-    itsAttr[ALPHA] = Attributes::makeReal
-                     ("ALPHA", "Pole face angle in degree");
-    itsAttr[BETA] = Attributes::makeReal
-                    ("BETA", "Pole face angle in degree");
-    itsAttr[EXITANGLE] = Attributes::makeReal
-                         ("EXITANGLE", "Angle between the entry and exit face (SBEND only)");
+                        ("ROTATION", "-- not supported any more; use PSI instead --");
     itsAttr[DESIGNENERGY] = Attributes::makeReal
-                            ("DESIGNENERGY", "the mean energy of the particles");
+                            ("DESIGNENERGY", "the mean energy of the particles in MeV");
     itsAttr[GREATERTHANPI] = Attributes::makeBool
                              ("GREATERTHANPI",
-                              "Set to true if bend angle is greater than 180 degrees",
-                              false);
-    itsAttr[DX] = Attributes::makeReal
-                  ("DX", "Misalignment in x direction", 0.0);
-    itsAttr[DY] = Attributes::makeReal
-                  ("DY", "Misalignment in y direction", 0.0);
+                              "-- not supported any more --");
 
     registerRealAttribute("ANGLE");
     registerRealAttribute("K0L");
@@ -109,12 +98,7 @@ OpalBend::OpalBend(const char *name, const char *help):
     registerRealAttribute("GAP");
     registerRealAttribute("HAPERT");
     registerRealAttribute("ROTATION");
-    registerRealAttribute("ALPHA");
-    registerRealAttribute("BETA");
-    registerRealAttribute("EXITANGLE");
     registerRealAttribute("DESIGNENERGY");
-    registerRealAttribute("DX");
-    registerRealAttribute("DY");
 }
 
 
@@ -131,4 +115,4 @@ void OpalBend::print(std::ostream &os) const {
 
     OpalElement::print(os);
 
-}
+}
\ No newline at end of file
diff --git a/src/Elements/OpalBend.h b/src/Elements/OpalBend.h
index d5bfcad45bbac8080bafdddc67b06dc61ac2aefc..08662556d9ef913ba40e628a8063bed7b56786cf 100644
--- a/src/Elements/OpalBend.h
+++ b/src/Elements/OpalBend.h
@@ -46,14 +46,9 @@ public:
         GAP,              // Full gap of magnet.
         HAPERT,           // Horizontal aperture of magnet.
         ROTATION,         // Magnet rotation about z axis.
-        ALPHA,            // The edge angle 1
-        BETA,             // The edge angle 2
         DESIGNENERGY,     // the design energy of the particles
-        EXITANGLE,        // the relative angle between the entry and the exit face
         GREATERTHANPI,    // Boolean flag set to true if bend angle is greater
         // than 180 degrees.
-        DX,             // Misalignment: translation in x direction
-        DY,             // Misalignment: translation in y direction
         SIZE              // Total number of attributes.
     };
 
diff --git a/src/Elements/OpalCCollimator.cpp b/src/Elements/OpalCCollimator.cpp
index 946f2959df28f52f43d721be18b2dd9f0a6e48b8..47e13ec22fec50cbeb79ab8ccdfcb4ba8f3b89b4 100644
--- a/src/Elements/OpalCCollimator.cpp
+++ b/src/Elements/OpalCCollimator.cpp
@@ -85,6 +85,8 @@ void OpalCCollimator::fillRegisteredAttributes(const ElementBase &base, ValueFla
 
 
 void OpalCCollimator::update() {
+    OpalElement::update();
+
     CollimatorRep *coll =
         dynamic_cast<CollimatorRep *>(getElement()->removeWrappers());
     double length = Attributes::getReal(itsAttr[LENGTH]);
@@ -106,25 +108,12 @@ void OpalCCollimator::update() {
     coll->setOutputFN(Attributes::getString(itsAttr[OUTFN]));
     coll->setCColl();
 
-    /*
-    std::vector<double> apert = getApert();
-    double apert_major = -1., apert_minor = -1.;
-    if(apert.size() > 0) {
-        apert_major = apert[0];
-        if(apert.size() > 1) {
-            apert_minor = apert[1];
-        } else {
-            apert_minor = apert[0];
-        }
-    }
-    */
     if(itsAttr[SURFACEPHYSICS] && sphys_m == NULL) {
         sphys_m = (SurfacePhysics::find(Attributes::getString(itsAttr[SURFACEPHYSICS])))->clone(getOpalName() + std::string("_sphys"));
         sphys_m->initSurfacePhysicsHandler(*coll);
         coll->setSurfacePhysics(sphys_m->handler_m);
     }
 
-
     // Transmit "unknown" attributes.
     OpalElement::updateUnknown(coll);
 }
diff --git a/src/Elements/OpalCavity.cpp b/src/Elements/OpalCavity.cpp
index 72c1326797b47e690285eb8658a211b61cb77665..ec4e5ac5947f878c1dac02ebaaff25de54f0e98a 100644
--- a/src/Elements/OpalCavity.cpp
+++ b/src/Elements/OpalCavity.cpp
@@ -18,16 +18,16 @@
 
 #include "Elements/OpalCavity.h"
 #include "AbstractObjects/Attribute.h"
-#include "Algorithms/AbstractTimeDependence.h"
 #include "Attributes/Attributes.h"
 #include "BeamlineCore/RFCavityRep.h"
+#include "Algorithms/AbstractTimeDependence.h"
 #include "Structure/OpalWake.h"
 #include "Structure/BoundaryGeometry.h"
 #include "Physics/Physics.h"
 
 extern Inform *gmsg;
 
-// Class OpalCavity for all flavours
+// Class OpalCavity
 // ------------------------------------------------------------------------
 
 OpalCavity::OpalCavity():
@@ -35,12 +35,16 @@ OpalCavity::OpalCavity():
                 "The \"RFCAVITY\" element defines an RF cavity."),
     owk_m(NULL),
     obgeo_m(NULL) {
-    itsAttr[VOLT] = Attributes::makeRealArray
+    itsAttr[VOLT] = Attributes::makeReal
                     ("VOLT", "RF voltage in MV");
-    itsAttr[FREQ] = Attributes::makeRealArray
+    itsAttr[DVOLT] = Attributes::makeReal
+                     ("DVOLT", "RF voltage error in MV");
+    itsAttr[FREQ] = Attributes::makeReal
 	            ("FREQ", "RF frequency in MHz");
-    itsAttr[LAG] = Attributes::makeRealArray
-                   ("LAG", "Phase lag (rad), !!!! was before in multiples of (2*pi) !!!!");
+    itsAttr[LAG] = Attributes::makeReal
+                   ("LAG", "Phase lag (rad)");
+    itsAttr[DLAG] = Attributes::makeReal
+                    ("DLAG", "Phase lag error (rad)");
     itsAttr[HARMON] = Attributes::makeReal
                       ("HARMON", "Harmonic number");
     itsAttr[BETARF] = Attributes::makeReal
@@ -51,16 +55,14 @@ OpalCavity::OpalCavity():
                       ("SHUNT", "Shunt impedance in MOhm");
     itsAttr[TFILL] = Attributes::makeReal
                      ("TFILL", "Fill time in microseconds");
-    itsAttr[FMAPFN] = Attributes::makeStringArray
-                      ("FMAPFN", "Filenames of the fieldmap(s)");
+    itsAttr[FMAPFN] = Attributes::makeString
+                      ("FMAPFN", "Filename of the fieldmap");
     itsAttr[GEOMETRY] = Attributes::makeString
                         ("GEOMETRY", "BoundaryGeometry for Cavities");
     itsAttr[FAST] = Attributes::makeBool
                     ("FAST", "Faster but less accurate", true);
     itsAttr[APVETO] = Attributes::makeBool
                     ("APVETO", "Do not use this cavity in the Autophase procedure", false);
-    itsAttr[CAVITYTYPE] = Attributes::makeString
-                          ("CAVITYTYPE", "STANDING or SINGLEGAP cavity in photoinjector and LINAC; SINGLEGAP or DOUBLEGAP cavity in cyclotron");
     itsAttr[RMIN] = Attributes::makeReal
                     ("RMIN", " Minimal Radius of a cyclotron cavity");
     itsAttr[RMAX] = Attributes::makeReal
@@ -73,13 +75,8 @@ OpalCavity::OpalCavity():
                         ("GAPWIDTH", "Gap width of a cyclotron cavity");
     itsAttr[PHI0] = Attributes::makeReal
                     ("PHI0", "initial phase of cavity");
-
-    itsAttr[DX] = Attributes::makeReal
-      ("DX", "Misalignment in x direction",0.0);
-    itsAttr[DY] = Attributes::makeReal
-      ("DY", "Misalignment in y direction",0.0);
-
-
+    itsAttr[DESIGNENERGY] = Attributes::makeReal
+                            ("DESIGNENERGY", "the mean energy of the particles at exit", -1.0);
     // attibutes for timedependent values
     itsAttr[PHASE_MODEL] = Attributes::makeString("PHASE_MODEL",
 						  "The name of the phase time dependence model.");
@@ -87,20 +84,21 @@ OpalCavity::OpalCavity():
 						      "The name of the amplitude time dependence model.");
     itsAttr[FREQUENCY_MODEL] = Attributes::makeString("FREQUENCY_MODEL",
 						      "The name of the frequency time dependence model.");
+
     registerRealAttribute("VOLT");
+    registerRealAttribute("DVOLT");
     registerRealAttribute("FREQ");
     registerRealAttribute("LAG");
+    registerRealAttribute("DLAG");
     registerStringAttribute("FMAPFN");
     registerStringAttribute("GEOMETRY");
-    registerStringAttribute("CAVITYTYPE");
     registerRealAttribute("RMIN");
     registerRealAttribute("RMAX");
     registerRealAttribute("ANGLE");
     registerRealAttribute("PDIS");
     registerRealAttribute("GAPWIDTH");
     registerRealAttribute("PHI0");
-    registerRealAttribute("DX");
-    registerRealAttribute("DY");
+    registerRealAttribute("DESIGNENERGY");
 
     // attibutes for timedependent values
     registerStringAttribute("PHASE_MODEL");
@@ -136,36 +134,31 @@ void OpalCavity::fillRegisteredAttributes(const ElementBase &base, ValueFlag fla
     if(flag != ERROR_FLAG) {
         const RFCavityRep *rfc =
             dynamic_cast<const RFCavityRep *>(base.removeWrappers());
-
         attributeRegistry["VOLT"]->setReal(rfc->getAmplitude());
         attributeRegistry["FREQ"]->setReal(rfc->getFrequency());
         attributeRegistry["LAG"]->setReal(rfc->getPhase());
         attributeRegistry["FMAPFN"]->setString(rfc->getFieldMapFN());
-        attributeRegistry["CAVITYTYPE"]->setString(rfc->getCavityType());
-        double dx, dy, dz;
-        rfc->getMisalignment(dx, dy, dz);
-        attributeRegistry["DX"]->setReal(dx);
-        attributeRegistry["DY"]->setReal(dy);
     }
 }
 
 
 void OpalCavity::update() {
+    OpalElement::update();
 
     using Physics::two_pi;
     RFCavityRep *rfc =
         dynamic_cast<RFCavityRep *>(getElement()->removeWrappers());
 
     double length = Attributes::getReal(itsAttr[LENGTH]);
-    std::vector<double> vPeak  = Attributes::getRealArray(itsAttr[VOLT]);
-    std::vector<double> phase  = Attributes::getRealArray(itsAttr[LAG]);
-    std::vector<double> freq   = Attributes::getRealArray(itsAttr[FREQ]);
-    std::vector<std::string> fmapfns = Attributes::getStringArray(itsAttr[FMAPFN]);
+    double peak  = Attributes::getReal(itsAttr[VOLT]);
+    double peakError  = Attributes::getReal(itsAttr[DVOLT]);
+    double phase  = Attributes::getReal(itsAttr[LAG]);
+    double phaseError  = Attributes::getReal(itsAttr[DLAG]);
+    double freq   = 1e6 * two_pi * Attributes::getReal(itsAttr[FREQ]);
+    std::string fmapfn = Attributes::getString(itsAttr[FMAPFN]);
     std::string type = Attributes::getString(itsAttr[TYPE]);
     bool fast = Attributes::getBool(itsAttr[FAST]);
-    double max_freq = 0.0;
-    for (size_t i = 0; i < freq.size(); ++ i) max_freq = std::max(std::abs(freq[i]), max_freq);
-    bool apVeto = (Attributes::getBool(itsAttr[APVETO]) || max_freq < 1e-9);
+    bool apVeto = (Attributes::getBool(itsAttr[APVETO]) || freq < 1e-3);
 
     double rmin = Attributes::getReal(itsAttr[RMIN]);
     double rmax = Attributes::getReal(itsAttr[RMAX]);
@@ -173,8 +166,7 @@ void OpalCavity::update() {
     double pdis = Attributes::getReal(itsAttr[PDIS]);
     double gapwidth = Attributes::getReal(itsAttr[GAPWIDTH]);
     double phi0 = Attributes::getReal(itsAttr[PHI0]);
-    double dx = Attributes::getReal(itsAttr[DX]);
-    double dy = Attributes::getReal(itsAttr[DY]);
+    double kineticEnergy = Attributes::getReal(itsAttr[DESIGNENERGY]);
 
     if(itsAttr[WAKEF] && owk_m == NULL) {
         owk_m = (OpalWake::find(Attributes::getString(itsAttr[WAKEF])))->clone(getOpalName() + std::string("_wake"));
@@ -189,36 +181,20 @@ void OpalCavity::update() {
         }
     }
 
-    rfc->setMisalignment(dx, dy, 0.0);
-
     rfc->setElementLength(length);
 
-    double peak = 0.0, frequency = 0.0, phi = 0.0;
-    if (vPeak.size() > 0) peak = vPeak[0];
-    rfc->setAmplitude(1.0e6 * peak);
-    if (freq.size() > 0) frequency = 1.0e6 * two_pi * freq[0];
-    rfc->setFrequency(frequency);
-    if (phase.size() > 0) phi = phase[0];
-    rfc->setPhase(phi);
+    rfc->setAmplitude(1e6 * peak);
+    rfc->setFrequency(freq);
+    rfc->setPhase(phase);
 
     rfc->dropFieldmaps();
 
-    std::vector<double>::iterator peak_it;
-    for (peak_it = vPeak.begin(); peak_it != vPeak.end(); ++ peak_it) {
-        rfc->setAmplitudem(*peak_it);
-    }
-    std::vector<double>::iterator freq_it;
-    for (freq_it = freq.begin(); freq_it != freq.end(); ++ freq_it) {
-        rfc->setFrequencym(1.0e6 * two_pi * (*freq_it));
-    }
-    std::vector<double>::iterator phase_it;
-    for (phase_it = phase.begin(); phase_it != phase.end(); ++ phase_it) {
-        rfc->setPhasem(*phase_it);
-    }
-    std::vector<std::string>::iterator fmap_it;
-    for (fmap_it = fmapfns.begin(); fmap_it != fmapfns.end(); ++ fmap_it) {
-        rfc->setFieldMapFN(*fmap_it);
-    }
+    rfc->setAmplitudem(peak);
+    rfc->setAmplitudeError(peakError);
+    rfc->setFrequencym(freq);
+    rfc->setPhasem(phase);
+    rfc->setPhaseError(phaseError);
+    rfc->setFieldMapFN(fmapfn);
 
     rfc->setFast(fast);
     rfc->setAutophaseVeto(apVeto);
@@ -230,11 +206,12 @@ void OpalCavity::update() {
     rfc->setPerpenDistance(pdis);
     rfc->setGapWidth(gapwidth);
     rfc->setPhi0(phi0);
+    rfc->setDesignEnergy(kineticEnergy);
 
-    rfc->setPhaseModelName(Attributes::getString(itsAttr[PHASE_MODEL]));    
-    rfc->setAmplitudeModelName(Attributes::getString(itsAttr[AMPLITUDE_MODEL]));    
+    rfc->setPhaseModelName(Attributes::getString(itsAttr[PHASE_MODEL]));
+    rfc->setAmplitudeModelName(Attributes::getString(itsAttr[AMPLITUDE_MODEL]));
     rfc->setFrequencyModelName(Attributes::getString(itsAttr[FREQUENCY_MODEL]));
 
     // Transmit "unknown" attributes.
     OpalElement::updateUnknown(rfc);
-}
+}
\ No newline at end of file
diff --git a/src/Elements/OpalCavity.h b/src/Elements/OpalCavity.h
index d1bcabb358bcf7fe325223ed4071102d5783bf28..9b140c2eba447d5985f18e9742b8d8c5d3eaea69 100644
--- a/src/Elements/OpalCavity.h
+++ b/src/Elements/OpalCavity.h
@@ -34,9 +34,11 @@ public:
     /// The attributes of class OpalCavity.
     enum {
         VOLT = COMMON,  // The peak voltage.
+        DVOLT,          // The peak voltage error.
         GEOMETRY,       // geometry of boundary
         FREQ,           // The RF frequency.
         LAG,            // The phase lag.
+        DLAG,           // The phase lag error.
         HARMON,         // The harmonic number.
         BETARF,         // The beta_RF.
         PG,             // The RF power.
@@ -45,18 +47,16 @@ public:
         FMAPFN,         // The filename of the fieldmap
         FAST,           // Faster but less accurate
         APVETO,         // Do not use this cavity in the Autophase procedure
-        CAVITYTYPE,     // STANDING or SINGLEGAP structure
         RMIN,           // Minimal Radius
         RMAX,           // Maximal Radius
         ANGLE,          // the azimuth position of the cavity
         PDIS,           // perpendicular distance from symmetric line of cavity gap to machine center
         GAPWIDTH,       // constant gap width of cavity
         PHI0,           // initial phase of cavity
-	PHASE_MODEL,    // time dependent parameter
-	AMPLITUDE_MODEL,// time dependent parameter
-	FREQUENCY_MODEL,// time dependent parameter
-        DX,             // Misalignment: translation in x direction
-        DY,             // Misalignment: translation in y direction
+        DESIGNENERGY,   // The mean kinetic energy at exit
+	PHASE_MODEL,    // time dependent phase
+	AMPLITUDE_MODEL,// time dependent amplitude
+	FREQUENCY_MODEL,// time dependent frequency
         SIZE
     };
 
diff --git a/src/Elements/OpalCyclotron.cpp b/src/Elements/OpalCyclotron.cpp
index 83228eee2cd07ef6e119efa6aade253c3ee354a3..7dbdc57ea62ebc591330fc907c5655bb0070382f 100644
--- a/src/Elements/OpalCyclotron.cpp
+++ b/src/Elements/OpalCyclotron.cpp
@@ -260,7 +260,7 @@ void OpalCyclotron::update() {
 
     unsigned int vsize = tcr1v.size();
 
-    if ((tcr1v.size() == vsize) && (tcr2v.size() == vsize) && 
+    if ((tcr1v.size() == vsize) && (tcr2v.size() == vsize) &&
 	(mbtcv.size() == vsize) && (slptcv.size() == vsize) && (vsize!=0)) {
       cycl->setTCr1V(tcr1v);
       cycl->setTCr2V(tcr2v);
diff --git a/src/Elements/OpalCyclotron.h b/src/Elements/OpalCyclotron.h
index f061ba8cf445c040bb1d3eb0950808cc6d0e9349..0a1995a560dc49491777735378dabd19da34600a 100644
--- a/src/Elements/OpalCyclotron.h
+++ b/src/Elements/OpalCyclotron.h
@@ -31,7 +31,7 @@ public:
 
     /// The attributes of class OpalCyclotron.
     enum {
-        TYPE,
+        TYPE = COMMON,
         GEOMETRY,  // geometry of boundary
         CYHARMON,  // The harmonic number of the cyclotron
         SYMMETRY,  // The symetry of the field
@@ -43,8 +43,8 @@ public:
         RFFREQ,    // First hamonic of the RF system [MHz]
         FMAPFN,    // The filename of the mid-plane fieldmap
         RFMAPFN,   // The filename(s) of the RF fieldmap
-	RFFCFN,    // The filename(s) of coefficients for RF frequency function f(t) 
-	RFVCFN,    // The filename(s) of coefficients for RF voltage function v(t) 
+	RFFCFN,    // The filename(s) of coefficients for RF frequency function f(t)
+	RFVCFN,    // The filename(s) of coefficients for RF voltage function v(t)
         BSCALE,    // A scalar to scale the B-field
         ESCALE,    // A scalar to scale the RF field
         TCR1,      // trim coil r1 (mm)
diff --git a/src/Elements/OpalCyclotronValley.cpp b/src/Elements/OpalCyclotronValley.cpp
index 5977285e0fa9811095f48e26231afc6229d7449c..2d509ff28fc21cad001b15bc27ac71ba16a7e5fb 100644
--- a/src/Elements/OpalCyclotronValley.cpp
+++ b/src/Elements/OpalCyclotronValley.cpp
@@ -33,18 +33,9 @@ OpalCyclotronValley::OpalCyclotronValley():
 
     itsAttr[FMAPFN] = Attributes::makeString
                       ("FMAPFN", "Filename for the fieldmap");
-    itsAttr[DX] = Attributes::makeReal
-      ("DX", "Misalignment in x direction",0.0);
-    itsAttr[DY] = Attributes::makeReal
-      ("DY", "Misalignment in y direction",0.0);
-    itsAttr[DZ] = Attributes::makeReal
-      ("DZ", "Misalignment in z direction",0.0);
     itsAttr[BFLG] = Attributes::makeReal
                   ("BFLG", "B flag");
     registerStringAttribute("FMAPFN");
-    registerRealAttribute("DX");
-    registerRealAttribute("DY");
-    registerRealAttribute("DZ");
     registerRealAttribute("BFLG");
     setElement((new CyclotronValleyRep("CyclotronValley"))->makeAlignWrapper());
 }
@@ -73,33 +64,26 @@ void OpalCyclotronValley::fillRegisteredAttributes(const ElementBase &base, Valu
         const CyclotronValleyRep *cv =
             dynamic_cast<const CyclotronValleyRep *>(base.removeWrappers());
         attributeRegistry["FMAPFN"]->setString(cv->getFieldMapFN());
-        double dx, dy, dz, bflg=1.0;
-        cv->getMisalignment(dx, dy, dz);
-        attributeRegistry["DX"]->setReal(dx);
-        attributeRegistry["DY"]->setReal(dy);
-        attributeRegistry["DZ"]->setReal(dz);
 
-        attributeRegistry["BFLG"]->setReal(bflg);
+        attributeRegistry["BFLG"]->setReal(1.0);
     }
 }
 
 
 void OpalCyclotronValley::update() {
+    OpalElement::update();
+
     using Physics::two_pi;
     CyclotronValleyRep *cv =
         dynamic_cast<CyclotronValleyRep *>(getElement()->removeWrappers());
 
 
     std::string fmapfm = Attributes::getString(itsAttr[FMAPFN]);
-    double dx = Attributes::getReal(itsAttr[DX]);
-    double dy = Attributes::getReal(itsAttr[DY]);
-    double dz = Attributes::getReal(itsAttr[DZ]);
-
-    cv->setMisalignment(dx, dy, dz);
 
     cv->setFieldMapFN(fmapfm);
 
     cv->setFast(false);//fast flag for cyclotronvalley has not been implemented yet.
+
     // Transmit "unknown" attributes.
     OpalElement::updateUnknown(cv);
 }
diff --git a/src/Elements/OpalCyclotronValley.h b/src/Elements/OpalCyclotronValley.h
index 0be4e649681e1ffd50dbf8f1261d3f78d17e7f8c..cd0b6917fb1954689e726b67d91b7bb044a52750 100644
--- a/src/Elements/OpalCyclotronValley.h
+++ b/src/Elements/OpalCyclotronValley.h
@@ -32,11 +32,7 @@ public:
 
     /// The attributes of class OpalCyclotronValley.
     enum {
-
-        FMAPFN,         // The filename of the fieldmap
-        DX,             // Misalignment: translation in x direction
-        DY,             // Misalignment: translation in y direction
-        DZ,             // Misalignment: translation in z direction
+        FMAPFN = COMMON,         // The filename of the fieldmap
         BFLG,
         SIZE
     };
diff --git a/src/Elements/OpalDegrader.cpp b/src/Elements/OpalDegrader.cpp
index 19bf598d41ec33d91a7df343987a592adb40f8af..3c2192ca2358005dcff11558c801ab18985c8238 100644
--- a/src/Elements/OpalDegrader.cpp
+++ b/src/Elements/OpalDegrader.cpp
@@ -35,14 +35,8 @@ OpalDegrader::OpalDegrader():
         ("YSIZE", "not used",0.0);
     itsAttr[OUTFN] = Attributes::makeString
         ("OUTFN", "Degrader output filename");
-    itsAttr[DX] = Attributes::makeReal
-        ("DX", "not used",0.0);
-    itsAttr[DY] = Attributes::makeReal
-        ("DY", "not used",0.0);
 
     registerStringAttribute("OUTFN");
-    registerRealAttribute("DX");
-    registerRealAttribute("DY");
 
     setElement((new DegraderRep("DEGRADER"))->makeAlignWrapper());
 }
@@ -68,38 +62,19 @@ OpalDegrader *OpalDegrader::clone(const std::string &name) {
 
 void OpalDegrader::fillRegisteredAttributes(const ElementBase &base, ValueFlag flag) {
     OpalElement::fillRegisteredAttributes(base, flag);
-
-    const DegraderRep *deg =
-        dynamic_cast<const DegraderRep *>(base.removeWrappers());
-
-    double dx, dy, dz;
-    deg->getMisalignment(dx, dy, dz);
 }
 
 
 void OpalDegrader::update() {
+    OpalElement::update();
 
     DegraderRep *deg =
         dynamic_cast<DegraderRep *>(getElement()->removeWrappers());
     double length = Attributes::getReal(itsAttr[LENGTH]);
     deg->setElementLength(length);
-    deg->setZSize(length);
 
     deg->setOutputFN(Attributes::getString(itsAttr[OUTFN]));
-    deg->setMisalignment(0.0, 0.0, 0.0);
-
-    /*
-    std::vector<double> apert = getApert();
-    double apert_major = -1., apert_minor = -1.;
-    if(apert.size() > 0) {
-        apert_major = apert[0];
-        if(apert.size() > 1) {
-            apert_minor = apert[1];
-        } else {
-            apert_minor = apert[0];
-        }
-    }
-    */
+
     if(itsAttr[SURFACEPHYSICS] && sphys_m == NULL) {
         sphys_m = (SurfacePhysics::find(Attributes::getString(itsAttr[SURFACEPHYSICS])))->clone(getOpalName() + std::string("_sphys"));
         sphys_m->initSurfacePhysicsHandler(*deg);
diff --git a/src/Elements/OpalDegrader.h b/src/Elements/OpalDegrader.h
index f36b646c413189fa72de976c6746f35467121db8..407cd68bd28b84b8750a13cb90888a20e9d0abc5 100644
--- a/src/Elements/OpalDegrader.h
+++ b/src/Elements/OpalDegrader.h
@@ -35,8 +35,6 @@ public:
         XSIZE = COMMON,  // not used
         YSIZE,           // not used
         OUTFN,
-        DX,             // Misalignment: translation in x direction
-        DY,             // Misalignment: translation in y direction
         SIZE
     };
 
diff --git a/src/Elements/OpalDrift.cpp b/src/Elements/OpalDrift.cpp
index 4c3c5d9ea62bd168852ed527143533015d953105..02d08ae77b389d5bd40215d0e4f2a7c73bd521e9 100644
--- a/src/Elements/OpalDrift.cpp
+++ b/src/Elements/OpalDrift.cpp
@@ -76,6 +76,7 @@ bool OpalDrift::isDrift() const {
 
 
 void OpalDrift::update() {
+    OpalElement::update();
 
     DriftRep *drf = static_cast<DriftRep *>(getElement());
     drf->setElementLength(Attributes::getReal(itsAttr[LENGTH]));
@@ -84,18 +85,7 @@ void OpalDrift::update() {
         owk_m->initWakefunction(*drf);
         drf->setWake(owk_m->wf_m);
     }
-    /*
-    std::vector<double> apert = getApert();
-    double apert_major = -1., apert_minor = -1.;
-    if(apert.size() > 0) {
-        apert_major = apert[0];
-        if(apert.size() > 1) {
-            apert_minor = apert[1];
-        } else {
-            apert_minor = apert[0];
-        }
-    }
-    */
+
     if(itsAttr[SURFACEPHYSICS] && sphys_m == NULL) {
         sphys_m = (SurfacePhysics::find(Attributes::getString(itsAttr[SURFACEPHYSICS])))->clone(getOpalName() + std::string("_sphys"));
         sphys_m->initSurfacePhysicsHandler(*drf);
@@ -108,7 +98,6 @@ void OpalDrift::update() {
         }
     }
 
-
     // Transmit "unknown" attributes.
     OpalElement::updateUnknown(drf);
 }
diff --git a/src/Elements/OpalECollimator.cpp b/src/Elements/OpalECollimator.cpp
index 15de6a83313ead795e4fa061b1431ad8a71949ff..65ffdb2a9aa52c9142621d17cd94fdb25206335a 100644
--- a/src/Elements/OpalECollimator.cpp
+++ b/src/Elements/OpalECollimator.cpp
@@ -35,17 +35,11 @@ OpalECollimator::OpalECollimator():
                      ("YSIZE", "Vertical half-aperture in m");
     itsAttr[OUTFN] = Attributes::makeString
                      ("OUTFN", "Monitor output filename");
-    itsAttr[DX] = Attributes::makeReal
-      ("DX", "Misalignment in x direction",0.0);
-    itsAttr[DY] = Attributes::makeReal
-      ("DY", "Misalignment in y direction",0.0);
 
 
     registerStringAttribute("OUTFN");
     registerRealAttribute("XSIZE");
     registerRealAttribute("YSIZE");
-    registerRealAttribute("DX");
-    registerRealAttribute("DY");
     setElement((new CollimatorRep("ECOLLIMATOR"))->makeAlignWrapper());
 }
 
@@ -75,17 +69,11 @@ void OpalECollimator::fillRegisteredAttributes(const ElementBase &base, ValueFla
         dynamic_cast<const CollimatorRep *>(base.removeWrappers());
     attributeRegistry["XSIZE"]->setReal(coll->getXsize());
     attributeRegistry["YSIZE"]->setReal(coll->getYsize());
-    double dx, dy, dz;
-    coll->getMisalignment(dx, dy, dz);
-    attributeRegistry["DX"]->setReal(dx);
-    attributeRegistry["DY"]->setReal(dy);
 }
 
 
 void OpalECollimator::update() {
-
-    double dx = Attributes::getReal(itsAttr[DX]);
-    double dy = Attributes::getReal(itsAttr[DY]);
+    OpalElement::update();
 
     CollimatorRep *coll =
         dynamic_cast<CollimatorRep *>(getElement()->removeWrappers());
@@ -94,19 +82,7 @@ void OpalECollimator::update() {
     coll->setXsize(Attributes::getReal(itsAttr[XSIZE]));
     coll->setYsize(Attributes::getReal(itsAttr[YSIZE]));
     coll->setOutputFN(Attributes::getString(itsAttr[OUTFN]));
-    coll->setMisalignment(dx, dy, 0.0);
-    /*
-    std::vector<double> apert = getApert();
-    double apert_major = -1., apert_minor = -1.;
-    if(apert.size() > 0) {
-        apert_major = apert[0];
-        if(apert.size() > 1) {
-            apert_minor = apert[1];
-        } else {
-            apert_minor = apert[0];
-        }
-    }
-    */
+
     if(itsAttr[SURFACEPHYSICS] && sphys_m == NULL) {
         sphys_m = (SurfacePhysics::find(Attributes::getString(itsAttr[SURFACEPHYSICS])))->clone(getOpalName() + std::string("_sphys"));
         sphys_m->initSurfacePhysicsHandler(*coll);
diff --git a/src/Elements/OpalECollimator.h b/src/Elements/OpalECollimator.h
index 9915eefb315881ed7f1b02c87d46e52035f25cda..9caac1cc78a750bff27ef749c4371bb1bb149158 100644
--- a/src/Elements/OpalECollimator.h
+++ b/src/Elements/OpalECollimator.h
@@ -35,8 +35,6 @@ public:
         XSIZE = COMMON,  // The horizontal half-size.
         YSIZE,           // The vertical half-size.
         OUTFN,
-        DX,             // Misalignment: translation in x direction
-        DY,             // Misalignment: translation in y direction
         SIZE
     };
 
diff --git a/src/Elements/OpalElement.cpp b/src/Elements/OpalElement.cpp
index cab09a88436cb3f07553c1088cbe0f4327c9e2eb..03f8a66c70a6857c959ba309316a264bc83ed2e9 100644
--- a/src/Elements/OpalElement.cpp
+++ b/src/Elements/OpalElement.cpp
@@ -21,6 +21,7 @@
 #include "Elements/OpalElement.h"
 #include "AbsBeamline/AlignWrapper.h"
 #include "AbsBeamline/ElementImage.h"
+#include "AbsBeamline/Bend.h"
 #include "AbstractObjects/Attribute.h"
 #include "AbstractObjects/Expressions.h"
 #include "AbstractObjects/OpalData.h"
@@ -31,6 +32,8 @@
 #include "Utilities/Options.h"
 #include "Utilities/ParseError.h"
 #include "Utilities/Round.h"
+#include "Utilities/Util.h"
+
 #include <cmath>
 #include <cctype>
 #if defined(__GNUC__) && __GNUC__ < 3
@@ -39,13 +42,95 @@
 #include <sstream>
 #endif
 #include <vector>
+#include <boost/regex.hpp>
 
-
+extern Inform *gmsg;
 // Class OpalElement
 // ------------------------------------------------------------------------
 
 std::map < std::string, OwnPtr<AttCell> > OpalElement::attributeRegistry;
 
+OpalElement::OpalElement(int size, const char *name, const char *help):
+    Element(size, name, help), itsSize(size) {
+    itsAttr[TYPE]   = Attributes::makeString
+                      ("TYPE", "The element design type (the project name)");
+    itsAttr[LENGTH] = Attributes::makeReal
+                      ("L", "The element length in m");
+    itsAttr[APERT]  = Attributes::makeString
+                      ("APERTURE", "The element aperture");
+    itsAttr[WAKEF]   = Attributes::makeString
+                       ("WAKEF", "Defines the wake function");
+    itsAttr[SURFACEPHYSICS]   = Attributes::makeString
+                                ("SURFACEPHYSICS", "Defines the surface physics handler");
+    itsAttr[ORIGIN] = Attributes::makeRealArray
+                      ("ORIGIN", "The location of the element");
+
+    itsAttr[ORIENTATION] = Attributes::makeRealArray
+                           ("ORIENTATION", "The Tait-Bryan angles for the orientation of the element");
+
+    itsAttr[X] = Attributes::makeReal
+        ("X", "The x-coordinate of the location of the element", 0);
+
+    itsAttr[Y] = Attributes::makeReal
+        ("Y", "The y-coordinate of the location of the element", 0);
+
+    itsAttr[Z] = Attributes::makeReal
+        ("Z", "The z-coordinate of the location of the element", 0);
+
+    itsAttr[THETA] = Attributes::makeReal
+        ("THETA", "The rotation about the y-axis of the element", 0);
+
+    itsAttr[PHI] = Attributes::makeReal
+        ("PHI", "The rotation about the x-axis of the element", 0);
+
+    itsAttr[PSI] = Attributes::makeReal
+        ("PSI", "The rotation about the z-axis of the element", 0);
+
+    itsAttr[DX] = Attributes::makeReal
+                  ("DX", "Misalignment in x direction",0.0);
+    itsAttr[DY] = Attributes::makeReal
+                  ("DY", "Misalignment in y direction",0.0);
+    itsAttr[DZ] = Attributes::makeReal
+                  ("DZ", "Misalignment in z direction",0.0);
+    itsAttr[DTHETA] = Attributes::makeReal
+                  ("DTHETA", "Misalignment in theta (Tait-Bryan angles)",0.0);
+    itsAttr[DPHI] = Attributes::makeReal
+                  ("DPHI", "Misalignment in theta (Tait-Bryan angles)",0.0);
+    itsAttr[DPSI] = Attributes::makeReal
+                  ("DPSI", "Misalignment in theta (Tait-Bryan angles)",0.0);
+
+    static bool first = true;
+    if(first) {
+        registerStringAttribute("NAME");
+        registerStringAttribute("TYPE");
+        registerStringAttribute("CLASS");
+        registerStringAttribute("KEYWORD");
+        registerRealAttribute("L");
+        registerStringAttribute("WAKEF");
+        registerStringAttribute("SURFACEPHYSICS");
+        registerStringAttribute("APERT");
+        registerRealAttribute("X");
+        registerRealAttribute("Y");
+        registerRealAttribute("Z");
+        registerRealAttribute("THETA");
+        registerRealAttribute("PHI");
+        registerRealAttribute("PSI");
+        registerRealAttribute("DX");
+        registerRealAttribute("DY");
+        registerRealAttribute("DZ");
+        registerRealAttribute("DTHETA");
+        registerRealAttribute("DPHI");
+        registerRealAttribute("DPSI");
+        first = false;
+    }
+
+}
+
+
+OpalElement::OpalElement(const std::string &name, OpalElement *parent):
+    Element(name, parent), itsSize(parent->itsSize)
+{}
+
 
 OpalElement::~OpalElement()
 {}
@@ -60,19 +145,40 @@ fillRegisteredAttributes(const ElementBase &base, ValueFlag) {
     attributeRegistry["KEYWORD"]->setString(getBaseObject()->getOpalName());
     attributeRegistry["L"]->setReal(base.getElementLength());
 
+    CoordinateSystemTrafo global2local = base.getCSTrafoGlobal2Local();
+    Vector_t origin = global2local.getOrigin();
+    Vector_t orientation = Util::getTaitBryantAngles(global2local.getRotation().conjugate());
+    attributeRegistry["X"]->setReal(origin[0]);
+    attributeRegistry["Y"]->setReal(origin[1]);
+    attributeRegistry["Z"]->setReal(origin[2]);
+    attributeRegistry["THETA"]->setReal(orientation[0]);
+    attributeRegistry["PHI"]->setReal(orientation[1]);
+    attributeRegistry["PSI"]->setReal(orientation[2]);
+
     // Misalignments.
     const AlignWrapper *wrap = dynamic_cast<const AlignWrapper *>(&base);
     if(wrap) {
-        double dx, dy, ds, dphi, dtheta, dpsi;
-        wrap->offset().getAll(dx, dy, ds, dtheta, dphi, dpsi);
+        double dx, dy, dz, dphi, dtheta, dpsi;
+        wrap->offset().getAll(dx, dy, dz, dtheta, dphi, dpsi);
         attributeRegistry["DX"]->setReal(dx);
         attributeRegistry["DY"]->setReal(dy);
-        attributeRegistry["DELTAS"]->setReal(ds);
+        attributeRegistry["DZ"]->setReal(dz);
         attributeRegistry["DTHETA"]->setReal(dtheta);
         attributeRegistry["DPHI"]->setReal(dphi);
         attributeRegistry["DPSI"]->setReal(dpsi);
     }
 
+    CoordinateSystemTrafo misalignment = base.getMisalignment();
+    Vector_t misalignmentShift = misalignment.getOrigin();
+    Vector_t misalignmentAngles = Util::getTaitBryantAngles(misalignment.getRotation().conjugate());
+
+    attributeRegistry["DX"]->setReal(misalignmentShift(0));
+    attributeRegistry["DY"]->setReal(misalignmentShift(1));
+    attributeRegistry["DZ"]->setReal(misalignmentShift(2));
+    attributeRegistry["DTHETA"]->setReal(misalignmentAngles[0]);
+    attributeRegistry["DPHI"]->setReal(misalignmentAngles[1]);
+    attributeRegistry["DPSI"]->setReal(misalignmentAngles[2]);
+
     // Fill in the "unknown" attributes.
     ElementImage *image = base.ElementBase::getImage();
     AttributeSet::const_iterator cur = image->begin();
@@ -107,8 +213,154 @@ AttCell *OpalElement::findRegisteredAttribute(const std::string &name) {
     return cell;
 }
 
-std::vector<double> OpalElement::getApert() const {
-    return Attributes::getRealArray(itsAttr[APERT]);
+std::pair<ElementBase::ApertureType, std::vector<double> > OpalElement::getApert() const {
+    std::string aperture = Attributes::getString(itsAttr[APERT]);
+
+    std::pair<ElementBase::ApertureType, std::vector<double> > retvalue(ElementBase::ELLIPTICAL,
+                                                                        std::vector<double>({0.5, 0.5, 1.0}));
+    boost::regex square("square *\\((.*)\\)", boost::regex::icase);
+    boost::regex rectangle("rectangle *\\((.*)\\)", boost::regex::icase);
+    boost::regex circle("circle *\\((.*)\\)", boost::regex::icase);
+    boost::regex ellipse("ellipse *\\((.*)\\)", boost::regex::icase);
+
+    boost::regex twoArguments("([^,]*),([^,]*)");
+    boost::regex threeArguments("([^,]*),([^,]*),([^,]*)");
+
+    boost::smatch match;
+
+    const double width2HalfWidth = 0.5;
+
+    if (boost::regex_search(aperture, match, square)) {
+        std::string arguments = match[1];
+        if (!boost::regex_search(arguments, match, twoArguments)) {
+            retvalue.first = ElementBase::RECTANGULAR;
+
+            try {
+                retvalue.second[0] = width2HalfWidth * std::stod(arguments);
+                retvalue.second[1] = retvalue.second[0];
+            } catch (const std::exception &ex) {
+                throw OpalException("OpalElement::getApert()",
+                                    "could not convert '" + arguments + "' to double");
+            }
+
+        } else {
+            retvalue.first = ElementBase::CONIC_RECTANGULAR;
+
+            try {
+                retvalue.second[0] = width2HalfWidth * std::stod(match[1]);
+                retvalue.second[1] = retvalue.second[0];
+                retvalue.second[2] = std::stod(match[2]);
+            } catch (const std::exception &ex) {
+                throw OpalException("OpalElement::getApert()",
+                                    "could not convert '" + arguments + "' to doubles");
+            }
+        }
+
+        return retvalue;
+    }
+
+    if (boost::regex_search(aperture, match, rectangle)) {
+        std::string arguments = match[1];
+
+        if (!boost::regex_search(arguments, match, threeArguments)) {
+            retvalue.first = ElementBase::RECTANGULAR;
+
+            try {
+                size_t sz = 0;
+
+                retvalue.second[0] = width2HalfWidth * std::stod(arguments, &sz);
+                sz = arguments.find_first_of(",", sz) + 1;
+                retvalue.second[1] = width2HalfWidth * std::stod(arguments.substr(sz));
+
+            } catch (const std::exception &ex) {
+                throw OpalException("OpalElement::getApert()",
+                                    "could not convert '" + arguments + "' to doubles");
+            }
+
+        } else {
+            retvalue.first = ElementBase::CONIC_RECTANGULAR;
+
+            try {
+                retvalue.second[0] = width2HalfWidth * std::stod(match[1]);
+                retvalue.second[1] = width2HalfWidth * std::stod(match[2]);
+                retvalue.second[2] = std::stod(match[3]);
+            } catch (const std::exception &ex) {
+                throw OpalException("OpalElement::getApert()",
+                                    "could not convert '" + arguments + "' to doubles");
+            }
+        }
+
+        return retvalue;
+    }
+
+    if (boost::regex_search(aperture, match, circle)) {
+        std::string arguments = match[1];
+        if (!boost::regex_search(arguments, match, twoArguments)) {
+            retvalue.first = ElementBase::ELLIPTICAL;
+
+            try {
+                retvalue.second[0] = width2HalfWidth * std::stod(arguments);
+                retvalue.second[1] = retvalue.second[0];
+            } catch (const std::exception &ex) {
+                throw OpalException("OpalElement::getApert()",
+                                    "could not convert '" + arguments + "' to double");
+            }
+
+        } else {
+            retvalue.first = ElementBase::CONIC_ELLIPTICAL;
+
+            try {
+                retvalue.second[0] = width2HalfWidth * std::stod(match[1]);
+                retvalue.second[1] = retvalue.second[0];
+                retvalue.second[2] = std::stod(match[2]);
+            } catch (const std::exception &ex) {
+                throw OpalException("OpalElement::getApert()",
+                                    "could not convert '" + arguments + "' to doubles");
+            }
+        }
+
+        return retvalue;
+    }
+
+    if (boost::regex_search(aperture, match, ellipse)) {
+        std::string arguments = match[1];
+
+        if (!boost::regex_search(arguments, match, threeArguments)) {
+            retvalue.first = ElementBase::ELLIPTICAL;
+
+            try {
+                size_t sz = 0;
+
+                retvalue.second[0] = width2HalfWidth * std::stod(arguments, &sz);
+                sz = arguments.find_first_of(",", sz) + 1;
+                retvalue.second[1] = width2HalfWidth * std::stod(arguments.substr(sz));
+
+            } catch (const std::exception &ex) {
+                throw OpalException("OpalElement::getApert()",
+                                    "could not convert '" + arguments + "' to doubles");
+            }
+
+        } else {
+            retvalue.first = ElementBase::CONIC_ELLIPTICAL;
+
+            try {
+                retvalue.second[0] = width2HalfWidth * std::stod(match[1]);
+                retvalue.second[1] = width2HalfWidth * std::stod(match[2]);
+                retvalue.second[2] = std::stod(match[3]);
+            } catch (const std::exception &ex) {
+                throw OpalException("OpalElement::getApert()",
+                                    "could not convert '" + arguments + "' to doubles");
+            }
+        }
+
+        return retvalue;
+    }
+
+    if (aperture != "")
+        throw OpalException("OpalElement::getApert()",
+                            "Unknown aperture type '" + aperture + "'.");
+
+    return retvalue;
 }
 
 double OpalElement::getLength() const {
@@ -315,6 +567,91 @@ void OpalElement::printMultipoleStrength
     }
 }
 
+void OpalElement::update() {
+    ElementBase *base = getElement()->removeWrappers();
+
+    auto apert = getApert();
+    base->setAperture(apert.first, apert.second);
+
+    if (itsAttr[ORIGIN] || itsAttr[ORIENTATION]) {
+        std::vector<double> ori = Attributes::getRealArray(itsAttr[ORIGIN]);
+        std::vector<double> dir = Attributes::getRealArray(itsAttr[ORIENTATION]);
+        Vector_t origin(0.0);
+        Quaternion rotation;
+
+        if (dir.size() == 3) {
+            Quaternion rotTheta(cos(0.5 * dir[0]), 0,                 sin(0.5 * dir[0]), 0);
+            Quaternion rotPhi(cos(0.5 * dir[1]),   sin(0.5 * dir[1]), 0,                 0);
+            Quaternion rotPsi(cos(0.5 * dir[2]),   0,                 0,                 sin(0.5 * dir[2]));
+            rotation = rotTheta * (rotPhi * rotPsi);
+        } else {
+            if (itsAttr[ORIENTATION]) {
+                throw OpalException("Line::parse","Parameter orientation is array of 3 values (theta, phi, psi);\n" +
+                                    std::to_string(dir.size()) + " values provided");
+            }
+        }
+
+        if (ori.size() == 3) {
+            origin = Vector_t(ori[0], ori[1], ori[2]);
+        } else {
+            if (itsAttr[ORIGIN]) {
+                throw OpalException("Line::parse","Parameter origin is array of 3 values (x, y, z);\n" +
+                                    std::to_string(ori.size()) + " values provided");
+            }
+        }
+
+        CoordinateSystemTrafo global2local(origin,
+                                           rotation.conjugate());
+        base->setCSTrafoGlobal2Local(global2local);
+        base->fixPosition();
+
+    } else if (!itsAttr[PSI].defaultUsed() &&
+               itsAttr[X].defaultUsed() &&
+               itsAttr[Y].defaultUsed() &&
+               itsAttr[Z].defaultUsed() &&
+               itsAttr[THETA].defaultUsed() &&
+               itsAttr[PHI].defaultUsed()) {
+        base->setRotationAboutZ(Attributes::getReal(itsAttr[PSI]));
+    } else if (!itsAttr[X].defaultUsed() ||
+               !itsAttr[Y].defaultUsed() ||
+               !itsAttr[Z].defaultUsed() ||
+               !itsAttr[THETA].defaultUsed() ||
+               !itsAttr[PHI].defaultUsed() ||
+               !itsAttr[PSI].defaultUsed()) {
+        const Vector_t origin(Attributes::getReal(itsAttr[X]),
+                              Attributes::getReal(itsAttr[Y]),
+                              Attributes::getReal(itsAttr[Z]));
+
+        const double theta = Attributes::getReal(itsAttr[THETA]);
+        const double phi = Attributes::getReal(itsAttr[PHI]);
+        const double psi = Attributes::getReal(itsAttr[PSI]);
+
+        Quaternion rotTheta(cos(0.5 * theta), 0,              sin(0.5 * theta), 0);
+        Quaternion rotPhi(cos(0.5 * phi),     sin(0.5 * phi), 0,                0);
+        Quaternion rotPsi(cos(0.5 * psi),     0,              0,                sin(0.5 * psi));
+        Quaternion rotation = rotTheta * (rotPhi * rotPsi);
+
+        CoordinateSystemTrafo global2local(origin,
+                                           rotation.conjugate());
+        base->setCSTrafoGlobal2Local(global2local);
+        base->fixPosition();
+    }
+
+    Vector_t misalignmentShift(Attributes::getReal(itsAttr[DX]),
+                               Attributes::getReal(itsAttr[DY]),
+                               Attributes::getReal(itsAttr[DZ]));
+    double dtheta = Attributes::getReal(itsAttr[DTHETA]);
+    double dphi = Attributes::getReal(itsAttr[DPHI]);
+    double dpsi = Attributes::getReal(itsAttr[DPSI]);
+    Quaternion rotationY(cos(0.5 * dtheta), 0,               sin(0.5 * dtheta), 0);
+    Quaternion rotationX(cos(0.5 * dphi),   sin(0.5 * dphi), 0,                 0);
+    Quaternion rotationZ(cos(0.5 * dpsi),   0,               0,                 sin(0.5 * dpsi));
+    Quaternion misalignmentRotation = rotationY * rotationX * rotationZ;
+    CoordinateSystemTrafo misalignment(misalignmentShift,
+                                       misalignmentRotation.conjugate());
+
+    base->setMisalignment(misalignment);
+}
 
 void OpalElement::updateUnknown(ElementBase *base) {
     for(std::vector<Attribute>::size_type i = itsSize;
@@ -355,44 +692,6 @@ void OpalElement::printAttribute
 }
 
 
-OpalElement::OpalElement(int size, const char *name, const char *help):
-    Element(size, name, help), itsSize(size) {
-    itsAttr[TYPE]   = Attributes::makeString
-                      ("TYPE", "The element design type (the project name)");
-    itsAttr[LENGTH] = Attributes::makeReal
-                      ("L", "The element length in m");
-    itsAttr[APERT]  = Attributes::makeRealArray
-                      ("APERTURE", "The element aperture");
-    itsAttr[WAKEF]   = Attributes::makeString
-                       ("WAKEF", "Defines the wake function");
-    itsAttr[SURFACEPHYSICS]   = Attributes::makeString
-                                ("SURFACEPHYSICS", "Defines the surface physics handler");
-    static bool first = true;
-    if(first) {
-        registerStringAttribute("NAME");
-        registerStringAttribute("TYPE");
-        registerStringAttribute("CLASS");
-        registerStringAttribute("KEYWORD");
-        registerRealAttribute("L");
-        registerRealAttribute("DELTAX");
-        registerRealAttribute("DELTAY");
-        registerRealAttribute("DELTAS");
-        registerRealAttribute("DTHETA");
-        registerRealAttribute("DPHI");
-        registerRealAttribute("DPSI");
-        registerStringAttribute("WAKEF");
-        registerStringAttribute("SURFACEPHYSICS");
-        first = false;
-    }
-
-}
-
-
-OpalElement::OpalElement(const std::string &name, OpalElement *parent):
-    Element(name, parent), itsSize(parent->itsSize)
-{}
-
-
 AttCell *OpalElement::registerRealAttribute(const std::string &name) {
     OwnPtr<AttCell> &cell = attributeRegistry[name];
     if(! cell.isValid()) {
@@ -408,4 +707,4 @@ AttCell *OpalElement::registerStringAttribute(const std::string &name) {
         cell = new AttString();
     }
     return &*cell;
-}
+}
\ No newline at end of file
diff --git a/src/Elements/OpalElement.h b/src/Elements/OpalElement.h
index c8265cc11dc016f5a194047b0f55aa89ef23d469..dd87c21f364cbf9e8ef855ee338d0449867fcf44 100644
--- a/src/Elements/OpalElement.h
+++ b/src/Elements/OpalElement.h
@@ -44,11 +44,26 @@ public:
 
     /// The common attributes for all elements.
     enum {
-        TYPE,     // The design type.
-        APERT,    // The aperture data.
-        LENGTH,   // The element length.
-        WAKEF,    // The wake function to be used
+        TYPE,           // The design type.
+        APERT,          // The aperture data.
+        LENGTH,         // The element length.
+        // ELEMEDGE,       // The position of the element (in path length)
+        WAKEF,          // The wake function to be used
         SURFACEPHYSICS, // The surface physics handler to be used
+        ORIGIN,         // The location of the element in floor coordinates
+        ORIENTATION,    // The orientation of the element (Tait Bryan angles)
+        X,              // The x-coordinate of the location of the element in floor coordinates
+        Y,              // The y-coordinate of the location of the element in floor coordinates
+        Z,              // The z-coordinate of the location of the element in floor coordinates
+        THETA,          // The rotation about the y-axis
+        PHI,            // The rotation about the x-axis
+        PSI,            // The rotation about the z-axis
+        DX,             // Misalignment in x (local coordinate system)
+        DY,             // Misalignment in y (local coordinate system)
+        DZ,             // Misalignment in z (local coordinate system)
+        DTHETA,         // The rotation around y axis in rad.
+        DPHI,           // The rotation around x axis in rad.
+        DPSI,           // The rotation around s axis in rad.
         COMMON
     };
 
@@ -76,7 +91,7 @@ public:
     const std::string getTypeName() const;
 
     //return the element aperture vector
-    std::vector<double> getApert() const;
+    std::pair<ElementBase::ApertureType, std::vector<double> > getApert() const;
 
 
     /// Return the element's type name.
@@ -107,6 +122,9 @@ public:
     /// Store a registered string attribute.
     static void setRegisteredAttribute(const std::string &, const std::string &);
 
+    /// Update the embedded CLASSIC element.
+    virtual void update();
+
     /// Transmit the ``unknown'' (not known to OPAL) attributes to CLASSIC.
     virtual void updateUnknown(ElementBase *);
 
@@ -163,4 +181,4 @@ private:
     int itsSize;
 };
 
-#endif // OPAL_OpalElement_HH
+#endif // OPAL_OpalElement_HH
\ No newline at end of file
diff --git a/src/Elements/OpalHKicker.cpp b/src/Elements/OpalHKicker.cpp
index 4d35e82b3d7f088a6c400a843276194142e24138..09b63a494979e287780eb843551786e8e1e83cf4 100644
--- a/src/Elements/OpalHKicker.cpp
+++ b/src/Elements/OpalHKicker.cpp
@@ -34,8 +34,14 @@ OpalHKicker::OpalHKicker():
                 "acting on the horizontal plane.") {
     itsAttr[KICK] = Attributes::makeReal
                     ("KICK", "Horizontal deflection in rad");
+    itsAttr[DESIGNENERGY] = Attributes::makeReal
+                           ("DESIGNENERGY", "the mean energy of the particles", -1.0);
+    itsAttr[K0] = Attributes::makeReal
+                  ("K0", "Normal dipole field in T");
 
     registerRealAttribute("HKICK");
+    registerRealAttribute("DESIGNENERGY");
+    registerRealAttribute("K0");
 
     setElement((new XCorrectorRep("HKICKER"))->makeWrappers());
 }
@@ -78,16 +84,27 @@ fillRegisteredAttributes(const ElementBase &base, ValueFlag flag) {
 
 
 void OpalHKicker::update() {
+    OpalElement::update();
+
     XCorrectorRep *corr =
         dynamic_cast<XCorrectorRep *>(getElement()->removeWrappers());
     double length = Attributes::getReal(itsAttr[LENGTH]);
     double factor = OpalData::getInstance()->getP0() / Physics::c;
     double kick = Attributes::getReal(itsAttr[KICK]);
+
     corr->setElementLength(length);
     corr->setBy(- kick * factor);
 
-    corr->setKickX(Attributes::getReal(itsAttr[KICK]));
+    corr->setKickX(kick);
+    if(itsAttr[DESIGNENERGY]) {
+        double kineticEnergy = Attributes::getReal(itsAttr[DESIGNENERGY]);
+        corr->setDesignEnergy(kineticEnergy, false);
+    }
+
+    if (itsAttr[K0]) {
+        corr->setKickField(Vector_t(0, Attributes::getReal(itsAttr[K0]), 0));
+    }
 
     // Transmit "unknown" attributes.
     OpalElement::updateUnknown(corr);
-}
\ No newline at end of file
+}
diff --git a/src/Elements/OpalHKicker.h b/src/Elements/OpalHKicker.h
index 61a8b59a7bbacea84c63210f6a619409b023deec..112a490c78ac164c431b39432369053a9e420d03 100644
--- a/src/Elements/OpalHKicker.h
+++ b/src/Elements/OpalHKicker.h
@@ -34,6 +34,8 @@ public:
     /// The attributes of class OpalHKicker.
     enum {
         KICK = COMMON,  // The kicker strength.
+        DESIGNENERGY,   // The mean kinetic energy at exit
+        K0,             // The magnetic field
         SIZE
     };
 
diff --git a/src/Elements/OpalHMonitor.cpp b/src/Elements/OpalHMonitor.cpp
index 10265de18966e2391227e80d71e262ff98b1a81d..2e7dd5fcdb216e86312b5670dcb0227331f0d6ef 100644
--- a/src/Elements/OpalHMonitor.cpp
+++ b/src/Elements/OpalHMonitor.cpp
@@ -50,11 +50,13 @@ OpalHMonitor *OpalHMonitor::clone(const std::string &name) {
 
 
 void OpalHMonitor::update() {
+    OpalElement::update();
+
     XMonitorRep *mon =
         dynamic_cast<XMonitorRep *>(getElement()->removeWrappers());
     double length = Attributes::getReal(itsAttr[LENGTH]);
     mon->setElementLength(length);
 
-    // Transmit "unknown" attributes.
+   // Transmit "unknown" attributes.
     OpalElement::updateUnknown(mon);
 }
diff --git a/src/Elements/OpalKicker.cpp b/src/Elements/OpalKicker.cpp
index 43b7bc63da9dc2254307384d21f17ce9a5d9cd59..b2b2cbce67c84a13ecd90d8b6de2e85cce72f59a 100644
--- a/src/Elements/OpalKicker.cpp
+++ b/src/Elements/OpalKicker.cpp
@@ -38,9 +38,18 @@ OpalKicker::OpalKicker():
                      ("HKICK", "Horizontal deflection in rad");
     itsAttr[VKICK] = Attributes::makeReal
                      ("VKICK", "Vertical deflection in rad");
+    itsAttr[DESIGNENERGY] = Attributes::makeReal
+                            ("DESIGNENERGY", "the mean energy of the particles", -1.0);
+    itsAttr[K0] = Attributes::makeReal
+                  ("K0", "Normal dipole field in T");
+    itsAttr[K0S] = Attributes::makeReal
+                  ("K0S", "Skew dipole field in T");
 
     registerRealAttribute("HKICK");
     registerRealAttribute("VKICK");
+    registerRealAttribute("DESIGNENERGY");
+    registerRealAttribute("K0");
+    registerRealAttribute("K0S");
 
     setElement((new CorrectorRep("KICKER"))->makeWrappers());
 }
@@ -89,19 +98,41 @@ fillRegisteredAttributes(const ElementBase &base, ValueFlag flag) {
 
 
 void OpalKicker::update() {
+    OpalElement::update();
+
     CorrectorRep *corr =
         dynamic_cast<CorrectorRep *>(getElement()->removeWrappers());
     double length = Attributes::getReal(itsAttr[LENGTH]);
     double factor = OpalData::getInstance()->getP0() / Physics::c;
     double hKick = Attributes::getReal(itsAttr[HKICK]);
     double vKick = Attributes::getReal(itsAttr[VKICK]);
+
     corr->setElementLength(length);
     corr->setBy(- hKick * factor);
     corr->setBx(vKick * factor);
 
-    corr->setKickX(Attributes::getReal(itsAttr[HKICK]));
-    corr->setKickY(Attributes::getReal(itsAttr[VKICK]));
+    corr->setKickX(hKick);
+    corr->setKickY(vKick);
+    if(itsAttr[DESIGNENERGY]) {
+        double kineticEnergy = Attributes::getReal(itsAttr[DESIGNENERGY]);
+        corr->setDesignEnergy(kineticEnergy, false);
+    }
+
+    double Bx = 0.0, By = 0.0;
+    bool fieldSet = false;
+    if (itsAttr[K0]) {
+        Bx = Attributes::getReal(itsAttr[K0]);
+        fieldSet = true;
+    }
+    if (itsAttr[K0S]) {
+        By = Attributes::getReal(itsAttr[K0S]);
+        fieldSet = true;
+    }
+
+    if (fieldSet) {
+        corr->setKickField(Vector_t(Bx, By, 0));
+    }
 
     // Transmit "unknown" attributes.
     OpalElement::updateUnknown(corr);
-}
\ No newline at end of file
+}
diff --git a/src/Elements/OpalKicker.h b/src/Elements/OpalKicker.h
index 38a44cc3db2e1bb7bf02b8f3d2f1b8b717481142..ad381f40d3194d8548c81db99df195530a11a580 100644
--- a/src/Elements/OpalKicker.h
+++ b/src/Elements/OpalKicker.h
@@ -35,6 +35,9 @@ public:
     enum {
         HKICK = COMMON,  // The horizontal kicker strength.
         VKICK,           // The vertical kicker strength.
+        DESIGNENERGY,    // The mean kinetic energy at exit
+        K0,              // The normal dipole field
+        K0S,             // The skew dipole field
         SIZE
     };
 
diff --git a/src/Elements/OpalMonitor.cpp b/src/Elements/OpalMonitor.cpp
index 0040741c053586de18451435141604de140b0cb9..9aea4f869078d6f3c40d0742f50005b6906345ce 100644
--- a/src/Elements/OpalMonitor.cpp
+++ b/src/Elements/OpalMonitor.cpp
@@ -20,20 +20,20 @@
 #include "AbstractObjects/Attribute.h"
 #include "Attributes/Attributes.h"
 #include "BeamlineCore/MonitorRep.h"
+#include "Utilities/Util.h"
 
 // Class OpalMonitor
 // ------------------------------------------------------------------------
 
+extern Inform *gmsg;
+
 OpalMonitor::OpalMonitor():
     OpalElement(SIZE, "MONITOR",
                 "The \"MONITOR\" element defines a monitor for both planes.") {
     itsAttr[OUTFN] = Attributes::makeString
                      ("OUTFN", "Monitor output filename");
-    itsAttr[MONITORTYPE] = Attributes::makeString
-                           ("MONITORTYPE", "TEMPORAL or SPATIAL (default)");
 
     registerStringAttribute("OUTFN");
-    registerStringAttribute("MONITORTYPE");
 
     setElement((new MonitorRep("MONITOR"))->makeAlignWrapper());
 }
@@ -55,17 +55,20 @@ OpalMonitor *OpalMonitor::clone(const std::string &name) {
 
 
 void OpalMonitor::update() {
+    OpalElement::update();
+
     MonitorRep *mon =
         dynamic_cast<MonitorRep *>(getElement()->removeWrappers());
-    double length = Attributes::getReal(itsAttr[LENGTH]);
+    double length = std::max(0.01, Attributes::getReal(itsAttr[LENGTH]));
     mon->setElementLength(length);
     mon->setOutputFN(Attributes::getString(itsAttr[OUTFN]));
 
-    if (Attributes::getString(itsAttr[MONITORTYPE]) == "TEMPORAL") {
+    if (Util::toUpper(Attributes::getString(itsAttr[TYPE])) == "TEMPORAL") {
         mon->setType(Monitor::TEMPORAL);
     } else {
         mon->setType(Monitor::SPATIAL);
     }
+
     // Transmit "unknown" attributes.
     OpalElement::updateUnknown(mon);
 }
diff --git a/src/Elements/OpalMonitor.h b/src/Elements/OpalMonitor.h
index afb6bd8fc67acd6118c1999448e2fa6deda0c925..1b474b9f8e6568dba6654bc664ba7a6884466a86 100644
--- a/src/Elements/OpalMonitor.h
+++ b/src/Elements/OpalMonitor.h
@@ -31,7 +31,6 @@ public:
 
     enum {
         OUTFN = COMMON,
-        MONITORTYPE,
         SIZE
     };
 
diff --git a/src/Elements/OpalMultipole.cpp b/src/Elements/OpalMultipole.cpp
index e0561dca4ef3d80b661af2f2ed97a4371894b24c..91b1ba827396a27664f6c778307cf5f83b6dcc91 100644
--- a/src/Elements/OpalMultipole.cpp
+++ b/src/Elements/OpalMultipole.cpp
@@ -36,6 +36,7 @@
 #endif
 #include <vector>
 
+
 // Class OpalMultipole
 // ------------------------------------------------------------------------
 
@@ -48,8 +49,12 @@ OpalMultipole::OpalMultipole():
                 "* With zero length no synchrotron radiation can be calculated.") {
     itsAttr[KN] = Attributes::makeRealArray
                   ("KN", "Normalised multipole strengths (normal) in m^(-k)");
+    itsAttr[DKN] = Attributes::makeRealArray
+                  ("DKN", "Normalised multipole strengths errors(normal) in m^(-k)");
     itsAttr[KS] = Attributes::makeRealArray
                   ("KS", "Normalised multipole strengths (skew) in m^(-k)");
+    itsAttr[DKS] = Attributes::makeRealArray
+                  ("DKS", "Normalised multipole strength errors (skew) in m^(-k)");
 
     setElement((new MultipoleRep("MULTIPOLE"))->makeWrappers());
 }
@@ -121,6 +126,8 @@ fillRegisteredAttributes(const ElementBase &base, ValueFlag flag) {
 
 
 void OpalMultipole::update() {
+    OpalElement::update();
+
     // Magnet length.
     MultipoleRep *mult =
         dynamic_cast<MultipoleRep *>(getElement()->removeWrappers());
@@ -131,9 +138,13 @@ void OpalMultipole::update() {
     BMultipoleField field;
 
     const std::vector<double> norm = Attributes::getRealArray(itsAttr[KN]);
+    std::vector<double> normErrors = Attributes::getRealArray(itsAttr[DKN]);
     const std::vector<double> skew = Attributes::getRealArray(itsAttr[KS]);
+    std::vector<double> skewErrors = Attributes::getRealArray(itsAttr[DKS]);
     int normSize = norm.size();
     int skewSize = skew.size();
+    normErrors.resize(normSize, 0.0);
+    skewErrors.resize(skewSize, 0.0);
     double factor = OpalData::getInstance()->getP0() / Physics::c;
     int top = (normSize > skewSize) ? normSize : skewSize;
 
@@ -141,18 +152,16 @@ void OpalMultipole::update() {
         factor /= double(comp);
         if(comp <= normSize) {
             field.setNormalComponent(comp, norm[comp-1] * factor);
-            // if (comp > 1) // dipole not supported in opal-t yet
-            mult->setNormalComponent(comp, norm[comp-1]);
+            mult->setNormalComponent(comp, norm[comp-1], normErrors[comp-1]);
         }
         if(comp <= skewSize) {
             field.setSkewComponent(comp, skew[comp-1] * factor);
-            // if (comp > 1) //dipole not supported in opal-t yet
-            mult->setSkewComponent(comp, skew[comp-1]);
+            mult->setSkewComponent(comp, skew[comp-1], skewErrors[comp-1]);
         }
     }
 
     mult->setField(field);
 
-    // Transmit "unknown" attributes.
+   // Transmit "unknown" attributes.
     OpalElement::updateUnknown(mult);
-}
\ No newline at end of file
+}
diff --git a/src/Elements/OpalMultipole.h b/src/Elements/OpalMultipole.h
index ecba3765d52ba1804a60f647f85debab0d896a15..c37afb2039764156ccb75aa2da4870b669921c48 100644
--- a/src/Elements/OpalMultipole.h
+++ b/src/Elements/OpalMultipole.h
@@ -32,7 +32,9 @@ public:
     /// The attributes of class OpalMultipole.
     enum {
         KN = COMMON,  // The normal field components.
+        DKN,          // The normal field component errors.
         KS,           // The skewed field components.
+        DKS,          // The skewed field component errors.
         SIZE
     };
 
diff --git a/src/Elements/OpalOctupole.cpp b/src/Elements/OpalOctupole.cpp
index 54778448903f126b3878e756ee755b0b126db832..a437e4167399b820f86ee21c8717cd17f9b79dd5 100644
--- a/src/Elements/OpalOctupole.cpp
+++ b/src/Elements/OpalOctupole.cpp
@@ -40,15 +40,12 @@ OpalOctupole::OpalOctupole():
                 "The \"OCTUPOLE\" element defines a Octupole.") {
     itsAttr[K3] = Attributes::makeReal
                   ("K3", "Normalised upright octupole coefficient in m^(-4)");
+    itsAttr[DK3] = Attributes::makeReal
+                  ("DK3", "Normalised upright octupole coefficient error in m^(-4)");
     itsAttr[K3S] = Attributes::makeReal
                    ("K3S", "Normalised skew octupole coefficient in m^(-4)");
-    itsAttr[DX] = Attributes::makeReal
-      ("DX", "Misalignment in x direction",0.0);
-    itsAttr[DY] = Attributes::makeReal
-      ("DY", "Misalignment in y direction",0.0);
-
-    registerRealAttribute("DX");
-    registerRealAttribute("DY");
+    itsAttr[DK3S] = Attributes::makeReal
+                   ("DK3S", "Normalised skew octupole coefficient error in m^(-4)");
 
     setElement((new MultipoleRep("OCTUPOLE"))->makeWrappers());
 }
@@ -122,6 +119,8 @@ fillRegisteredAttributes(const ElementBase &base, ValueFlag flag) {
 
 
 void OpalOctupole::update() {
+    OpalElement::update();
+
     MultipoleRep *oct =
         dynamic_cast<MultipoleRep *>(getElement()->removeWrappers());
     oct->setElementLength(Attributes::getReal(itsAttr[LENGTH]));
@@ -131,12 +130,8 @@ void OpalOctupole::update() {
     field.setSkewComponent(4, factor * Attributes::getReal(itsAttr[K3S]));
     oct->setField(field);
 
-    oct->setNormalComponent(4, Attributes::getReal(itsAttr[K3]));
-    oct->setSkewComponent(4, Attributes::getReal(itsAttr[K3S]));
-
-    double dx = Attributes::getReal(itsAttr[DX]);
-    double dy = Attributes::getReal(itsAttr[DY]);
-    oct->setMisalignment(dx, dy, 0.0);
+    oct->setNormalComponent(4, Attributes::getReal(itsAttr[K3]), Attributes::getReal(itsAttr[DK3]));
+    oct->setSkewComponent(4, Attributes::getReal(itsAttr[K3S]), Attributes::getReal(itsAttr[DK3S]));
 
     // Transmit "unknown" attributes.
     OpalElement::updateUnknown(oct);
diff --git a/src/Elements/OpalOctupole.h b/src/Elements/OpalOctupole.h
index 3e0157459b4013bec6c6f39f9028ad309b80ee2c..df198ad1d3f4ac11430995ddabbdcc4374d3c3f8 100644
--- a/src/Elements/OpalOctupole.h
+++ b/src/Elements/OpalOctupole.h
@@ -32,9 +32,9 @@ public:
     /// The attributes of class OpalOctupole.
     enum {
         K3 = COMMON,  // The normal octupole coefficient.
+        DK3,          // The normal octupole coefficient error.
         K3S,          // The skew octupole coefficient.
-        DX,
-        DY,
+        DK3S,          // The skew octupole coefficient error.
         SIZE
     };
 
diff --git a/src/Elements/OpalParallelPlate.cpp b/src/Elements/OpalParallelPlate.cpp
index bc0e890fc9b9976c35b272414116d4de59ef9975..795c5533ac7ea0487e61820e013677952b241d85 100644
--- a/src/Elements/OpalParallelPlate.cpp
+++ b/src/Elements/OpalParallelPlate.cpp
@@ -45,10 +45,6 @@ OpalParallelPlate::OpalParallelPlate():
 
     itsAttr[PLENGTH] = Attributes::makeReal
                        ("PLENGTH", " Gap length in Meter");
-    itsAttr[DX] = Attributes::makeReal
-      ("DX", "Misalignment in x direction",0.0);
-    itsAttr[DY] = Attributes::makeReal
-      ("DY", "Misalignment in y direction",0.0);
 
 
     registerRealAttribute("VOLT");
@@ -57,8 +53,6 @@ OpalParallelPlate::OpalParallelPlate():
     registerStringAttribute("GEOMETRY");
     registerRealAttribute("PLENGTH");
 
-    registerRealAttribute("DX");
-    registerRealAttribute("DY");
     setElement((new ParallelPlateRep("ParallelPlate"))->makeAlignWrapper());
 }
 
@@ -91,16 +85,15 @@ void OpalParallelPlate::fillRegisteredAttributes(const ElementBase &base, ValueF
         attributeRegistry["FREQ"]->setReal(pplate->getFrequency());
         attributeRegistry["LAG"]->setReal(pplate->getPhase());
         attributeRegistry["PLENGTH"]->setReal(pplate->getElementLength());
-        double dx, dy, dz;
-        pplate->getMisalignment(dx, dy, dz);
-        attributeRegistry["DX"]->setReal(dx);
-        attributeRegistry["DY"]->setReal(dy);
     }
 }
 
 
 void OpalParallelPlate::update() {
     using Physics::two_pi;
+
+    OpalElement::update();
+
     ParallelPlateRep *pplate =
         dynamic_cast<ParallelPlateRep *>(getElement()->removeWrappers());
 
@@ -109,8 +102,6 @@ void OpalParallelPlate::update() {
     double phase  = Attributes::getReal(itsAttr[LAG]);
     double freq   = (1.0e6 * two_pi) * Attributes::getReal(itsAttr[FREQ]);
     double length = Attributes::getReal(itsAttr[PLENGTH]);
-    double dx = Attributes::getReal(itsAttr[DX]);
-    double dy = Attributes::getReal(itsAttr[DY]);
 
     if(itsAttr[GEOMETRY] && obgeo_m == NULL) {
         obgeo_m = (BoundaryGeometry::find(Attributes::getString(itsAttr[GEOMETRY])))->clone(getOpalName() + std::string("_geometry"));
@@ -121,7 +112,6 @@ void OpalParallelPlate::update() {
         }
     }
 
-    pplate->setMisalignment(dx, dy, 0.0);
     pplate->setAmplitude(1.0e6 * vPeak);
     pplate->setFrequency(freq);
     pplate->setPhase(phase);
@@ -130,4 +120,4 @@ void OpalParallelPlate::update() {
 
     // Transmit "unknown" attributes.
     OpalElement::updateUnknown(pplate);
-}
\ No newline at end of file
+}
diff --git a/src/Elements/OpalParallelPlate.h b/src/Elements/OpalParallelPlate.h
index 306a4ae362595d958198ce8f188d0d10c14228d7..aff65e7b296bdb2f41771ae5396ac7366391f03a 100644
--- a/src/Elements/OpalParallelPlate.h
+++ b/src/Elements/OpalParallelPlate.h
@@ -39,8 +39,6 @@ public:
         LAG,            // The phase lag.
 
         PLENGTH,           //distance between two plates or length in s direction
-        DX,             // Misalignment: translation in x direction
-        DY,             // Misalignment: translation in y direction
         SIZE
     };
 
diff --git a/src/Elements/OpalPatch.cpp b/src/Elements/OpalPatch.cpp
index 195e27599d323e74264ca7dc94ce00c0d79a7a75..9f8421e4bda66d1e3ed3a6f2ac2897d898e33fcb 100644
--- a/src/Elements/OpalPatch.cpp
+++ b/src/Elements/OpalPatch.cpp
@@ -59,6 +59,8 @@ bool OpalPatch::isPatch() const {
 
 
 void OpalPatch::update() {
+    OpalElement::update();
+
     PatchRep *patch = static_cast<PatchRep *>(getElement());
     double dx = Attributes::getReal(itsAttr[DX]);
     double dy = Attributes::getReal(itsAttr[DY]);
diff --git a/src/Elements/OpalPepperPot.cpp b/src/Elements/OpalPepperPot.cpp
index 1bfb6ccb021bca43d5fd3b77f2fd1c56c6b6d918..4755c8dc4cec4eef9ce08304be67d47aa81badab 100644
--- a/src/Elements/OpalPepperPot.cpp
+++ b/src/Elements/OpalPepperPot.cpp
@@ -44,11 +44,6 @@ OpalPepperPot::OpalPepperPot():
     itsAttr[R] = Attributes::makeReal
                  ("R", "Radios of a holes in m");
 
-    itsAttr[DX] = Attributes::makeReal
-      ("DX", "Misalignment in x direction",0.0);
-    itsAttr[DY] = Attributes::makeReal
-      ("DY", "Misalignment in y direction",0.0);
-
     registerStringAttribute("OUTFN");
     registerRealAttribute("XSIZE");
     registerRealAttribute("YSIZE");
@@ -56,8 +51,6 @@ OpalPepperPot::OpalPepperPot():
     registerRealAttribute("R");
     registerRealAttribute("NHOLX");
     registerRealAttribute("NHOLY");
-    registerRealAttribute("DX");
-    registerRealAttribute("DY");
 
     setElement((new CollimatorRep("PEPPERPOT"))->makeAlignWrapper());
 }
@@ -89,13 +82,12 @@ void OpalPepperPot::fillRegisteredAttributes(const ElementBase &base, ValueFlag
         dynamic_cast<const CollimatorRep *>(base.removeWrappers());
     attributeRegistry["XSIZE"]->setReal(ppo->getXsize());
     attributeRegistry["YSIZE"]->setReal(ppo->getYsize());
-    double dx, dy, dz;
-    ppo->getMisalignment(dx, dy, dz);
-    attributeRegistry["DX"]->setReal(dx);
-    attributeRegistry["DY"]->setReal(dy);
+
 }
 
 void OpalPepperPot::update() {
+    OpalElement::update();
+
     CollimatorRep *ppo =
         dynamic_cast<CollimatorRep *>(getElement()->removeWrappers());
     double length = Attributes::getReal(itsAttr[LENGTH]);
@@ -108,24 +100,8 @@ void OpalPepperPot::update() {
     ppo->setPitch(Attributes::getReal(itsAttr[PITCH]));
     ppo->setNHoles(Attributes::getReal(itsAttr[NHOLX]), Attributes::getReal(itsAttr[NHOLY]));
 
-    double dx = Attributes::getReal(itsAttr[DX]);
-    double dy = Attributes::getReal(itsAttr[DY]);
-
-    ppo->setMisalignment(dx, dy, 0.0);
-
     ppo->setPepperPot();
-    /*
-    std::vector<double> apert = getApert();
-    double apert_major = -1., apert_minor = -1.;
-    if(apert.size() > 0) {
-        apert_major = apert[0];
-        if(apert.size() > 1) {
-            apert_minor = apert[1];
-        } else {
-            apert_minor = apert[0];
-        }
-    }
-    */
+
     if(itsAttr[SURFACEPHYSICS] && sphys_m == NULL) {
         sphys_m = (SurfacePhysics::find(Attributes::getString(itsAttr[SURFACEPHYSICS])))->clone(getOpalName() + std::string("_sphys"));
         sphys_m->initSurfacePhysicsHandler(*ppo);
diff --git a/src/Elements/OpalPepperPot.h b/src/Elements/OpalPepperPot.h
index e9b7e3b2b131404da6045097db726c7b156a03c0..7cf559223c61892f94ecec8937d74f531938d072 100644
--- a/src/Elements/OpalPepperPot.h
+++ b/src/Elements/OpalPepperPot.h
@@ -40,8 +40,6 @@ public:
         XSIZE,
         YSIZE,
         OUTFN,
-        DX,             // Misalignment: translation in x direction
-        DY,             // Misalignment: translation in y direction
         SIZE
     };
 
diff --git a/src/Elements/OpalProbe.cpp b/src/Elements/OpalProbe.cpp
index be16fa6a829ceeb148f49f4716430053a8ed9889..35286f65a7326619f619152523e5ecd16f9e435a 100644
--- a/src/Elements/OpalProbe.cpp
+++ b/src/Elements/OpalProbe.cpp
@@ -81,6 +81,8 @@ void OpalProbe::fillRegisteredAttributes(const ElementBase &base, ValueFlag flag
 
 
 void OpalProbe::update() {
+    OpalElement::update();
+
     ProbeRep *prob =
         dynamic_cast<ProbeRep *>(getElement()->removeWrappers());
     double length = Attributes::getReal(itsAttr[LENGTH]);
diff --git a/src/Elements/OpalProbe.h b/src/Elements/OpalProbe.h
index 1d85363156218a16a919080ef3eee8eefa107847..b02e12a463873dbb89d6463cc203c44b0bcb2154 100644
--- a/src/Elements/OpalProbe.h
+++ b/src/Elements/OpalProbe.h
@@ -33,12 +33,12 @@ public:
 
     /// The attributes of class OpalProbe.
     enum {
-        XSTART,           // Start of x coordinate
-        XEND,           // End of x coordinate
+        XSTART = COMMON, // Start of x coordinate
+        XEND,            // End of x coordinate
         YSTART,          // Start of y coordinate
-        YEND1,          // Not used now
-        YEND,          // End of y coordinate
-        WIDTH,       // Width of the probe
+        YEND1,           // Not used now
+        YEND,            // End of y coordinate
+        WIDTH,           // Width of the probe
         SIZE
     };
     ///YEND1 is not used since it is treated as a string in the input file which should be a real argument.
diff --git a/src/Elements/OpalQuadrupole.cpp b/src/Elements/OpalQuadrupole.cpp
index b211e77d39f59e038f9a7724c4541249215039a5..641d39e6ce5ae0bc2846223310c28e607a1084c6 100644
--- a/src/Elements/OpalQuadrupole.cpp
+++ b/src/Elements/OpalQuadrupole.cpp
@@ -44,16 +44,18 @@ OpalQuadrupole::OpalQuadrupole():
     sphys_m(NULL) {
     itsAttr[K1] = Attributes::makeReal
                   ("K1", "Normalised upright quadrupole coefficient in m^(-2)");
+    itsAttr[DK1] = Attributes::makeReal
+                  ("DK1", "Normalised upright quadrupole coefficient error in m^(-2)");
     itsAttr[K1S] = Attributes::makeReal
                    ("K1S", "Normalised skew quadrupole coefficient in m^(-2)");
 
-    itsAttr[DX] = Attributes::makeReal
-      ("DX", "Misalignment in x direction",0.0);
-    itsAttr[DY] = Attributes::makeReal
-      ("DY", "Misalignment in y direction",0.0);
+    itsAttr[DK1S] = Attributes::makeReal
+                   ("DK1S", "Normalised skew quadrupole coefficient error in m^(-2)");
 
-    registerRealAttribute("DX");
-    registerRealAttribute("DY");
+    registerRealAttribute("K1");
+    registerRealAttribute("DK1");
+    registerRealAttribute("K1S");
+    registerRealAttribute("DK1S");
 
     setElement((new MultipoleRep("QUADRUPOLE"))->makeWrappers());
 }
@@ -126,15 +128,12 @@ fillRegisteredAttributes(const ElementBase &base, ValueFlag flag) {
 
         scale *= double(order);
     }
-
-    double dx, dy, dz;
-    mult->getMisalignment(dx, dy, dz);
-    attributeRegistry["DX"]->setReal(dx);
-    attributeRegistry["DY"]->setReal(dy);
 }
 
 
 void OpalQuadrupole::update() {
+    OpalElement::update();
+
     MultipoleRep *quad =
         dynamic_cast<MultipoleRep *>(getElement()->removeWrappers());
     quad->setElementLength(Attributes::getReal(itsAttr[LENGTH]));
@@ -144,25 +143,9 @@ void OpalQuadrupole::update() {
     field.setNormalComponent(2, factor * Attributes::getReal(itsAttr[K1]));   // this is for the maps
     field.setSkewComponent(2, factor * Attributes::getReal(itsAttr[K1S]));    // this is for the maps
     quad->setField(field);
-    quad->setNormalComponent(2, Attributes::getReal(itsAttr[K1]));
-    quad->setSkewComponent(2, Attributes::getReal(itsAttr[K1S]));
-
-    double dx = Attributes::getReal(itsAttr[DX]);
-    double dy = Attributes::getReal(itsAttr[DY]);
-    quad->setMisalignment(dx, dy, 0.0);
-
-    /*
-    std::vector<double> apert = getApert();
-    double apert_major = -1., apert_minor = -1.;
-    if(apert.size() > 0) {
-        apert_major = apert[0];
-        if(apert.size() > 1) {
-            apert_minor = apert[1];
-        } else {
-            apert_minor = apert[0];
-        }
-    }
-    */
+    quad->setNormalComponent(2, Attributes::getReal(itsAttr[K1]), Attributes::getReal(itsAttr[DK1]));
+    quad->setSkewComponent(2, Attributes::getReal(itsAttr[K1S]), Attributes::getReal(itsAttr[DK1S]));
+
     if(itsAttr[SURFACEPHYSICS] && sphys_m == NULL) {
         sphys_m = (SurfacePhysics::find(Attributes::getString(itsAttr[SURFACEPHYSICS])))->clone(getOpalName() + std::string("_sphys"));
         sphys_m->initSurfacePhysicsHandler(*quad);
diff --git a/src/Elements/OpalQuadrupole.h b/src/Elements/OpalQuadrupole.h
index 717596108673f2e518f810d544b8dd0a005fefa0..7c69ce0f9ae5b8d989aa3dde7313623f09b6a648 100644
--- a/src/Elements/OpalQuadrupole.h
+++ b/src/Elements/OpalQuadrupole.h
@@ -33,9 +33,9 @@ public:
     /// The attributes of class OpalQuadrupole.
     enum {
         K1 = COMMON,  // The normal quadrupole coefficient.
+        DK1,          // The normal quadupole coefficient error.
         K1S,          // The skew quadrupole coefficient.
-	DX,             // Misalignment: translation in x direction
-        DY,             // Misalignment: translation in y direction
+        DK1S,         // The skew quadrupole coefficient error.
         SIZE
     };
 
diff --git a/src/Elements/OpalRBend.cpp b/src/Elements/OpalRBend.cpp
index 885c676d37af5a954f53ab7f9b5430603e2546b0..6c57c00fa803379cce8e5ebce0fd6b93619a9a4a 100644
--- a/src/Elements/OpalRBend.cpp
+++ b/src/Elements/OpalRBend.cpp
@@ -25,6 +25,7 @@
 #include "Physics/Physics.h"
 #include "Structure/OpalWake.h"
 #include "Structure/SurfacePhysics.h"
+#include "Utilities/OpalException.h"
 #include <cmath>
 
 // Class OpalRBend
@@ -102,15 +103,12 @@ fillRegisteredAttributes(const ElementBase &base, ValueFlag flag) {
     // Store integration parameters.
     attributeRegistry["SLICES"]->setReal(bend->getSlices());
     attributeRegistry["STEPSIZE"]->setReal(bend->getStepsize());
-
-    double dx, dy, dz;
-    bend->getMisalignment(dx, dy, dz);
-    attributeRegistry["DX"]->setReal(dx);
-    attributeRegistry["DY"]->setReal(dy);
 }
 
 
 void OpalRBend::update() {
+    OpalElement::update();
+
     // Define geometry.
     RBendRep *bend =
         dynamic_cast<RBendRep *>(getElement()->removeWrappers());
@@ -152,56 +150,47 @@ void OpalRBend::update() {
 
     // Set field amplitude or bend angle.
     if(itsAttr[ANGLE])
-        bend->SetBendAngle(Attributes::getReal(itsAttr[ANGLE]));
+        bend->setBendAngle(Attributes::getReal(itsAttr[ANGLE]));
     else
-        bend->SetFieldAmplitude(k0, k0s);
+        bend->setFieldAmplitude(k0, k0s);
 
     if(itsAttr[ROTATION])
-        bend->SetRotationAboutZ(Attributes::getReal(itsAttr[ROTATION]));
-    else
-        bend->SetRotationAboutZ(0.0);
+        throw OpalException("OpalRBend::update",
+                            "ROTATION not supported any more; use PSI instead");
+
 
     if(itsAttr[FMAPFN])
-        bend->SetFieldMapFN(Attributes::getString(itsAttr[FMAPFN]));
+        bend->setFieldMapFN(Attributes::getString(itsAttr[FMAPFN]));
     else if(bend->getName() != "RBEND") {
         ERRORMSG(bend->getName() << ": No filename for a field map given. "
                  "Will assume the default map "
                  "\"1DPROFILE1-DEFAULT\"."
                  << endl);
-        bend->SetFieldMapFN("1DPROFILE1-DEFAULT");
+        bend->setFieldMapFN("1DPROFILE1-DEFAULT");
     }
 
-    if(itsAttr[E1])
-        bend->SetEntranceAngle(Attributes::getReal(itsAttr[E1]));
-    else if(itsAttr[ALPHA])
-        bend->SetEntranceAngle(Attributes::getReal(itsAttr[ALPHA]));
-    else
-        bend->SetEntranceAngle(0.0);
-
-    if(itsAttr[BETA])
-        bend->SetBeta(Attributes::getReal(itsAttr[BETA]));
-    else
-        bend->SetBeta(0.0);
+    bend->setEntranceAngle(Attributes::getReal(itsAttr[E1]));
 
     // Energy in eV.
     if(itsAttr[DESIGNENERGY]) {
-        bend->SetDesignEnergy(Attributes::getReal(itsAttr[DESIGNENERGY]));
+        bend->setDesignEnergy(Attributes::getReal(itsAttr[DESIGNENERGY]), false);
     }
 
-    if(itsAttr[GAP])
-        bend->SetFullGap(Attributes::getReal(itsAttr[GAP]));
-    else
-        bend->SetFullGap(0.0);
+    bend->setFullGap(Attributes::getReal(itsAttr[GAP]));
+
+    // if(itsAttr[APERT])
+    //     throw OpalException("OpalRBend::fillRegisteredAttributes",
+    //                         "APERTURE in RBEND not supported; use GAP and HAPERT instead");
 
     if(itsAttr[HAPERT])
-        bend->SetAperture(Attributes::getReal(itsAttr[HAPERT]));
+        bend->setAperture(ElementBase::RECTANGULAR, std::vector<double>(2, Attributes::getReal(itsAttr[HAPERT])));
     else
-        bend->SetAperture(0.0);
+        bend->setAperture(ElementBase::RECTANGULAR, std::vector<double>(2, 0.0));
 
     if(itsAttr[LENGTH])
-        bend->SetLength(Attributes::getReal(itsAttr[LENGTH]));
+        bend->setLength(Attributes::getReal(itsAttr[LENGTH]));
     else
-        bend->SetLength(0.0);
+        bend->setLength(0.0);
 
     if(itsAttr[WAKEF] && itsAttr[DESIGNENERGY] && owk_m == NULL) {
         owk_m = (OpalWake::find(Attributes::getString(itsAttr[WAKEF])))->clone(getOpalName() + std::string("_wake"));
@@ -210,36 +199,16 @@ void OpalRBend::update() {
     }
 
     if(itsAttr[K1])
-        bend->SetK1(Attributes::getReal(itsAttr[K1]));
+        bend->setK1(Attributes::getReal(itsAttr[K1]));
     else
-        bend->SetK1(0.0);
-
-    bend->setMisalignment(Attributes::getReal(itsAttr[DX]),
-                          Attributes::getReal(itsAttr[DY]),
-                          0.0);
-
-    /*
-    std::vector<double> apert = getApert();
-    double apert_major = -1., apert_minor = -1.;
-    if(apert.size() > 0) {
-        apert_major = apert[0];
-        if(apert.size() > 1) {
-            apert_minor = apert[1];
-        } else {
-            apert_minor = apert[0];
-        }
-    }
-    */
+        bend->setK1(0.0);
+
     if(itsAttr[SURFACEPHYSICS] && sphys_m == NULL) {
         sphys_m = (SurfacePhysics::find(Attributes::getString(itsAttr[SURFACEPHYSICS])))->clone(getOpalName() + std::string("_sphys"));
         sphys_m->initSurfacePhysicsHandler(*bend);
         bend->setSurfacePhysics(sphys_m->handler_m);
     }
 
-    double dx = Attributes::getReal(itsAttr[DX]);
-    double dy = Attributes::getReal(itsAttr[DY]);
-    bend->setMisalignment(dx, dy, 0.0);
-
     // Transmit "unknown" attributes.
     OpalElement::updateUnknown(bend);
 }
diff --git a/src/Elements/OpalRCollimator.cpp b/src/Elements/OpalRCollimator.cpp
index d40a87b405850dd680d476bf56353a30a760d5fb..cd4f6593092a337a85ea2e9c24607a8fa4922736 100644
--- a/src/Elements/OpalRCollimator.cpp
+++ b/src/Elements/OpalRCollimator.cpp
@@ -36,13 +36,6 @@ OpalRCollimator::OpalRCollimator():
     itsAttr[OUTFN] = Attributes::makeString
                      ("OUTFN", "Monitor output filename");
 
-    itsAttr[DX] = Attributes::makeReal
-      ("DX", "Misalignment in x direction",0.0);
-    itsAttr[DY] = Attributes::makeReal
-      ("DY", "Misalignment in y direction",0.0);
-
-    registerRealAttribute("DX");
-    registerRealAttribute("DY");
     registerStringAttribute("OUTFN");
     registerRealAttribute("XSIZE");
     registerRealAttribute("YSIZE");
@@ -77,16 +70,11 @@ fillRegisteredAttributes(const ElementBase &base, ValueFlag flag) {
         dynamic_cast<const CollimatorRep *>(base.removeWrappers());
     attributeRegistry["XSIZE"]->setReal(coll->getXsize());
     attributeRegistry["YSIZE"]->setReal(coll->getYsize());
-    double dx, dy, dz;
-    coll->getMisalignment(dx, dy, dz);
-    attributeRegistry["DX"]->setReal(dx);
-    attributeRegistry["DY"]->setReal(dy);
 }
 
 
 void OpalRCollimator::update() {
-    double dx = Attributes::getReal(itsAttr[DX]);
-    double dy = Attributes::getReal(itsAttr[DY]);
+    OpalElement::update();
 
     CollimatorRep *coll =
         dynamic_cast<CollimatorRep *>(getElement()->removeWrappers());
@@ -96,19 +84,6 @@ void OpalRCollimator::update() {
     coll->setOutputFN(Attributes::getString(itsAttr[OUTFN]));
     coll->setRColl();
 
-    coll->setMisalignment(dx, dy, 0.0);
-    /*
-    std::vector<double> apert = getApert();
-    double apert_major = -1., apert_minor = -1.;
-    if(apert.size() > 0) {
-        apert_major = apert[0];
-        if(apert.size() > 1) {
-            apert_minor = apert[1];
-        } else {
-            apert_minor = apert[0];
-        }
-    }
-    */
     if(itsAttr[SURFACEPHYSICS] && sphys_m == NULL) {
         sphys_m = (SurfacePhysics::find(Attributes::getString(itsAttr[SURFACEPHYSICS])))->clone(getOpalName() + std::string("_sphys"));
         sphys_m->initSurfacePhysicsHandler(*coll);
diff --git a/src/Elements/OpalRCollimator.h b/src/Elements/OpalRCollimator.h
index 012cd6c029a273a733401e6a5eb2577b43537b9b..cf3b596bd8bfae5e13c644c05b57939b908993a9 100644
--- a/src/Elements/OpalRCollimator.h
+++ b/src/Elements/OpalRCollimator.h
@@ -35,8 +35,6 @@ public:
         XSIZE = COMMON,  // The horizontal half-size.
         YSIZE,           // The vertical half-size.
         OUTFN,
-        DX,             // Misalignment: translation in x direction
-        DY,             // Misalignment: translation in y direction
         SIZE
     };
 
diff --git a/src/Elements/OpalRingDefinition.cpp b/src/Elements/OpalRingDefinition.cpp
index 4e7c506502a3183142ed7c40120c8258e1034ae9..04676be811b27bcbc14775077a00f1eda6efee33 100644
--- a/src/Elements/OpalRingDefinition.cpp
+++ b/src/Elements/OpalRingDefinition.cpp
@@ -36,7 +36,7 @@
 OpalRingDefinition::OpalRingDefinition() :
     OpalElement(SIZE, "RINGDEFINITION",
                 "The \"RINGDEFINITION\" element defines basic ring parameters.") {
-  
+
     itsAttr[HARMONIC_NUMBER] = Attributes::makeReal("HARMONIC_NUMBER",
                                                     "The assumed harmonic number of the ring (i.e. number of bunches in the ring on a given turn).");
     itsAttr[LAT_RINIT] = Attributes::makeReal("LAT_RINIT",
@@ -102,13 +102,15 @@ void OpalRingDefinition::update() {
     ring->setBeamPRInit(Attributes::getReal(itsAttr[BEAM_PRINIT]));
     ring->setBeamRInit(Attributes::getReal(itsAttr[BEAM_RINIT]));
     ring->setLatticeRInit(Attributes::getReal(itsAttr[LAT_RINIT]));
+
     ring->setLatticePhiInit(Attributes::getReal(itsAttr[LAT_PHIINIT])*degree);
     ring->setLatticeThetaInit(Attributes::getReal(itsAttr[LAT_THETAINIT])*degree);
     ring->setSymmetry(Attributes::getReal(itsAttr[SYMMETRY]));
     ring->setScale(Attributes::getReal(itsAttr[SCALE]));
+
     ring->setHarmonicNumber(Attributes::getReal(itsAttr[HARMONIC_NUMBER]));
     ring->setRFFreq(Attributes::getReal(itsAttr[RFFREQ]));
     ring->setIsClosed(!(Attributes::getString(itsAttr[IS_CLOSED])=="FALSE"));
 
     setElement(ring->makeWrappers());
-}
+}
\ No newline at end of file
diff --git a/src/Elements/OpalSBend.cpp b/src/Elements/OpalSBend.cpp
index d7f5fb9f55ed0eff10b0c0700361f5078eb7c9b4..7d9a2a69e153b04f70ea8959370aedc7506a4007 100644
--- a/src/Elements/OpalSBend.cpp
+++ b/src/Elements/OpalSBend.cpp
@@ -25,6 +25,7 @@
 #include "Physics/Physics.h"
 #include "Structure/OpalWake.h"
 #include "Structure/SurfacePhysics.h"
+#include "Utilities/OpalException.h"
 #include <cmath>
 
 // Class OpalSBend
@@ -103,16 +104,11 @@ fillRegisteredAttributes(const ElementBase &base, ValueFlag flag) {
     attributeRegistry["SLICES"]->setReal(bend->getSlices());
     attributeRegistry["STEPSIZE"]->setReal(bend->getStepsize());
     //attributeRegistry["FMAPFN"]->setString(bend->getFieldMapFN());
-
-
-    double dx, dy, dz;
-    bend->getMisalignment(dx, dy, dz);
-    attributeRegistry["DX"]->setReal(dx);
-    attributeRegistry["DY"]->setReal(dy);
 }
 
 
 void OpalSBend::update() {
+    OpalElement::update();
 
     // Define geometry.
     SBendRep *bend = dynamic_cast<SBendRep *>(getElement()->removeWrappers());
@@ -157,69 +153,48 @@ void OpalSBend::update() {
 
     // Set field amplitude or bend angle.
     if(itsAttr[ANGLE])
-        bend->SetBendAngle(Attributes::getReal(itsAttr[ANGLE]));
+        bend->setBendAngle(Attributes::getReal(itsAttr[ANGLE]));
     else
-        bend->SetFieldAmplitude(k0, k0s);
+        bend->setFieldAmplitude(k0, k0s);
 
     if(itsAttr[GREATERTHANPI])
-        bend->SetAngleGreaterThanPiFlag(Attributes::getBool(itsAttr[GREATERTHANPI]));
-    else
-        bend->SetAngleGreaterThanPiFlag(false);
+        throw OpalException("OpalSBend::update",
+                            "GREATERTHANPI not supportet any more");
 
     if(itsAttr[ROTATION])
-        bend->SetRotationAboutZ(Attributes::getReal(itsAttr[ROTATION]));
-    else
-        bend->SetRotationAboutZ(0.0);
+        throw OpalException("OpalSBend::update",
+                            "ROTATION not supportet any more; use PSI instead");
 
     if(itsAttr[FMAPFN])
-        bend->SetFieldMapFN(Attributes::getString(itsAttr[FMAPFN]));
+        bend->setFieldMapFN(Attributes::getString(itsAttr[FMAPFN]));
     else if(bend->getName() != "SBEND") {
         ERRORMSG(bend->getName() << ": No filename for a field map given. "
                  "Will assume the default map "
                  "\"1DPROFILE1-DEFAULT\"."
                  << endl);
-        bend->SetFieldMapFN("1DPROFILE1-DEFAULT");
+        bend->setFieldMapFN("1DPROFILE1-DEFAULT");
     }
 
-    if(itsAttr[E1])
-        bend->SetEntranceAngle(Attributes::getReal(itsAttr[E1]));
-    else if(itsAttr[ALPHA])
-        bend->SetEntranceAngle(Attributes::getReal(itsAttr[ALPHA]));
-    else
-        bend->SetEntranceAngle(0.0);
-
-    if(itsAttr[BETA])
-        bend->SetBeta(Attributes::getReal(itsAttr[BETA]));
-    else
-        bend->SetBeta(0.0);
+    bend->setEntranceAngle(Attributes::getReal(itsAttr[E1]));
+    bend->setExitAngle(Attributes::getReal(itsAttr[E2]));
 
     // Units are eV.
     if(itsAttr[DESIGNENERGY]) {
-        bend->SetDesignEnergy(Attributes::getReal(itsAttr[DESIGNENERGY]));
+        bend->setDesignEnergy(Attributes::getReal(itsAttr[DESIGNENERGY]), false);
     }
 
-    if(itsAttr[GAP])
-        bend->SetFullGap(Attributes::getReal(itsAttr[GAP]));
-    else
-        bend->SetFullGap(0.0);
+    bend->setFullGap(Attributes::getReal(itsAttr[GAP]));
 
-    if(itsAttr[HAPERT])
-        bend->SetAperture(Attributes::getReal(itsAttr[HAPERT]));
-    else
-        bend->SetAperture(0.0);
+    if(itsAttr[APERT])
+        throw OpalException("OpalRBend::fillRegisteredAttributes",
+                            "APERTURE in RBEND not supported; use GAP and HAPERT instead");
 
-    if(itsAttr[LENGTH])
-        bend->SetLength(Attributes::getReal(itsAttr[LENGTH]));
-    else
-        bend->SetLength(0.0);
+    bend->setAperture(ElementBase::RECTANGULAR, std::vector<double>(2, Attributes::getReal(itsAttr[HAPERT])));
 
-    if(itsAttr[E2])
-        bend->setExitAngle(Attributes::getReal(itsAttr[E2]));
-    else if(itsAttr[EXITANGLE])
-        bend->setExitAngle(Attributes::getReal(itsAttr[EXITANGLE]));
-    //        bend->setExitFaceSlope(tan(Physics::pi * Attributes::getReal(itsAttr[EXITANGLE]) / 180.0));
+    if(itsAttr[LENGTH])
+        bend->setLength(Attributes::getReal(itsAttr[LENGTH]));
     else
-        bend->setExitAngle(0.0);
+        bend->setLength(0.0);
 
     if(itsAttr[WAKEF] && itsAttr[DESIGNENERGY] && owk_m == NULL) {
         owk_m = (OpalWake::find(Attributes::getString(itsAttr[WAKEF])))->clone(getOpalName() + std::string("_wake"));
@@ -228,40 +203,16 @@ void OpalSBend::update() {
     }
 
     if(itsAttr[K1])
-        bend->SetK1(Attributes::getReal(itsAttr[K1]));
+        bend->setK1(Attributes::getReal(itsAttr[K1]));
     else
-        bend->SetK1(0.0);
-
-    bend->setMisalignment(Attributes::getReal(itsAttr[DX]),
-                          Attributes::getReal(itsAttr[DY]),
-                          0.0);
-
-    //  if (itsAttr[L])
-    //   bend->setL(Attributes::getReal(itsAttr[L]));
-    //  else
-    //    bend->setL(0.0);
-    /*
-    std::vector<double> apert = getApert();
-    double apert_major = -1., apert_minor = -1.;
-    if(apert.size() > 0) {
-        apert_major = apert[0];
-        if(apert.size() > 1) {
-            apert_minor = apert[1];
-        } else {
-            apert_minor = apert[0];
-        }
-    }
-    */
+        bend->setK1(0.0);
+
     if(itsAttr[SURFACEPHYSICS] && sphys_m == NULL) {
         sphys_m = (SurfacePhysics::find(Attributes::getString(itsAttr[SURFACEPHYSICS])))->clone(getOpalName() + std::string("_sphys"));
         sphys_m->initSurfacePhysicsHandler(*bend);
         bend->setSurfacePhysics(sphys_m->handler_m);
     }
 
-    double dx = Attributes::getReal(itsAttr[DX]);
-    double dy = Attributes::getReal(itsAttr[DY]);
-    bend->setMisalignment(dx, dy, 0.0);
-
     // Transmit "unknown" attributes.
     OpalElement::updateUnknown(bend);
 }
diff --git a/src/Elements/OpalSeparator.cpp b/src/Elements/OpalSeparator.cpp
index f5108343344e4cd36ba6e2566cf8ceee35e4c95e..546f4e69395ed36255ca0efa9b5e60caa036ceb1 100644
--- a/src/Elements/OpalSeparator.cpp
+++ b/src/Elements/OpalSeparator.cpp
@@ -69,6 +69,8 @@ fillRegisteredAttributes(const ElementBase &base, ValueFlag flag) {
 
 
 void OpalSeparator::update() {
+    OpalElement::update();
+
     SeparatorRep *sep =
         dynamic_cast<SeparatorRep *>(getElement()->removeWrappers());
     double length = Attributes::getReal(itsAttr[LENGTH]);
diff --git a/src/Elements/OpalSeptum.cpp b/src/Elements/OpalSeptum.cpp
index da3e0fe1a13ecdd86ea953004aab0b348255e62f..94147fcf0fc0cdac62357d8d074b3a9632191dca 100644
--- a/src/Elements/OpalSeptum.cpp
+++ b/src/Elements/OpalSeptum.cpp
@@ -81,6 +81,8 @@ void OpalSeptum::fillRegisteredAttributes(const ElementBase &base, ValueFlag fla
 
 
 void OpalSeptum::update() {
+    OpalElement::update();
+
     SeptumRep *sept =
         dynamic_cast<SeptumRep *>(getElement()->removeWrappers());
     double length = Attributes::getReal(itsAttr[LENGTH]);
diff --git a/src/Elements/OpalSeptum.h b/src/Elements/OpalSeptum.h
index 1968a8b29824b9aa22b518a6be173627a42c5a8f..43e43537b831364a71186757725a4ecdb3e8e0f5 100644
--- a/src/Elements/OpalSeptum.h
+++ b/src/Elements/OpalSeptum.h
@@ -32,12 +32,12 @@ public:
 
     /// The attributes of class OpalSeptum.
     enum {
-        XSTART,           // Start of x coordinate
-        XEND,           // End of x coordinate
+        XSTART = COMMON, // Start of x coordinate
+        XEND,            // End of x coordinate
         YSTART,          // Start of y coordinate
-        YEND1,          // Not used now
-        YEND,          // End of y coordinate
-        WIDTH,       // Width of the septum
+        YEND1,           // Not used now
+        YEND,            // End of y coordinate
+        WIDTH,           // Width of the septum
         SIZE
     };
     ///YEND1 is not used since it is treated as a string in the input file which should be a real argument.
diff --git a/src/Elements/OpalSextupole.cpp b/src/Elements/OpalSextupole.cpp
index 1adaf4fc09c90769785cbde6721bc4d7db0711b9..176f330bcebeb29fe54019217551578a5c7131e4 100644
--- a/src/Elements/OpalSextupole.cpp
+++ b/src/Elements/OpalSextupole.cpp
@@ -41,15 +41,12 @@ OpalSextupole::OpalSextupole():
                 "The \"SEXTUPOLE\" element defines a Sextupole.") {
     itsAttr[K2] = Attributes::makeReal
                   ("K2", "Normalised upright sextupole coefficient in m^(-3)");
+    itsAttr[DK2] = Attributes::makeReal
+                  ("DK2", "Normalised upright sextupole coefficient error in m^(-3)");
     itsAttr[K2S] = Attributes::makeReal
                    ("K2S", "Normalised skew sextupole coefficient in m^(-3)");
-    itsAttr[DX] = Attributes::makeReal
-      ("DX", "Misalignment in x direction",0.0);
-    itsAttr[DY] = Attributes::makeReal
-      ("DY", "Misalignment in y direction",0.0);
-
-    registerRealAttribute("DX");
-    registerRealAttribute("DY");
+    itsAttr[DK2S] = Attributes::makeReal
+                   ("DK2S", "Normalised skew sextupole coefficient error in m^(-3)");
 
     setElement((new MultipoleRep("SEXTUPOLE"))->makeWrappers());
 }
@@ -124,6 +121,8 @@ fillRegisteredAttributes(const ElementBase &base, ValueFlag flag) {
 
 
 void OpalSextupole::update() {
+    OpalElement::update();
+
     MultipoleRep *sext =
         dynamic_cast<MultipoleRep *>(getElement()->removeWrappers());
     sext->setElementLength(Attributes::getReal(itsAttr[LENGTH]));
@@ -132,13 +131,8 @@ void OpalSextupole::update() {
     field.setNormalComponent(3, factor * Attributes::getReal(itsAttr[K2]));
     field.setSkewComponent(3, factor * Attributes::getReal(itsAttr[K2S]));
     sext->setField(field);
-
-    sext->setNormalComponent(3, Attributes::getReal(itsAttr[K2]));
-    sext->setSkewComponent(3, Attributes::getReal(itsAttr[K2S]));
-
-    double dx = Attributes::getReal(itsAttr[DX]);
-    double dy = Attributes::getReal(itsAttr[DY]);
-    sext->setMisalignment(dx, dy, 0.0);
+    sext->setNormalComponent(3, Attributes::getReal(itsAttr[K2]), Attributes::getReal(itsAttr[DK2]));
+    sext->setSkewComponent(3, Attributes::getReal(itsAttr[K2S]), Attributes::getReal(itsAttr[DK2S]));
 
     // Transmit "unknown" attributes.
     OpalElement::updateUnknown(sext);
diff --git a/src/Elements/OpalSextupole.h b/src/Elements/OpalSextupole.h
index 6b424ca9904607ebc3b234a2f345ea353f5b3774..72971b4a7b28237f2693d0f002de278c0c7aa50e 100644
--- a/src/Elements/OpalSextupole.h
+++ b/src/Elements/OpalSextupole.h
@@ -32,9 +32,9 @@ public:
     /// The attributes of class OpalSextupole.
     enum {
         K2 = COMMON,  // The normal sextupole strength.
+        DK2,          // The normal sextupole strength error.
         K2S,          // The skew sextupole strength.
-        DX,
-        DY,
+        DK2S,         // The skew sextupole strength error.
         SIZE
     };
 
diff --git a/src/Elements/OpalSlit.cpp b/src/Elements/OpalSlit.cpp
index 1b1e91787759edb9c4b760ef375f3cdc30be5cd8..a091a4d98f5a46af41d7aa31f60c877227f2e1f7 100644
--- a/src/Elements/OpalSlit.cpp
+++ b/src/Elements/OpalSlit.cpp
@@ -35,17 +35,10 @@ OpalSlit::OpalSlit():
     itsAttr[OUTFN] = Attributes::makeString
                      ("OUTFN", "Monitor output filename");
 
-    itsAttr[DX] = Attributes::makeReal
-      ("DX", "Misalignment in x direction",0.0);
-    itsAttr[DY] = Attributes::makeReal
-      ("DY", "Misalignment in y direction",0.0);
-
 
     registerStringAttribute("OUTFN");
     registerRealAttribute("XSIZE");
     registerRealAttribute("YSIZE");
-    registerRealAttribute("DX");
-    registerRealAttribute("DY");
 
     setElement((new CollimatorRep("SLIT"))->makeAlignWrapper());
 }
@@ -76,15 +69,12 @@ void OpalSlit::fillRegisteredAttributes(const ElementBase &base, ValueFlag flag)
         dynamic_cast<const CollimatorRep *>(base.removeWrappers());
     attributeRegistry["XSIZE"]->setReal(coll->getXsize());
     attributeRegistry["YSIZE"]->setReal(coll->getYsize());
-
-    double dx, dy, dz;
-    coll->getMisalignment(dx, dy, dz);
-    attributeRegistry["DX"]->setReal(dx);
-    attributeRegistry["DY"]->setReal(dy);
 }
 
 
 void OpalSlit::update() {
+    OpalElement::update();
+
     CollimatorRep *coll =
         dynamic_cast<CollimatorRep *>(getElement()->removeWrappers());
     double length = Attributes::getReal(itsAttr[LENGTH]);
@@ -94,28 +84,15 @@ void OpalSlit::update() {
     coll->setOutputFN(Attributes::getString(itsAttr[OUTFN]));
     coll->setSlit();
 
-    double dx = Attributes::getReal(itsAttr[DX]);
-    double dy = Attributes::getReal(itsAttr[DY]);
-    /*
-    std::vector<double> apert = getApert();
-    double apert_major = -1., apert_minor = -1.;
-    if(apert.size() > 0) {
-        apert_major = apert[0];
-        if(apert.size() > 1) {
-            apert_minor = apert[1];
-        } else {
-            apert_minor = apert[0];
-        }
-    }
-    */
     if(itsAttr[SURFACEPHYSICS] && sphys_m == NULL) {
         sphys_m = (SurfacePhysics::find(Attributes::getString(itsAttr[SURFACEPHYSICS])))->clone(getOpalName() + std::string("_sphys"));
         sphys_m->initSurfacePhysicsHandler(*coll);
         coll->setSurfacePhysics(sphys_m->handler_m);
     }
 
-    coll->setMisalignment(dx, dy, 0.0);
-
+    std::vector<double> apert = {Attributes::getReal(itsAttr[XSIZE]),
+                                 Attributes::getReal(itsAttr[YSIZE])};
+    coll->setAperture(ElementBase::RECTANGULAR, apert );
 
     // Transmit "unknown" attributes.
     OpalElement::updateUnknown(coll);
diff --git a/src/Elements/OpalSlit.h b/src/Elements/OpalSlit.h
index ccc6dee73e085e52904c280452117115eab7ff53..7755a4b78090a12c0e2ae3c7ba433fecdf9710f5 100644
--- a/src/Elements/OpalSlit.h
+++ b/src/Elements/OpalSlit.h
@@ -35,8 +35,6 @@ public:
         XSIZE = COMMON,  // The horizontal half-size.
         YSIZE,           // The vertical half-size.
         OUTFN,
-        DX,             // Misalignment: translation in x direction
-        DY,             // Misalignment: translation in y direction
         SIZE
     };
 
diff --git a/src/Elements/OpalSolenoid.cpp b/src/Elements/OpalSolenoid.cpp
index 19c7377272a14fcceee78af49c9057dcd8002de5..4532610d79a64cc20a001bb535f78a2d2a2b9a61 100644
--- a/src/Elements/OpalSolenoid.cpp
+++ b/src/Elements/OpalSolenoid.cpp
@@ -31,21 +31,18 @@ OpalSolenoid::OpalSolenoid():
                 "The \"SOLENOID\" element defines a Solenoid.") {
     itsAttr[KS] = Attributes::makeReal
                   ("KS", "Normalised solenoid strength in m**(-1)");
+    itsAttr[DKS] = Attributes::makeReal
+                  ("DKS", "Normalised solenoid strength error in m**(-1)");
 
     registerRealAttribute("KS");
+    registerRealAttribute("DKS");
 
     itsAttr[FMAPFN] = Attributes::makeString
                       ("FMAPFN", "Solenoid field map filename ");
     itsAttr[FAST] = Attributes::makeBool
                     ("FAST", "Faster but less accurate", true);
-    itsAttr[DX] = Attributes::makeReal
-      ("DX", "Misalignment in x direction",0.0);
-    itsAttr[DY] = Attributes::makeReal
-      ("DY", "Misalignment in y direction",0.0);
 
     registerStringAttribute("FMAPFN");
-    registerRealAttribute("DX");
-    registerRealAttribute("DY");
 
     setElement((new SolenoidRep("SOLENOID"))->makeAlignWrapper());
 }
@@ -76,30 +73,25 @@ fillRegisteredAttributes(const ElementBase &base, ValueFlag flag) {
         double length = sol->getElementLength();
         double ks = length * sol->getBz() * Physics::c / OpalData::getInstance()->getP0();
         attributeRegistry["KS"]->setReal(ks);
-        double dx, dy, dz;
-        sol->getMisalignment(dx, dy, dz);
-        attributeRegistry["DX"]->setReal(dx);
-        attributeRegistry["DY"]->setReal(dy);
     }
 }
 
 
 void OpalSolenoid::update() {
+    OpalElement::update();
+
     SolenoidRep *sol =
         dynamic_cast<SolenoidRep *>(getElement()->removeWrappers());
     double length = Attributes::getReal(itsAttr[LENGTH]);
     double Bz = Attributes::getReal(itsAttr[KS]) * OpalData::getInstance()->getP0() / Physics::c;
     bool fast = Attributes::getBool(itsAttr[FAST]);
-    double dx = Attributes::getReal(itsAttr[DX]);
-    double dy = Attributes::getReal(itsAttr[DY]);
-
-    sol->setMisalignment(dx, dy, 0.0);
 
     sol->setElementLength(length);
     sol->setFieldMapFN(Attributes::getString(itsAttr[FMAPFN]));
     sol->setFast(fast);
     sol->setBz(Bz);
     sol->setKS(Attributes::getReal(itsAttr[KS]));
+    sol->setDKS(Attributes::getReal(itsAttr[DKS]));
 
     // Transmit "unknown" attributes.
     OpalElement::updateUnknown(sol);
diff --git a/src/Elements/OpalSolenoid.h b/src/Elements/OpalSolenoid.h
index 2eb708f8f9d624dd602947b8db27b2c1fdc93b51..f063ec8e122809beabb6c5c1dc96031fccef36dd 100644
--- a/src/Elements/OpalSolenoid.h
+++ b/src/Elements/OpalSolenoid.h
@@ -32,10 +32,9 @@ public:
     /// The attributes of class OpalSolenoid.
     enum {
         KS = COMMON,  // The longitudinal magnetic field.
-        FMAPFN,          // The Field filename
-        FAST,           // Faster but less accurate
-        DX,             // Misalignment: translation in x direction
-        DY,             // Misalignment: translation in y direction
+        DKS,          // The longitudinal magnetic field error.
+        FMAPFN,       // The Field filename
+        FAST,         // Faster but less accurate
         SIZE
     };
 
diff --git a/src/Elements/OpalStripper.cpp b/src/Elements/OpalStripper.cpp
index 12110d0e95db7179c28655605e8cf0019b44b967..15a521a3b70415dfb465daa086acad63d560191f 100644
--- a/src/Elements/OpalStripper.cpp
+++ b/src/Elements/OpalStripper.cpp
@@ -84,6 +84,8 @@ void OpalStripper::fillRegisteredAttributes(const ElementBase &base, ValueFlag f
 
 
 void OpalStripper::update() {
+    OpalElement::update();
+
     StripperRep *strp =dynamic_cast<StripperRep *>(getElement()->removeWrappers());
     double length = Attributes::getReal(itsAttr[LENGTH]);
     double xstart = Attributes::getReal(itsAttr[XSTART]);
diff --git a/src/Elements/OpalStripper.h b/src/Elements/OpalStripper.h
index 7bd3aba5bc5b7ada4c9978dba13b36ca3cfdc65e..35e1c9b45ddf29dfef6fc5d8ceb9262e7a0d9698 100644
--- a/src/Elements/OpalStripper.h
+++ b/src/Elements/OpalStripper.h
@@ -31,13 +31,13 @@ public:
 
     /// The attributes of class OpalStripper.
     enum {
-        XSTART,           // Start of x coordinate
+        XSTART = COMMON,  // Start of x coordinate
         XEND,             // End of x coordinate
         YSTART,           // Start of y coordinate
         YEND,             // End of y coordinate
         WIDTH,            // Width of the probe
-        OPCHARGE,           // Charge number of the outcome particle
-        OPMASS,             // Mass of the outcome particle
+        OPCHARGE,         // Charge number of the outcome particle
+        OPMASS,           // Mass of the outcome particle
         OPYIELD,
         STOP,
         SIZE
diff --git a/src/Elements/OpalTravelingWave.cpp b/src/Elements/OpalTravelingWave.cpp
index 4e86395afcfea62588c2af84412bc4315d42df4b..347bbedc463e4435fe3d1da4406b6026cbf006ae 100644
--- a/src/Elements/OpalTravelingWave.cpp
+++ b/src/Elements/OpalTravelingWave.cpp
@@ -32,11 +32,15 @@ OpalTravelingWave::OpalTravelingWave():
                 "The \"TRAVELINGWAVE\" element defines a traveling wave structure."),
     owk_m(NULL) {
     itsAttr[VOLT] = Attributes::makeReal
-                    ("VOLT", "RF voltage in MV");
+                    ("VOLT", "RF voltage in MV/m");
+    itsAttr[DVOLT] = Attributes::makeReal
+                     ("DVOLT", "RF voltage error in MV/m");
     itsAttr[FREQ] = Attributes::makeReal
                     ("FREQ", "RF frequency in MHz");
     itsAttr[LAG] = Attributes::makeReal
-                   ("LAG", "Phase lag, in multiples of (2*pi)");
+                   ("LAG", "Phase lag in rad");
+    itsAttr[DLAG] = Attributes::makeReal
+                    ("DLAG", "Phase lag error in rad");
     itsAttr[HARMON] = Attributes::makeReal
                       ("HARMON", "Harmonic number");
     itsAttr[BETARF] = Attributes::makeReal
@@ -57,19 +61,18 @@ OpalTravelingWave::OpalTravelingWave():
                           ("CAVITYTYPE", "STANDING or TRAVELING wave cavity in photoinjector and LINAC; SINGLEGAP or DOUBLEGAP cavity in cyclotron");
     itsAttr[NUMCELLS] = Attributes::makeReal
                         ("NUMCELLS", "Number of cells in a TW structure");
-    itsAttr[DX] = Attributes::makeReal
-      ("DX", "Misalignment in x direction",0.0);
-    itsAttr[DY] = Attributes::makeReal
-      ("DY", "Misalignment in y direction",0.0);
+    itsAttr[DESIGNENERGY] = Attributes::makeReal
+                            ("DESIGNENERGY", "the mean energy of the particles at exit", -1.0);
 
     registerRealAttribute("VOLT");
+    registerRealAttribute("DVOLT");
     registerRealAttribute("FREQ");
     registerRealAttribute("LAG");
+    registerRealAttribute("DLAG");
     registerStringAttribute("FMAPFN");
     registerStringAttribute("CAVITYTYPE");
     registerRealAttribute("NUMCELLS");
-    registerRealAttribute("DX");
-    registerRealAttribute("DY");
+    registerRealAttribute("DESIGNENERGY");
 
     setElement((new TravelingWaveRep("TRAVELINGWAVE"))->makeAlignWrapper());
 }
@@ -101,35 +104,35 @@ fillRegisteredAttributes(const ElementBase &base, ValueFlag flag) {
         const TravelingWaveRep *rfc =
             dynamic_cast<const TravelingWaveRep *>(base.removeWrappers());
         attributeRegistry["VOLT"]->setReal(rfc->getAmplitude());
+        attributeRegistry["DVOLT"]->setReal(rfc->getAmplitudeError());
         attributeRegistry["FREQ"]->setReal(rfc->getFrequency());
         attributeRegistry["LAG"]->setReal(rfc->getPhase());
+        attributeRegistry["DLAG"]->setReal(rfc->getPhaseError());
         attributeRegistry["FMAPFN"]->setString(rfc->getFieldMapFN());
-        double dx, dy, dz;
-        rfc->getMisalignment(dx, dy, dz);
-        attributeRegistry["DX"]->setReal(dx);
-        attributeRegistry["DY"]->setReal(dy);
     }
 }
 
 
 void OpalTravelingWave::update() {
     using Physics::two_pi;
+
+    OpalElement::update();
+
     TravelingWaveRep *rfc =
         dynamic_cast<TravelingWaveRep *>(getElement()->removeWrappers());
 
     double length = Attributes::getReal(itsAttr[LENGTH]);
     double vPeak  = Attributes::getReal(itsAttr[VOLT]);
+    double vPeakError  = Attributes::getReal(itsAttr[DVOLT]);
     double phase  = Attributes::getReal(itsAttr[LAG]);
+    double phaseError  = Attributes::getReal(itsAttr[DLAG]);
     double freq   = (1.0e6 * two_pi) * Attributes::getReal(itsAttr[FREQ]);
     std::string fmapfm = Attributes::getString(itsAttr[FMAPFN]);
     bool fast = Attributes::getBool(itsAttr[FAST]);
     bool apVeto = Attributes::getBool(itsAttr[APVETO]);
 
     std::string type = Attributes::getString(itsAttr[TYPE]);
-    double dx = Attributes::getReal(itsAttr[DX]);
-    double dy = Attributes::getReal(itsAttr[DY]);
-
-    rfc->setMisalignment(dx, dy, 0.0);
+    double kineticEnergy = Attributes::getReal(itsAttr[DESIGNENERGY]);
 
     rfc->setElementLength(length);
     rfc->setAmplitude(1.0e6 * vPeak);
@@ -140,15 +143,20 @@ void OpalTravelingWave::update() {
     rfc->setFast(fast);
     rfc->setAutophaseVeto(apVeto);
     rfc->setAmplitudem(vPeak);
+    rfc->setAmplitudeError(vPeakError);
     rfc->setFrequencym(freq);
     rfc->setPhasem(phase);
+    rfc->setPhaseError(phaseError);
     rfc->setNumCells((int)Attributes::getReal(itsAttr[NUMCELLS]));
 
+    rfc->setDesignEnergy(kineticEnergy);
+
     if(itsAttr[WAKEF] && owk_m == NULL) {
         owk_m = (OpalWake::find(Attributes::getString(itsAttr[WAKEF])))->clone(getOpalName() + std::string("_wake"));
         owk_m->initWakefunction(*rfc);
         rfc->setWake(owk_m->wf_m);
     }
+
     // Transmit "unknown" attributes.
     OpalElement::updateUnknown(rfc);
 }
diff --git a/src/Elements/OpalTravelingWave.h b/src/Elements/OpalTravelingWave.h
index 6207c865aaacfd55320c0a62fb7d028d17c2fe9d..4b516dd4bc13e4f50c5c1082600cbf79b573369e 100644
--- a/src/Elements/OpalTravelingWave.h
+++ b/src/Elements/OpalTravelingWave.h
@@ -33,8 +33,10 @@ public:
     /// The attributes of class OpalTravelingWave.
     enum {
         VOLT = COMMON,  // The peak voltage.
+        DVOLT,          // The peak voltage error
         FREQ,           // The RF frequency.
         LAG,            // The phase lag.
+        DLAG,           // The phase lag error
         HARMON,         // The harmonic number.
         BETARF,         // The beta_RF.
         PG,             // The RF power.
@@ -47,6 +49,7 @@ public:
         NUMCELLS,       // Number of cells in a TW structure
         DX,             // Misalignment: translation in x direction
         DY,             // Misalignment: translation in y direction
+        DESIGNENERGY,   // The mean kinetic energy at exit
         SIZE
     };
 
diff --git a/src/Elements/OpalVKicker.cpp b/src/Elements/OpalVKicker.cpp
index 9a523a09502b9757bb497b7c0a0fe61619ffd1b6..13ca54cecb428e8a17f692f4a344bf65e5e5af00 100644
--- a/src/Elements/OpalVKicker.cpp
+++ b/src/Elements/OpalVKicker.cpp
@@ -34,8 +34,14 @@ OpalVKicker::OpalVKicker():
                 "acting on the vertical plane.") {
     itsAttr[KICK] = Attributes::makeReal
                     ("KICK", "Vertical deflection in rad");
+    itsAttr[DESIGNENERGY] = Attributes::makeReal
+                            ("DESIGNENERGY", "the mean energy of the particles", -1.0);
+    itsAttr[K0] = Attributes::makeReal
+                  ("K0", "Normal dipole field in T");
 
-    registerRealAttribute("VKICK");
+    registerRealAttribute("KICK");
+    registerRealAttribute("DESIGNENERGY");
+    registerRealAttribute("K0");
 
     setElement((new YCorrectorRep("VKICKER"))->makeWrappers());
 }
@@ -85,6 +91,8 @@ fillRegisteredAttributes(const ElementBase &base, ValueFlag flag) {
 
 
 void OpalVKicker::update() {
+    OpalElement::update();
+
     YCorrectorRep *corr = dynamic_cast<YCorrectorRep *>(getElement()->removeWrappers());
 
     double length = Attributes::getReal(itsAttr[LENGTH]);
@@ -93,8 +101,15 @@ void OpalVKicker::update() {
 
     corr->setElementLength(length);
     corr->setBx(kick * factor);
-    corr->setKickY(Attributes::getReal(itsAttr[KICK]));
+    corr->setKickY(kick);
+    if(itsAttr[DESIGNENERGY]) {
+        double kineticEnergy = Attributes::getReal(itsAttr[DESIGNENERGY]);
+        corr->setDesignEnergy(kineticEnergy, false);
+    }
 
+    if (itsAttr[K0]) {
+        corr->setKickField(Vector_t(Attributes::getReal(itsAttr[K0]), 0, 0));
+    }
     // Transmit "unknown" attributes.
     OpalElement::updateUnknown(corr);
-}
\ No newline at end of file
+}
diff --git a/src/Elements/OpalVKicker.h b/src/Elements/OpalVKicker.h
index 4d1c104758cbb84cf10af6acceafc3e035ff4659..40905df391acebfde3597faff9711bad01f2ab93 100644
--- a/src/Elements/OpalVKicker.h
+++ b/src/Elements/OpalVKicker.h
@@ -33,6 +33,8 @@ public:
     /// The attributes of class OpalVKicker.
     enum {
         KICK = COMMON,  // The kicker strength.
+        DESIGNENERGY,   // The mean kinetic energy at exit
+        K0,             // The magnetic field
         SIZE
     };
 
diff --git a/src/Elements/OpalVMonitor.cpp b/src/Elements/OpalVMonitor.cpp
index e3ad1868bc875dc519653b6074919fea30c42878..42b9846580face19fc2e88b1dea29f96575185c7 100644
--- a/src/Elements/OpalVMonitor.cpp
+++ b/src/Elements/OpalVMonitor.cpp
@@ -48,6 +48,8 @@ OpalVMonitor *OpalVMonitor::clone(const std::string &name) {
 
 
 void OpalVMonitor::update() {
+    OpalElement::update();
+
     YMonitorRep *mon =
         dynamic_cast<YMonitorRep *>(getElement()->removeWrappers());
     double length = Attributes::getReal(itsAttr[LENGTH]);
diff --git a/src/Elements/OpalVariableRFCavity.cpp b/src/Elements/OpalVariableRFCavity.cpp
index d945f91a08bcf18ee48110a685978b95553ee9d8..089e6863f05d76f08483c25ddaad15e38f6e0e4a 100644
--- a/src/Elements/OpalVariableRFCavity.cpp
+++ b/src/Elements/OpalVariableRFCavity.cpp
@@ -102,6 +102,8 @@ fillRegisteredAttributes(const ElementBase &base, ValueFlag flag) {
 }
 
 void OpalVariableRFCavity::update() {
+    OpalElement::update();
+
     VariableRFCavity *cavity = dynamic_cast<VariableRFCavity*>(
                                                 getElement()->removeWrappers());
     double length = Attributes::getReal(itsAttr[LENGTH]);
diff --git a/src/Elements/OpalWire.cpp b/src/Elements/OpalWire.cpp
index e900d037e99998c841b948a34a09b3b0afbb9f06..84ccfa29213f72455d259c1678a1a8865a46ad79 100644
--- a/src/Elements/OpalWire.cpp
+++ b/src/Elements/OpalWire.cpp
@@ -39,18 +39,11 @@ OpalWire::OpalWire():
     itsAttr[OUTFN] = Attributes::makeString
                      ("OUTFN", "Wire output filename");
 
-    itsAttr[DX] = Attributes::makeReal
-      ("DX", "Misalignment in x direction",0.0);
-    itsAttr[DY] = Attributes::makeReal
-      ("DY", "Misalignment in y direction",0.0);
-
     registerStringAttribute("OUTFN");
     registerRealAttribute("XSIZE");
     registerRealAttribute("YSIZE");
     registerRealAttribute("XPOS");
     registerRealAttribute("YPOS");
-    registerRealAttribute("DX");
-    registerRealAttribute("DY");
 
     setElement((new CollimatorRep("WIRE"))->makeAlignWrapper());
 }
@@ -81,20 +74,11 @@ void OpalWire::fillRegisteredAttributes(const ElementBase &base, ValueFlag flag)
         dynamic_cast<const CollimatorRep *>(base.removeWrappers());
     attributeRegistry["XSIZE"]->setReal(coll->getXsize());
     attributeRegistry["YSIZE"]->setReal(coll->getYsize());
-
-    double dx, dy, dz;
-    coll->getMisalignment(dx, dy, dz);
-    attributeRegistry["DX"]->setReal(dx);
-    attributeRegistry["DY"]->setReal(dy);
-
-    //  attributeRegistry["XPOS"]->setReal(coll->getXpos());
-    // attributeRegistry["YPOS"]->setReal(coll->getYpos());
 }
 
 
 void OpalWire::update() {
-    double dx = Attributes::getReal(itsAttr[DX]);
-    double dy = Attributes::getReal(itsAttr[DY]);
+    OpalElement::update();
 
     CollimatorRep *coll =
         dynamic_cast<CollimatorRep *>(getElement()->removeWrappers());
@@ -105,28 +89,14 @@ void OpalWire::update() {
     coll->setXpos(Attributes::getReal(itsAttr[XPOS]));
     coll->setYpos(Attributes::getReal(itsAttr[YPOS]));
     coll->setOutputFN(Attributes::getString(itsAttr[OUTFN]));
-    coll->setMisalignment(dx, dy, 0.0);
     coll->setWire();
 
-    /*
-    std::vector<double> apert = getApert();
-    double apert_major = -1., apert_minor = -1.;
-    if(apert.size() > 0) {
-        apert_major = apert[0];
-        if(apert.size() > 1) {
-            apert_minor = apert[1];
-        } else {
-            apert_minor = apert[0];
-        }
-    }
-    */
     if(itsAttr[SURFACEPHYSICS] && sphys_m == NULL) {
         sphys_m = (SurfacePhysics::find(Attributes::getString(itsAttr[SURFACEPHYSICS])))->clone(getOpalName() + std::string("_sphys"));
         sphys_m->initSurfacePhysicsHandler(*coll);
         coll->setSurfacePhysics(sphys_m->handler_m);
     }
 
-
     // Transmit "unknown" attributes.
     OpalElement::updateUnknown(coll);
 }
diff --git a/src/Elements/OpalWire.h b/src/Elements/OpalWire.h
index 26f820a922c45c36cc34833cc2f7fce664487d3c..630f92c746ef7bc482e992c0bab80d7673d2759c 100644
--- a/src/Elements/OpalWire.h
+++ b/src/Elements/OpalWire.h
@@ -36,8 +36,6 @@ public:
         XPOS,  // The horizontal position.
         YPOS,           // The vertical position.
         OUTFN,
-        DX,             // Misalignment: translation in x direction
-        DY,             // Misalignment: translation in y direction
         SIZE
     };
 
diff --git a/src/Errors/CMakeLists.txt b/src/Errors/CMakeLists.txt
index 01cc1ea925262bc2934ebdb868a85fd9866b8b43..d824e6b130ff9067790c7ca540c94fd64646454a 100644
--- a/src/Errors/CMakeLists.txt
+++ b/src/Errors/CMakeLists.txt
@@ -25,4 +25,29 @@ include_directories (
   ${CMAKE_CURRENT_SOURCE_DIR}
 )
 
-add_sources(${_SRCS})
+add_opal_sources(${_SRCS})
+
+set (HDRS
+    AlignBase.h
+    AlignHandler.h
+    AlignReader.h
+    AlignRemover.h
+    AlignWriter.h
+    ErrorAlign.h
+    ErrorCmd.h
+    ErrorComp.h
+    ErrorEnd.h
+    ErrorField.h
+    Error.h
+    ErrorParser.h
+    ErrorPrint.h
+    ErrorSave.h
+    ErrorSelect.h
+    MPBase.h
+    MPHandler.h
+    MPReader.h
+    MPRemover.h
+    MPWriter.h
+)
+
+install (FILES ${HDRS} DESTINATION "${CMAKE_INSTALL_PREFIX}/include/Errors")
\ No newline at end of file
diff --git a/src/Expressions/CMakeLists.txt b/src/Expressions/CMakeLists.txt
index 1db12ae8aefca2b79a1e95faba61d3dcd9ba6054..975a9fd20fb0b61fd1e03c14f9a0609ba71f16ef 100644
--- a/src/Expressions/CMakeLists.txt
+++ b/src/Expressions/CMakeLists.txt
@@ -1,15 +1,50 @@
 set (_SRCS
-  AColumn.cpp
-  ARow.cpp
-  ATable.cpp
-  Expressions.cpp
-  SCell.cpp
-  SFunction.cpp
-  SHash.cpp
+    AColumn.cpp
+    ARow.cpp
+    ATable.cpp
+    Expressions.cpp
+    SCell.cpp
+    SFunction.cpp
+    SHash.cpp
 )
 
 include_directories (
   ${CMAKE_CURRENT_SOURCE_DIR}
 )
 
-add_sources(${_SRCS})
+add_opal_sources(${_SRCS})
+
+set (HDRS
+    AAutomatic.h
+    ABinary.h
+    AColumn.h
+    ADeferred.h
+    AList.h
+    ARefAttr.h
+    ARefExpr.h
+    ARow.h
+    ASUnary.h
+    ATable.h
+    AUnary.h
+    AValue.h
+    Expressions.h
+    Indexer.h
+    SAutomatic.h
+    SBinary.h
+    SCell.h
+    SConstant.h
+    SDeferred.h
+    SFunction.h
+    SHash.h
+    SNull.h
+    SRefAttr.h
+    SRefExpr.h
+    SUnary.h
+    SValue.h
+    TFind.h
+    TFunction0.h
+    TFunction1.h
+    TFunction2.h
+)
+
+install (FILES ${HDRS} DESTINATION "${CMAKE_INSTALL_PREFIX}/include/Expressions")
\ No newline at end of file
diff --git a/src/Expressions/Expressions.cpp b/src/Expressions/Expressions.cpp
index 9c28a62c729eb3dc42e86cb4bc7468719403542c..c8c6c4da8f2943286e456e3d50391c2416e53526 100644
--- a/src/Expressions/Expressions.cpp
+++ b/src/Expressions/Expressions.cpp
@@ -157,11 +157,11 @@ namespace Expressions {
     double getEkin() {
         auto p = OpalData::getInstance()->getPartBunch();
         if (p)
-            return p->get_meanEnergy();
+            return p->get_meanKineticEnergy();
         else
             return -1.0;
     }
-    
+
 
     double ranf() {
         return Options::rangen.uniform();
diff --git a/src/Lines/CMakeLists.txt b/src/Lines/CMakeLists.txt
index f74b9a72c9b804b81f446d72782313b5a9d8b32d..44f1ad5a917252f0b08e33e3b3785f0f2b432cfb 100644
--- a/src/Lines/CMakeLists.txt
+++ b/src/Lines/CMakeLists.txt
@@ -13,4 +13,17 @@ include_directories (
   ${CMAKE_CURRENT_SOURCE_DIR}
 )
 
-add_sources(${_SRCS})
+add_opal_sources(${_SRCS})
+
+set (HDRS
+    FlatWriter.h
+    Line.h
+    LineTemplate.h
+    Replacer.h
+    Sequence.h
+    SequenceMember.h
+    SequenceParser.h
+    SequenceTemplate.h
+)
+
+install (FILES ${HDRS} DESTINATION "${CMAKE_INSTALL_PREFIX}/include/Lines")
\ No newline at end of file
diff --git a/src/Lines/Line.cpp b/src/Lines/Line.cpp
index 4c2e17584c88c2ebb2459f7bac780509589692fd..5cc30675c033d5423a0ca4534feb50737b6647ac 100644
--- a/src/Lines/Line.cpp
+++ b/src/Lines/Line.cpp
@@ -43,7 +43,6 @@
 
 using namespace Expressions;
 
-
 // Class Line
 // ------------------------------------------------------------------------
 
@@ -52,6 +51,14 @@ namespace {
     enum {
         TYPE,        // The type attribute.
         LENGTH,      // The line length.
+        ORIGIN,      // The location of the particle source
+        ORIENTATION,      // The orientation of the particle source
+        X,
+        Y,
+        Z,
+        THETA,
+        PHI,
+        PSI,
         SIZE
     };
 
@@ -72,6 +79,30 @@ Line::Line():
                       ("L", "Total length of line in m");
     itsAttr[LENGTH].setReadOnly(true);
 
+    itsAttr[ORIGIN] = Attributes::makeRealArray
+        ("ORIGIN", "The location of the particle source");
+
+    itsAttr[ORIENTATION] = Attributes::makeRealArray
+        ("ORIENTATION", "The Tait-Bryan angles for the orientation of the particle source");
+
+    itsAttr[X] = Attributes::makeReal
+        ("X", "The x-coordinate of the location of the particle source", 0);
+
+    itsAttr[Y] = Attributes::makeReal
+        ("Y", "The y-coordinate of the location of the particle source", 0);
+
+    itsAttr[Z] = Attributes::makeReal
+        ("Z", "The z-coordinate of the location of the particle source", 0);
+
+    itsAttr[THETA] = Attributes::makeReal
+        ("THETA", "The rotation about the y-axis of the particle source", 0);
+
+    itsAttr[PHI] = Attributes::makeReal
+        ("PHI", "The rotation about the x-axis of the particle source", 0);
+
+    itsAttr[PSI] = Attributes::makeReal
+        ("PSI", "The rotation about the z-axis of the particle source", 0);
+
     setElement((new FlaggedBeamline("LINE"))->makeAlignWrapper());
 }
 
@@ -162,6 +193,78 @@ void Line::parse(Statement &stat) {
         i->setCounter(elem->increment());
     }
     if(expr.isValid()) itsAttr[LENGTH].set(new SAutomatic<double>(expr));
+
+    while(stat.delimiter(',')) {
+        std::string name = Expressions::parseString(stat, "Attribute name expected.");
+        Attribute *attr = findAttribute(name);
+
+        if (attr != 0) {
+            if(stat.delimiter('=')) {
+                attr->parse(stat, true);
+            } else if(stat.delimiter(":=")) {
+                attr->parse(stat, false);
+            } else {
+                attr->setDefault();
+            }
+        }
+    }
+
+    if (itsAttr[ORIGIN] || itsAttr[ORIENTATION]) {
+        std::vector<double> origin = Attributes::getRealArray(itsAttr[ORIGIN]);
+        if (origin.size() == 3) {
+            line->setOrigin3D(Vector_t(origin[0],
+                                       origin[1],
+                                       origin[2]));
+        } else {
+            line->setOrigin3D(Vector_t(0.0));
+            if (itsAttr[ORIGIN]) {
+                throw OpalException("Line::parse","Parameter origin is array of 3 values (x, y, z);\n" +
+                                    std::to_string(origin.size()) + " values provided");
+            }
+        }
+
+        std::vector<double> direction = Attributes::getRealArray(itsAttr[ORIENTATION]);
+        if (direction.size() == 3) {
+            const double &theta = direction[0];
+            const double &phi = direction[1];
+            const double &psi = direction[2];
+
+            Quaternion rotTheta(cos(0.5 * theta), 0, -sin(0.5 * theta), 0);
+            Quaternion rotPhi(cos(0.5 * phi), -sin(0.5 * phi), 0, 0);
+            Quaternion rotPsi(cos(0.5 * psi), 0, 0, -sin(0.5 * psi));
+            line->setCoordTransformationTo(rotPsi * rotPhi * rotTheta);
+        } else {
+            line->setCoordTransformationTo(Quaternion(1, 0, 0, 0));
+            if (itsAttr[ORIENTATION]) {
+                throw OpalException("Line::parse","Parameter orientation is array of 3 values (theta, phi, psi);\n" +
+                                    std::to_string(direction.size()) + " values provided");
+            }
+        }
+
+        line->setRelativeFlag(true);
+    } else {
+        const Vector_t origin(Attributes::getReal(itsAttr[X]),
+                              Attributes::getReal(itsAttr[Y]),
+                              Attributes::getReal(itsAttr[Z]));
+
+        const double theta = Attributes::getReal(itsAttr[THETA]);
+        const double phi = Attributes::getReal(itsAttr[PHI]);
+        const double psi = Attributes::getReal(itsAttr[PSI]);
+
+        Quaternion rotTheta(cos(0.5 * theta), 0, -sin(0.5 * theta), 0);
+        Quaternion rotPhi(cos(0.5 * phi), -sin(0.5 * phi), 0, 0);
+        Quaternion rotPsi(cos(0.5 * psi), 0, 0, -sin(0.5 * psi));
+
+        line->setOrigin3D(origin);
+        line->setCoordTransformationTo(rotPsi * rotPhi * rotTheta);
+
+        line->setRelativeFlag(!itsAttr[X].defaultUsed() ||
+                              !itsAttr[Y].defaultUsed() ||
+                              !itsAttr[Z].defaultUsed() ||
+                              !itsAttr[THETA].defaultUsed() ||
+                              !itsAttr[PHI].defaultUsed() ||
+                              !itsAttr[PSI].defaultUsed());
+    }
 }
 
 
diff --git a/src/Main.cpp b/src/Main.cpp
index 4cbbe92a2d38e2d6216d11d513ba73585f8bd9f3..5753f11bd45c3672b90d2c49be2b6e593f93f0fe 100644
--- a/src/Main.cpp
+++ b/src/Main.cpp
@@ -40,7 +40,7 @@ Inform *gmsg;
 #include "Utilities/Options.h"
 #include "Utilities/OpalException.h"
 
-#include "config.h"
+#include "OPALconfig.h"
 
 #ifdef HAVE_AMR_SOLVER
 #include <ParallelDescriptor.H>
@@ -120,12 +120,12 @@ int main(int argc, char *argv[]) {
 
 
     *gmsg << endl
-          << "This is OPAL (Object Oriented Parallel Accelerator Library) Version " << PACKAGE_VERSION << "\n\n"
+          << "This is OPAL (Object Oriented Parallel Accelerator Library) Version " << PACKAGE_VERSION_STR << "\n\n"
           << "                (c) PSI, http://amas.web.psi.ch" << endl
           << endl;
 
 #ifdef OPAL_DKS
-    *gmsg << "OPAL compiled with DKS (Dynamic Kernel Scheduler) Version " 
+    *gmsg << "OPAL compiled with DKS (Dynamic Kernel Scheduler) Version "
 	  << DKS_VERSION << endl << endl;
 #endif
 
@@ -294,8 +294,8 @@ int main(int argc, char *argv[]) {
         return 0;
 
     } catch(ClassicException &ex) {
-      *gmsg << endl << "*** User error detected by function \""
-	    << ex.where() << "\"" << endl;
+      *gmsg << endl << "*** User error detected by function \"" << ex.where() << "\":\n"
+            << ex.what() << endl;
       abort();
 
     } catch(std::bad_alloc &) {
@@ -317,4 +317,4 @@ void errorHandlerGSL(const char *reason,
                      int,
                      int) {
     throw OpalException(file, reason);
-}
+}
\ No newline at end of file
diff --git a/src/Match/CMakeLists.txt b/src/Match/CMakeLists.txt
index 36b407d090fa460f0cc4b55870be5aa78be3e6bb..3b09310e602770a54376aa576af20cc556f10d0c 100644
--- a/src/Match/CMakeLists.txt
+++ b/src/Match/CMakeLists.txt
@@ -1,22 +1,43 @@
 set (_SRCS
-  AbstractFun.cpp
-  AbstractVar.cpp
-  ConcreteFun.cpp
-  ConcreteVar.cpp
-  ConstraintCmd.cpp
-  LMDif.cpp
-  Match.cpp
-  MatchCmd.cpp
-  MatchEnd.cpp
-  MatchOption.cpp
-  MatchParser.cpp
-  Migrad.cpp
-  Simplex.cpp
-  VaryCmd.cpp
-  )
+    AbstractFun.cpp
+    AbstractVar.cpp
+    ConcreteFun.cpp
+    ConcreteVar.cpp
+    ConstraintCmd.cpp
+    LMDif.cpp
+    Match.cpp
+    MatchCmd.cpp
+    MatchEnd.cpp
+    MatchOption.cpp
+    MatchParser.cpp
+    Migrad.cpp
+    Simplex.cpp
+    VaryCmd.cpp
+)
 
 include_directories (
   ${CMAKE_CURRENT_SOURCE_DIR}
 )
 
-add_sources(${_SRCS})
+add_opal_sources(${_SRCS})
+
+set (HDRS
+    AbstractFun.h
+    AbstractVar.h
+    ConcreteFun.h
+    ConcreteVar.h
+    ConstraintCmd.h
+    LMDif.h
+    MatchCmd.h
+    MatchEnd.h
+    Match.h
+    MatchLimits.h
+    MatchOption.h
+    MatchParser.h
+    MatchState.h
+    Migrad.h
+    Simplex.h
+    VaryCmd.h
+)
+
+install (FILES ${HDRS} DESTINATION "${CMAKE_INSTALL_PREFIX}/include/Match")
\ No newline at end of file
diff --git a/src/OpalConfigure/CMakeLists.txt b/src/OpalConfigure/CMakeLists.txt
index 59c45d5e71b183c88cd2a67ab0d8b132cdf53c04..90f0176a4ea7609ffff3f5a1a22b7d93e08998fe 100644
--- a/src/OpalConfigure/CMakeLists.txt
+++ b/src/OpalConfigure/CMakeLists.txt
@@ -6,4 +6,10 @@ include_directories (
   ${CMAKE_CURRENT_SOURCE_DIR}
 )
 
-add_sources(${_SRCS})
+add_opal_sources(${_SRCS})
+
+set (HDRS
+    Configure.h
+)
+
+install (FILES ${HDRS} DESTINATION "${CMAKE_INSTALL_PREFIX}/include/OpalConfigure")
\ No newline at end of file
diff --git a/src/OpalConfigure/Configure.cpp b/src/OpalConfigure/Configure.cpp
index a64f42853701d886a11a39a8dd5a419e9eed37aa..e27759d63f3ac88b03d5b84b82830f56a5a4ff0a 100644
--- a/src/OpalConfigure/Configure.cpp
+++ b/src/OpalConfigure/Configure.cpp
@@ -36,6 +36,7 @@
 #include "BasicActions/Quit.h"
 #include "BasicActions/What.h"
 #include "BasicActions/System.h"
+#include "BasicActions/PSystem.h"
 #include "BasicActions/Title.h"
 #include "BasicActions/Value.h"
 
@@ -111,6 +112,7 @@
 #include "Elements/OpalQuadrupole.h"
 #include "Elements/OpalPolynomialTimeDependence.h"
 #include "Elements/OpalRBend.h"
+#include "Elements/OpalRBend3D.h"
 #include "Elements/OpalRCollimator.h"
 #include "Elements/OpalSBend.h"
 #include "Elements/OpalSBend3D.h"
@@ -119,6 +121,7 @@
 #include "Elements/OpalSextupole.h"
 #include "Elements/OpalSlit.h"
 #include "Elements/OpalSolenoid.h"
+#include "Elements/OpalSource.h"
 #include "Elements/OpalSRot.h"
 #include "Elements/OpalTravelingWave.h"
 #include "Elements/OpalVKicker.h"
@@ -135,6 +138,7 @@
 #include "Lines/Line.h"
 #include "Lines/Sequence.h"
 
+#include "changes.h"
 
 // Namespace Configure
 // Modify these methods to add new commands.
@@ -146,7 +150,6 @@ namespace Configure {
         OpalData *opal = OpalData::getInstance();
         opal->create(new Call());
         opal->create(new Dump());
-        opal->create(new DumpFields());
         opal->create(new Echo());
         opal->create(new Dynamic());
         opal->create(new Eigen());
@@ -167,6 +170,7 @@ namespace Configure {
         opal->create(new Static());
         opal->create(new Stop());
         opal->create(new Quit());
+        opal->create(new PSystem());
         opal->create(new System());
         opal->create(new ThreadAll());
         opal->create(new ThreadBpm());
@@ -235,6 +239,7 @@ namespace Configure {
         opal->create(new OpalPolynomialTimeDependence());
         opal->create(new OpalQuadrupole());
         opal->create(new OpalRBend());
+        opal->create(new OpalRBend3D());
         opal->create(new OpalRCollimator());
         opal->create(new OpalSBend());
         opal->create(new OpalSBend3D());
@@ -243,6 +248,7 @@ namespace Configure {
         opal->create(new OpalSextupole());
         opal->create(new OpalSlit());
         opal->create(new OpalSolenoid());
+        opal->create(new OpalSource());
         opal->create(new OpalSRot());
         opal->create(new OpalTravelingWave());
         opal->create(new OpalVariableRFCavity());
@@ -263,5 +269,6 @@ namespace Configure {
         makeDefinitions();
         makeElements();
         makeActions();
+        Versions::fillChanges();
     }
-};
+};
\ No newline at end of file
diff --git a/src/OpalParser/CMakeLists.txt b/src/OpalParser/CMakeLists.txt
index 955f8d4135109586dbf52275ab11276690ae64f1..adc1a7e6bc10343d0df757af8af3facb3e588407 100644
--- a/src/OpalParser/CMakeLists.txt
+++ b/src/OpalParser/CMakeLists.txt
@@ -12,4 +12,16 @@ include_directories (
   ${CMAKE_CURRENT_SOURCE_DIR}
 )
 
-add_sources(${_SRCS})
+add_opal_sources(${_SRCS})
+
+set (HDRS
+    CompoundStatement.h
+    IfStatement.h
+    MacroCmd.h
+    Macro.h
+    MacroStream.h
+    OpalParser.h
+    WhileStatement.h
+)
+
+install (FILES ${HDRS} DESTINATION "${CMAKE_INSTALL_PREFIX}/include/OpalParser")
\ No newline at end of file
diff --git a/src/OpalParser/OpalParser.cpp b/src/OpalParser/OpalParser.cpp
index c3231a2aad67306c53bdd42fe10e07e3eed61c66..07ebc43a6041ee911a0e17a83066b1cf42c7f2e8 100644
--- a/src/OpalParser/OpalParser.cpp
+++ b/src/OpalParser/OpalParser.cpp
@@ -192,7 +192,6 @@ void OpalParser::parseAssign(Statement &stat) const {
     }
 
     std::string objName = parseString(stat, "Object name expected.");
-
     // Test for attribute name.
     Object *object = 0;
     std::string attrName;
@@ -541,12 +540,10 @@ Statement *OpalParser::readStatement(TokenStream *is) const {
                              "Command should begin with a <name>.");
         }
     } catch(ParseError &ex) {
-        *gmsg << "\n*** Parse error detected by function \""
-              << "OpalParser::readStatement()" << "\"\n";
-        stat->printWhere(true);
-        *gmsg << "    ";
-        stat->print();
-        *gmsg << "    " << ex.what() << '\n' << endl;
+        ERRORMSG("\n*** Parse error detected by function \""
+                 << "OpalParser::readStatement()" << "\"\n");
+        stat->printWhere(*IpplInfo::Error, true);
+        ERRORMSG("     " << *stat <<"    " << ex.what() << '\n' << endl);
         stat = readStatement(is);
 	exit(1);
     }
@@ -564,50 +561,38 @@ void OpalParser::run() const {
             // treatment of structured statements.
             stat->execute(*this);
         } catch(ParseError &ex) {
-            *gmsg << "\n*** Parse error detected by function \""
-                  << ex.where() << "\"\n";
-            stat->printWhere(true);
-            *gmsg << "    ";
-            stat->print();
-            *gmsg << "    " << ex.what() << '\n' << endl;
+            ERRORMSG("\n*** Parse error detected by function \""
+                     << ex.where() << "\"" << endl);
+            stat->printWhere(*IpplInfo::Error, true);
+            ERRORMSG("    " << *stat << "    " << ex.what() << '\n' << endl);
 	    exit(1);
         } catch(OpalException &ex) {
-            *gmsg << "\n*** User error detected by function \""
-                  << ex.where() << "\"\n";
-            stat->printWhere(true);
-            *gmsg << "    ";
-            stat->print();
-            *gmsg << "    " << ex.what() << '\n' << endl;
+            ERRORMSG("\n*** User error detected by function \""
+                     << ex.where() << "\"" << endl);
+            stat->printWhere(*IpplInfo::Error, true);
+            ERRORMSG("    " << *stat << "    " << ex.what() << '\n' << endl);
         } catch(ClassicException &ex) {
-            *gmsg << "\n*** User error detected by function \""
-                  << ex.where() << "\"\n";
-            stat->printWhere(false);
-            *gmsg << "    ";
-            stat->print();
-            *gmsg << "    " << ex.what() << '\n' << endl;
+            ERRORMSG("\n*** User error detected by function \""
+                     << ex.where() << "\"" << endl);
+            stat->printWhere(*IpplInfo::Error, false);
+            ERRORMSG(*stat << "    " << ex.what() << '\n' << endl);
         } catch(bad_alloc &) {
-            *gmsg << "\n*** Error:\n";
-            stat->printWhere(false);
-            *gmsg << "    ";
-            stat->print();
-            *gmsg << "    Sorry, virtual memory exhausted.\n" << endl;
+            ERRORMSG("\n*** Error:" << endl);
+            stat->printWhere(*IpplInfo::Error, false);
+            ERRORMSG("    " << *stat << "    Sorry, virtual memory exhausted.\n" << endl);
         } catch(assertion &ex) {
-            ERRORMSG("\n*** Runtime-error ******************\n");
+            ERRORMSG("\n*** Runtime-error ******************" << endl);
             ERRORMSG(ex.what());
             ERRORMSG("\n************************************\n" << endl);
             throw std::runtime_error("in Parser");
         } catch(exception &ex) {
-            *gmsg << "\n*** Error:\n";
-            stat->printWhere(false);
-            *gmsg << "    ";
-            stat->print();
-            *gmsg << "    Internal OPAL error: " << ex.what() << '\n' << endl;
+            ERRORMSG("\n*** Error:" << endl);
+            stat->printWhere(*IpplInfo::Error, false);
+            ERRORMSG("    " << *stat << "    Internal OPAL error: " << ex.what() << '\n' << endl);
         } catch(...) {
-            *gmsg << "\n*** Error:\n";
-            stat->printWhere(false);
-            *gmsg << "    ";
-            stat->print();
-            *gmsg << "    Unexpected exception caught.\n" << endl;
+            ERRORMSG("\n*** Error:\n");
+            stat->printWhere(*IpplInfo::Error, false);
+            ERRORMSG("    " << *stat << "    Unexpected exception caught.\n" << endl);
 	    throw std::runtime_error("in Parser");
         }
 
@@ -626,4 +611,4 @@ void OpalParser::run(TokenStream *is) const {
 
 void OpalParser::stop() const {
     stopFlag = true;
-}
+}
\ No newline at end of file
diff --git a/src/PhysicsActions/CMakeLists.txt b/src/PhysicsActions/CMakeLists.txt
index 7ec392a6e59abd874f6a61894752f4b09cc7f028..6e31d515d7bba17de83fae5f7fcc8b98aaa83698 100644
--- a/src/PhysicsActions/CMakeLists.txt
+++ b/src/PhysicsActions/CMakeLists.txt
@@ -9,4 +9,13 @@ include_directories (
   ${CMAKE_CURRENT_SOURCE_DIR}
 )
 
-add_sources(${_SRCS})
+add_opal_sources(${_SRCS})
+
+set (HDRS
+    Dynamic.h
+    MakeSequence.h
+    SetIntegrator.h
+    Static.h
+)
+
+install (FILES ${HDRS} DESTINATION "${CMAKE_INSTALL_PREFIX}/include/PhysicsActions")
\ No newline at end of file
diff --git a/src/Solvers/ArbitraryDomain.cpp b/src/Solvers/ArbitraryDomain.cpp
index 6c1a85394c7d70a8f15f29c03e2236714ad179c0..ca84626f41c994758ff56819232e96a2cb5fdffd 100644
--- a/src/Solvers/ArbitraryDomain.cpp
+++ b/src/Solvers/ArbitraryDomain.cpp
@@ -28,13 +28,13 @@
 ArbitraryDomain::ArbitraryDomain( BoundaryGeometry * bgeom,
    	                          Vector_t nr,
 	                          Vector_t hr,
-	                          std::string interpl){ 
+	                          std::string interpl){
     bgeom_m  = bgeom;
     minCoords_m = bgeom->getmincoords();
     maxCoords_m = bgeom->getmaxcoords();
     geomCentroid_m = (minCoords_m + maxCoords_m)/2.0;
-    
-    // TODO: THis needs to be made into OPTION of the geometry. 
+
+    // TODO: THis needs to be made into OPTION of the geometry.
     // A user defined point that is INSIDE with 100% certainty. -DW
     globalInsideP0_m = Vector_t(0.0, 0.0, -0.13);
 
@@ -57,8 +57,8 @@ ArbitraryDomain::~ArbitraryDomain() {
     //nothing so far
 }
 
-void ArbitraryDomain::Compute(Vector_t hr){
-    
+void ArbitraryDomain::compute(Vector_t hr){
+
     setHr(hr);
 
     globalMeanR_m = getGlobalMeanR();
@@ -186,7 +186,7 @@ void ArbitraryDomain::Compute(Vector_t hr){
      }
 }
 
-void ArbitraryDomain::Compute(Vector_t hr, NDIndex<3> localId){
+void ArbitraryDomain::compute(Vector_t hr, NDIndex<3> localId){
 
     INFOMSG(level2 << "* Starting the Boundary Intersection Tests..." << endl);
 
@@ -221,18 +221,18 @@ void ArbitraryDomain::Compute(Vector_t hr, NDIndex<3> localId){
     Vector_t P0 = globalInsideP0_m;
 
     // We cannot assume that the geometry is symmetric about the xy, xz, and yz planes!
-    // In my spiral inflector simulation, this is not the case for z direction for 
-    // example (-0.13 to +0.025). -DW   
+    // In my spiral inflector simulation, this is not the case for z direction for
+    // example (-0.13 to +0.025). -DW
     for (int idz = localId[2].first()-zGhostOffsetLeft; idz <= localId[2].last()+zGhostOffsetRight; idz++) {
 
 	 //saveP_old[2] = (idz - (nr[2]-1)/2.0)*hr[2];
 	 P[2] = minCoords_m[2] + (idz + 0.5) * hr[2];
- 
+
          for (int idy = localId[1].first()-yGhostOffsetLeft; idy <= localId[1].last()+yGhostOffsetRight; idy++) {
 
 	     //saveP_old[1] = (idy - (nr[1]-1)/2.0)*hr[1];
 	     P[1] = minCoords_m[1] + (idy + 0.5) * hr[1];
- 
+
    	     for (int idx = localId[0].first()-xGhostOffsetLeft; idx <= localId[0].last()+xGhostOffsetRight; idx++) {
 
 	          //saveP_old[0] = (idx - (nr[0]-1)/2.0)*hr[0];
@@ -260,7 +260,7 @@ void ArbitraryDomain::Compute(Vector_t hr, NDIndex<3> localId){
 		      P0 = P;
 
                       std::tuple<int, int, int> pos(idx, idy, idz);
-		     
+
 		      //rotateZAxisWithQuaternion(dir, localToGlobalQuaternion_m);
 		      dir = Vector_t(0, 0, 1);
 
@@ -310,7 +310,7 @@ void ArbitraryDomain::Compute(Vector_t hr, NDIndex<3> localId){
 			   *gmsg << "ydir=-1" << -dir << " x,y,z= " << idx << "," << idy << "," << idz << " P=" << P <<" I=" << I << endl;
 #endif
 		     }
-		     
+
 	             //rotateXAxisWithQuaternion(dir, localToGlobalQuaternion_m);
 		     dir = Vector_t(1, 0, 0);
 
@@ -409,7 +409,7 @@ inline int ArbitraryDomain::toCoordIdx(int idx, int idy, int idz) {
 
 // Conversion from (x,y,z) to index on the 3D grid
 int ArbitraryDomain::getIdx(int idx, int idy, int idz) {
-       
+
      if(isInside(idx, idy, idz) && idx >= 0 && idy >= 0 && idz >= 0)
          return IdxMap[toCoordIdx(idx, idy, idz)];
      else
@@ -427,7 +427,7 @@ inline void ArbitraryDomain::getCoord(int idxyz, int &idx, int &idy, int &idz) {
 }
 
 inline bool ArbitraryDomain::isInside(int idx, int idy, int idz) {
-  
+
     return IsInsideMap[toCoordIdx(idx, idy, idz)];
 }
 
@@ -436,9 +436,9 @@ inline bool ArbitraryDomain::isInside(int idx, int idy, int idz) {
     Vector_t P;
 
     P[0] = minCoords_m[0] + (idx + 0.5) * hr[0];
-    P[1] = minCoords_m[1] + (idy + 0.5) * hr[1]; 
+    P[1] = minCoords_m[1] + (idy + 0.5) * hr[1];
     P[2] = minCoords_m[2] + (idz + 0.5) * hr[2];
-    
+
     return (bgeom_m->fastIsInside(globalInsideP0_m, P) % 2 == 0);
 }
 */
@@ -505,10 +505,10 @@ void ArbitraryDomain::getBoundaryStencil(int idx, int idy, int idz, double &W, d
    // determine which interpolation method we use for points near the boundary
     switch(interpolationMethod){
     	case CONSTANT:
-        	ConstantInterpolation(idx,idy,idz,W,E,S,N,F,B,C,scaleFactor);
+        	constantInterpolation(idx,idy,idz,W,E,S,N,F,B,C,scaleFactor);
         	break;
     	case LINEAR:
-                LinearInterpolation(idx,idy,idz,W,E,S,N,F,B,C,scaleFactor);
+                linearInterpolation(idx,idy,idz,W,E,S,N,F,B,C,scaleFactor);
         	break;
     	case QUADRATIC:
             //  QuadraticInterpolation(idx,idy,idz,W,E,S,N,F,B,C,scaleFactor);
@@ -519,7 +519,7 @@ void ArbitraryDomain::getBoundaryStencil(int idx, int idy, int idz, double &W, d
     assert(C > 0);
 }
 
-void ArbitraryDomain::ConstantInterpolation(int idx, int idy, int idz, double& W, double& E, double& S, double& N, double& F, double& B, double& C, double &scaleFactor) {
+void ArbitraryDomain::constantInterpolation(int idx, int idy, int idz, double& W, double& E, double& S, double& N, double& F, double& B, double& C, double &scaleFactor) {
 
     W = -1/(hr[0]*hr[0]);
     E = -1/(hr[0]*hr[0]);
@@ -545,7 +545,7 @@ void ArbitraryDomain::ConstantInterpolation(int idx, int idy, int idz, double& W
 	B = 0.0;
 }
 
-void ArbitraryDomain::LinearInterpolation(int idx, int idy, int idz, double& W, double& E, double& S, double& N, double& F, double& B, double& C, double &scaleFactor)
+void ArbitraryDomain::linearInterpolation(int idx, int idy, int idz, double& W, double& E, double& S, double& N, double& F, double& B, double& C, double &scaleFactor)
 {
     scaleFactor = 1;
 
@@ -554,8 +554,8 @@ void ArbitraryDomain::LinearInterpolation(int idx, int idy, int idz, double& W,
     double cz = (idz - (nr[2]-1)/2.0)*hr[2];
 
     double dx_w=hr[0];
-    double dx_e=hr[0]; 
-    double dy_n=hr[1]; 
+    double dx_e=hr[0];
+    double dy_n=hr[1];
     double dy_s=hr[1];
     double dz_f=hr[2];
     double dz_b=hr[2];
@@ -729,4 +729,4 @@ inline void ArbitraryDomain::rotateZAxisWithQuaternion(Vector_t & v, Quaternion_
          + quaternion(3) * quaternion(3);
 
 }
-#endif //#ifdef HAVE_SAAMG_SOLVER
+#endif //#ifdef HAVE_SAAMG_SOLVER
\ No newline at end of file
diff --git a/src/Solvers/ArbitraryDomain.h b/src/Solvers/ArbitraryDomain.h
index c93f1d385c4be0cbf3ea4fdb9e6ec5cfdda9305c..b690931b2851477df96972eecc11062110738015 100644
--- a/src/Solvers/ArbitraryDomain.h
+++ b/src/Solvers/ArbitraryDomain.h
@@ -35,13 +35,13 @@ public:
     /// returns type of boundary condition
     std::string getType() {return "Geometric";}
     /// queries if a given (x,y,z) coordinate lies inside the domain
-    inline bool isInside(int idx, int idy, int idz);
+    bool isInside(int idx, int idy, int idz);
     /// returns number of nodes in xy plane
     int getNumXY(int idz);
-    // calculates intersection  
-    void Compute(Vector_t hr);
-    // calculates intersection with rotated and shifted geometry 
-    void Compute(Vector_t hr, NDIndex<3> localId);
+    // calculates intersection
+    void compute(Vector_t hr);
+    // calculates intersection with rotated and shifted geometry
+    void compute(Vector_t hr, NDIndex<3> localId);
 
     int getStartId() {return startId;}
 
@@ -78,8 +78,8 @@ private:
 
     /// all intersection points with gridlines in Z direction
     PointList IntersectHiZ, IntersectLoZ;
-    
-    // meanR to shift from global to local frame 
+
+    // meanR to shift from global to local frame
     Vector_t globalMeanR_m;
     Quaternion_t globalToLocalQuaternion_m;
     Quaternion_t localToGlobalQuaternion_m;
@@ -103,7 +103,7 @@ private:
 
     // Interpolation type
     int interpolationMethod;
- 
+
     // Flag indicating if geometry has changed for the current time-step
     bool hasGeometryChanged_m;
 
@@ -125,17 +125,17 @@ private:
     inline double dotProduct(double v1[], double v2[]) { return (v1[0] * v2[0] + v1[1] * v2[1] + v1[2] * v2[2]); }
 
     // Different interpolation methods for boundary points
-    void ConstantInterpolation(int idx, int idy, int idz, double &W, double &E, double &S, double &N, double &F, double &B, double &C, double &scaleFactor);
-    void LinearInterpolation(int idx, int idy, int idz, double &W, double &E, double &S, double &N, double &F, double &B, double &C, double &scaleFactor);
-    void QuadraticInterpolation(int idx, int idy, int idz, double &W, double &E, double &S, double &N, double &F, double &B, double &C, double &scaleFactor);
+    void constantInterpolation(int idx, int idy, int idz, double &W, double &E, double &S, double &N, double &F, double &B, double &C, double &scaleFactor);
+    void linearInterpolation(int idx, int idy, int idz, double &W, double &E, double &S, double &N, double &F, double &B, double &C, double &scaleFactor);
+    void quadraticInterpolation(int idx, int idy, int idz, double &W, double &E, double &S, double &N, double &F, double &B, double &C, double &scaleFactor);
 
     // Rotate positive axes with quaternion -DW
     inline void rotateWithQuaternion(Vector_t &v, Quaternion_t const quaternion);
- 	
+
     inline void rotateXAxisWithQuaternion(Vector_t &v, Quaternion_t const quaternion);
     inline void rotateYAxisWithQuaternion(Vector_t &v, Quaternion_t const quaternion);
     inline void rotateZAxisWithQuaternion(Vector_t &v, Quaternion_t const quaternion);
 };
 
 #endif //#ifdef HAVE_SAAMG_SOLVER
-#endif //#ifdef ARBITRARY_DOMAIN
+#endif //#ifdef ARBITRARY_DOMAIN
\ No newline at end of file
diff --git a/src/Solvers/BoxCornerDomain.cpp b/src/Solvers/BoxCornerDomain.cpp
index 6fe23e4d24abbccbced0ef11591f2d587763cacf..51017c1940df6a52657c9e612e39a60b668a29e3 100644
--- a/src/Solvers/BoxCornerDomain.cpp
+++ b/src/Solvers/BoxCornerDomain.cpp
@@ -27,11 +27,11 @@ BoxCornerDomain::BoxCornerDomain(double A, double B, double C, double Length, do
     setNr(nr);
     setHr(hr);
 
-    if(interpl == "constant")
+    if(interpl == "CONSTANT")
         interpolationMethod = CONSTANT;
-    else if(interpl == "linear")
+    else if(interpl == "LINEAR")
         interpolationMethod = LINEAR;
-    else if(interpl == "quadratic")
+    else if(interpl == "QUADRATIC")
         interpolationMethod = QUADRATIC;
 
     if(Ippl::getNodes() == 1) {
@@ -55,7 +55,7 @@ BoxCornerDomain::~BoxCornerDomain() {
 // for the moment we center the box corner geometry around the center of the grid
 // hr holds the grid-spacings (boundary ellipse embedded in hr-grid)
 
-void BoxCornerDomain::Compute(Vector_t hr){
+void BoxCornerDomain::compute(Vector_t hr){
 
     //there is nothing to be done if the mesh spacings have not changed
     //    if(hr[0] == getHr()[0] && hr[1] == getHr()[1] && hr[2] == getHr()[2]) {
@@ -130,7 +130,7 @@ void BoxCornerDomain::Compute(Vector_t hr){
     */
 }
 
-void BoxCornerDomain::Compute(Vector_t hr, NDIndex<3> localId){
+void BoxCornerDomain::compute(Vector_t hr, NDIndex<3> localId){
 }
 
 void BoxCornerDomain::getBoundaryStencil(int x, int y, int z, double &W, double &E, double &S, double &N, double &F, double &B, double &C, double &scaleFactor) {
@@ -138,13 +138,13 @@ void BoxCornerDomain::getBoundaryStencil(int x, int y, int z, double &W, double
     // determine which interpolation method we use for points near the boundary
     switch(interpolationMethod) {
         case CONSTANT:
-            ConstantInterpolation(x, y, z, W, E, S, N, F, B, C, scaleFactor);
+            constantInterpolation(x, y, z, W, E, S, N, F, B, C, scaleFactor);
             break;
         case LINEAR:
-            LinearInterpolation(x, y, z, W, E, S, N, F, B, C, scaleFactor);
+            linearInterpolation(x, y, z, W, E, S, N, F, B, C, scaleFactor);
             break;
         case QUADRATIC:
-            QuadraticInterpolation(x, y, z, W, E, S, N, F, B, C, scaleFactor);
+            quadraticInterpolation(x, y, z, W, E, S, N, F, B, C, scaleFactor);
             break;
     }
 
@@ -200,7 +200,7 @@ void BoxCornerDomain::getNeighbours(int x, int y, int z, int &W, int &E, int &S,
 
 }
 
-void BoxCornerDomain::ConstantInterpolation(int x, int y, int z, double &W, double &E, double &S, double &N, double &F, double &B, double &C, double &scaleFactor) {
+void BoxCornerDomain::constantInterpolation(int x, int y, int z, double &W, double &E, double &S, double &N, double &F, double &B, double &C, double &scaleFactor) {
 
     scaleFactor = 1.0;
 
@@ -260,7 +260,7 @@ void BoxCornerDomain::ConstantInterpolation(int x, int y, int z, double &W, doub
 
 }
 
-void BoxCornerDomain::LinearInterpolation(int x, int y, int z, double &W, double &E, double &S, double &N, double &F, double &B, double &C, double &scaleFactor) {
+void BoxCornerDomain::linearInterpolation(int x, int y, int z, double &W, double &E, double &S, double &N, double &F, double &B, double &C, double &scaleFactor) {
 
     scaleFactor = 1.0;
 
@@ -363,7 +363,7 @@ void BoxCornerDomain::LinearInterpolation(int x, int y, int z, double &W, double
 }
 
 //FIXME: this probably needs some cleanup/rewriting
-void BoxCornerDomain::QuadraticInterpolation(int x, int y, int z, double &W, double &E, double &S, double &N, double &F, double &B, double &C, double &scaleFactor) {
+void BoxCornerDomain::quadraticInterpolation(int x, int y, int z, double &W, double &E, double &S, double &N, double &F, double &B, double &C, double &scaleFactor) {
 
     double cx = (x - (nr[0] - 1) / 2.0) * hr[0];
     double cy = (y - (nr[1] - 1) / 2.0) * hr[1];
diff --git a/src/Solvers/BoxCornerDomain.h b/src/Solvers/BoxCornerDomain.h
index 87877ed957113f9788ef1f3b4e95196b1f819dc2..b5c15b99e61ae89fb5ad2876fc5e89ce82e8d5bf 100644
--- a/src/Solvers/BoxCornerDomain.h
+++ b/src/Solvers/BoxCornerDomain.h
@@ -99,8 +99,8 @@ public:
     /// set semi-major
     //void setSemiMajor(double sm) {SemiMajor = sm;}
 
-    void Compute(Vector_t hr);
-    void Compute(Vector_t hr, NDIndex<3> localId);
+    void compute(Vector_t hr);
+    void compute(Vector_t hr, NDIndex<3> localId);
 
     double getXRangeMin() { return -A_m; }
     double getXRangeMax() { return  A_m; }
@@ -219,9 +219,9 @@ private:
     }
 
     /// different interpolation methods for boundary points
-    void ConstantInterpolation(int x, int y, int z, double &W, double &E, double &S, double &N, double &F, double &B, double &C, double &scaleFactor);
-    void LinearInterpolation(int x, int y, int z, double &W, double &E, double &S, double &N, double &F, double &B, double &C, double &scaleFactor);
-    void QuadraticInterpolation(int x, int y, int z, double &W, double &E, double &S, double &N, double &F, double &B, double &C, double &scaleFactor);
+    void constantInterpolation(int x, int y, int z, double &W, double &E, double &S, double &N, double &F, double &B, double &C, double &scaleFactor);
+    void linearInterpolation(int x, int y, int z, double &W, double &E, double &S, double &N, double &F, double &B, double &C, double &scaleFactor);
+    void quadraticInterpolation(int x, int y, int z, double &W, double &E, double &S, double &N, double &F, double &B, double &C, double &scaleFactor);
 
 };
 
diff --git a/src/Solvers/CMakeLists.txt b/src/Solvers/CMakeLists.txt
index 518ccb73d1b3206d2978e1787901fdfd98b0cd98..e071f64e35e5e24de9be196e3ae8c65049e71b6f 100644
--- a/src/Solvers/CMakeLists.txt
+++ b/src/Solvers/CMakeLists.txt
@@ -14,4 +14,20 @@ include_directories (
   ${CMAKE_CURRENT_SOURCE_DIR}
 )
 
-add_sources(${_SRCS})
+add_opal_sources(${_SRCS})
+
+set (HDRS
+    ArbitraryDomain.h
+    BoxCornerDomain.h
+    EllipticDomain.h
+    FFTBoxPoissonSolver.h
+    FFTPoissonSolver.h
+    IrregularDomain.h
+    MGPoissonSolver.h
+    P3MPoissonSolver.h
+    PoissonSolver.h
+    RectangularDomain.h
+    TaperDomain.h
+)
+
+install (FILES ${HDRS} DESTINATION "${CMAKE_INSTALL_PREFIX}/include/Solvers")
\ No newline at end of file
diff --git a/src/Solvers/EllipticDomain.cpp b/src/Solvers/EllipticDomain.cpp
index 8e68d4487bd8312e31e057566725a0c73bf42f7b..06fc2b5d55188af719988077a2f569b7843b0631 100644
--- a/src/Solvers/EllipticDomain.cpp
+++ b/src/Solvers/EllipticDomain.cpp
@@ -70,7 +70,7 @@ EllipticDomain::~EllipticDomain() {
 // for this geometry we only have to calculate the intersection on
 // one x-y-plane
 // for the moment we center the ellipse around the center of the grid
-void EllipticDomain::Compute(Vector_t hr){
+void EllipticDomain::compute(Vector_t hr){
     //there is nothing to be done if the mesh spacings have not changed
     if(hr[0] == getHr()[0] && hr[1] == getHr()[1] && hr[2] == getHr()[2]) {
         hasGeometryChanged_m = false;
@@ -147,7 +147,7 @@ void EllipticDomain::Compute(Vector_t hr){
     }
 }
 
-void EllipticDomain::Compute(Vector_t hr, NDIndex<3> localId){
+void EllipticDomain::compute(Vector_t hr, NDIndex<3> localId){
     //there is nothing to be done if the mesh spacings have not changed
     if(hr[0] == getHr()[0] && hr[1] == getHr()[1] && hr[2] == getHr()[2]) {
         hasGeometryChanged_m = false;
@@ -229,13 +229,13 @@ void EllipticDomain::getBoundaryStencil(int x, int y, int z, double &W, double &
         // determine which interpolation method we use for points near the boundary
     switch(interpolationMethod) {
         case CONSTANT:
-            ConstantInterpolation(x, y, z, W, E, S, N, F, B, C, scaleFactor);
+            constantInterpolation(x, y, z, W, E, S, N, F, B, C, scaleFactor);
             break;
         case LINEAR:
-            LinearInterpolation(x, y, z, W, E, S, N, F, B, C, scaleFactor);
+            linearInterpolation(x, y, z, W, E, S, N, F, B, C, scaleFactor);
             break;
         case QUADRATIC:
-            QuadraticInterpolation(x, y, z, W, E, S, N, F, B, C, scaleFactor);
+            quadraticInterpolation(x, y, z, W, E, S, N, F, B, C, scaleFactor);
             break;
     }
 
@@ -291,7 +291,7 @@ void EllipticDomain::getNeighbours(int x, int y, int z, int &W, int &E, int &S,
 
 }
 
-void EllipticDomain::ConstantInterpolation(int x, int y, int z, double &WV, double &EV, double &SV, double &NV, double &FV, double &BV, double &CV, double &scaleFactor) {
+void EllipticDomain::constantInterpolation(int x, int y, int z, double &WV, double &EV, double &SV, double &NV, double &FV, double &BV, double &CV, double &scaleFactor) {
 
     scaleFactor = 1.0;
 
@@ -351,7 +351,7 @@ void EllipticDomain::ConstantInterpolation(int x, int y, int z, double &WV, doub
 
 }
 
-void EllipticDomain::LinearInterpolation(int x, int y, int z, double &W, double &E, double &S, double &N, double &F, double &B, double &C, double &scaleFactor) {
+void EllipticDomain::linearInterpolation(int x, int y, int z, double &W, double &E, double &S, double &N, double &F, double &B, double &C, double &scaleFactor) {
 
     scaleFactor = 1.0;
 
@@ -443,7 +443,7 @@ void EllipticDomain::LinearInterpolation(int x, int y, int z, double &W, double
 */
 }
 
-void EllipticDomain::QuadraticInterpolation(int x, int y, int z, double &W, double &E, double &S, double &N, double &F, double &B, double &C, double &scaleFactor) {
+void EllipticDomain::quadraticInterpolation(int x, int y, int z, double &W, double &E, double &S, double &N, double &F, double &B, double &C, double &scaleFactor) {
 
     double cx = (x - (nr[0] - 1) / 2.0) * hr[0];
     double cy = (y - (nr[1] - 1) / 2.0) * hr[1];
diff --git a/src/Solvers/EllipticDomain.h b/src/Solvers/EllipticDomain.h
index 703436047ad354d2741614d12267c1d712f9228d..97386c5772ca67c71929302336caebee3e759640 100644
--- a/src/Solvers/EllipticDomain.h
+++ b/src/Solvers/EllipticDomain.h
@@ -44,8 +44,8 @@ public:
     void setSemiMajor(double sm) {SemiMajor = sm;}
 
     /// calculates intersection 
-    void Compute(Vector_t hr);
-    void Compute(Vector_t hr, NDIndex<3> localId);
+    void compute(Vector_t hr);
+    void compute(Vector_t hr, NDIndex<3> localId);
 
     double getXRangeMin() { return -SemiMajor; }
     double getXRangeMax() { return SemiMajor;  }
@@ -109,9 +109,9 @@ private:
     }
 
     /// different interpolation methods for boundary points
-    void ConstantInterpolation(int x, int y, int z, double &W, double &E, double &S, double &N, double &F, double &B, double &C, double &scaleFactor);
-    void LinearInterpolation(int x, int y, int z, double &W, double &E, double &S, double &N, double &F, double &B, double &C, double &scaleFactor);
-    void QuadraticInterpolation(int x, int y, int z, double &W, double &E, double &S, double &N, double &F, double &B, double &C, double &scaleFactor);
+    void constantInterpolation(int x, int y, int z, double &W, double &E, double &S, double &N, double &F, double &B, double &C, double &scaleFactor);
+    void linearInterpolation(int x, int y, int z, double &W, double &E, double &S, double &N, double &F, double &B, double &C, double &scaleFactor);
+    void quadraticInterpolation(int x, int y, int z, double &W, double &E, double &S, double &N, double &F, double &B, double &C, double &scaleFactor);
 
 };
 
diff --git a/src/Solvers/FFTBoxPoissonSolver.cpp b/src/Solvers/FFTBoxPoissonSolver.cpp
index 2af66e9c1189aab596aeb25a16d55a38f3732d4f..8085bfb8236219bbbb76a5cf4b5865588b2feda2 100644
--- a/src/Solvers/FFTBoxPoissonSolver.cpp
+++ b/src/Solvers/FFTBoxPoissonSolver.cpp
@@ -12,6 +12,7 @@
 
 #include "Algorithms/PartBunch.h"
 #include "Physics/Physics.h"
+#include "Utility/IpplTimings.h"
 #include <fstream>
 //////////////////////////////////////////////////////////////////////////////
 // a little helper class to specialize the action of the Green's function
diff --git a/src/Solvers/FFTPoissonSolver.cpp b/src/Solvers/FFTPoissonSolver.cpp
index 82195df9afe422ca5142452634872a600b57d610..293868e5bb2b3d960dfa4a1ac0879f70cbc7153d 100644
--- a/src/Solvers/FFTPoissonSolver.cpp
+++ b/src/Solvers/FFTPoissonSolver.cpp
@@ -16,11 +16,10 @@
 #include "Solvers/FFTPoissonSolver.h"
 #include "Algorithms/PartBunch.h"
 #include "Physics/Physics.h"
-#include <fstream>
-
+#include "Utility/IpplTimings.h"
 #include "BasicActions/Option.h"
 #include "Utilities/Options.h"
-#include "Utilities/Options.h"
+#include <fstream>
 //////////////////////////////////////////////////////////////////////////////
 // a little helper class to specialize the action of the Green's function
 // calculation.  This should be specialized for each dimension
@@ -181,7 +180,7 @@ FFTPoissonSolver::FFTPoissonSolver(Mesh_t *mesh, FieldLayout_t *fl, std::string
     }
 
     GreensFunctionTimer_m = IpplTimings::getTimer("SF: GreensFTotal");
-    
+
     if(greensFunction_m == std::string("INTEGRATED")) {
         IntGreensFunctionTimer1_m = IpplTimings::getTimer("SF: IntGreenF1");
         IntGreensFunctionTimer2_m = IpplTimings::getTimer("SF: IntGreenF2");
@@ -199,7 +198,7 @@ FFTPoissonSolver::FFTPoissonSolver(Mesh_t *mesh, FieldLayout_t *fl, std::string
     }
 
     ComputePotential_m = IpplTimings::getTimer("ComputePotential");
-  
+
 #ifdef OPAL_DKS
 
     if (IpplInfo::DKSEnabled) {
@@ -210,21 +209,21 @@ FFTPoissonSolver::FFTPoissonSolver(Mesh_t *mesh, FieldLayout_t *fl, std::string
       dksbase.initDevice();
 
       if (Ippl::myNode() == 0) {
-	
+
 	//create stream for greens function
 	dksbase.createStream(streamGreens);
 	dksbase.createStream(streamFFT);
 
 	//create fft plans for multiple reuse
 	int dimsize[3] = {2*nr_m[0], 2*nr_m[1], 2*nr_m[2]};
-      
+
 	dksbase.setupFFT(3, dimsize);
-   
+
 	//allocate memory
 	int sizegreen = tmpgreen.getLayout().getDomain().size();
 	int sizerho2_m = rho2_m.getLayout().getDomain().size();
 	int sizecomp = grntr_m.getLayout().getDomain().size();
-	
+
 	tmpgreen_ptr = dksbase.allocateMemory<double>(sizegreen, dkserr);
 	rho2_m_ptr = dksbase.allocateMemory<double>(sizerho2_m, dkserr);
 	rho2real_m_ptr = dksbase.allocateMemory<double>(sizerho2_m, dkserr);
@@ -240,11 +239,11 @@ FFTPoissonSolver::FFTPoissonSolver(Mesh_t *mesh, FieldLayout_t *fl, std::string
       } else {
 	//create stream for FFT data transfer
 	dksbase.createStream(streamFFT);
-	//receive pointer 
+	//receive pointer
 	rho2real_m_ptr = dksbase.receivePointer(0, Ippl::getComm(), dkserr);
       }
     }
-    
+
 #endif
 
 }
@@ -355,25 +354,25 @@ FFTPoissonSolver::FFTPoissonSolver(PartBunch &beam, std::string greensFunction):
       dksbase.initDevice();
 
       if (Ippl::myNode() == 0) {
-	
+
 	//create stream for greens function
 	dksbase.createStream(streamGreens);
 	dksbase.createStream(streamFFT);
-	
+
 	//create fft plans for multiple reuse
 	int dimsize[3] = {2*nr_m[0], 2*nr_m[1], 2*nr_m[2]};
-      
+
 	dksbase.setupFFT(3, dimsize);
-   
+
 	//allocate memory
 	int sizegreen = tmpgreen.getLayout().getDomain().size();
 	int sizerho2_m = rho2_m.getLayout().getDomain().size();
 	int sizecomp = grntr_m.getLayout().getDomain().size();
-	
+
 	tmpgreen_ptr = dksbase.allocateMemory<double>(sizegreen, dkserr);
 	rho2_m_ptr = dksbase.allocateMemory<double>(sizerho2_m, dkserr);
 	rho2real_m_ptr = dksbase.allocateMemory<double>(sizerho2_m, dkserr);
-	
+
 	grntr_m_ptr = dksbase.allocateMemory< std::complex<double>  >(sizecomp, dkserr);
 	rho2tr_m_ptr = dksbase.allocateMemory< std::complex<double> > (sizecomp, dkserr);
 
@@ -385,7 +384,7 @@ FFTPoissonSolver::FFTPoissonSolver(PartBunch &beam, std::string greensFunction):
       } else {
 	//create stream for FFT data transfer
 	dksbase.createStream(streamFFT);
-	//receive pointer 
+	//receive pointer
 	rho2real_m_ptr = dksbase.receivePointer(0, Ippl::getComm(), dkserr);
       }
     }
@@ -413,12 +412,12 @@ FFTPoissonSolver::~FFTPoissonSolver() {
       int sizegreen = tmpgreen.getLayout().getDomain().size();
       int sizerho2_m = rho2_m.getLayout().getDomain().size();
       int sizecomp = grntr_m.getLayout().getDomain().size();
-      
+
       //free memory
       dksbase.freeMemory<double>(tmpgreen_ptr, sizegreen);
       dksbase.freeMemory<double>(rho2_m_ptr, sizerho2_m);
       dksbase.freeMemory< std::complex<double> >(grntr_m_ptr, sizecomp);
-      
+
       //wait for other processes to close handle to rho2real_m_ptr before freeing memory
       MPI_Barrier(Ippl::getComm());
       dksbase.freeMemory<double>(rho2real_m_ptr, sizerho2_m);
@@ -437,7 +436,7 @@ FFTPoissonSolver::~FFTPoissonSolver() {
 // the Poisson's equation
 
 void FFTPoissonSolver::computePotential(Field_t &rho, Vector_t hr, double zshift) {
-  
+
     // use grid of complex doubled in both dimensions
     // and store rho in lower left quadrant of doubled grid
     rho2_m = 0.0;
@@ -508,9 +507,9 @@ void FFTPoissonSolver::computePotential(Field_t &rho, Vector_t hr) {
       // and rescale later
       IpplTimings::startTimer(GreensFunctionTimer_m);
       if(greensFunction_m == std::string("INTEGRATED"))
-        integratedGreensFunction();
+          integratedGreensFunction();
       else
-        greensFunction();
+          greensFunction();
       IpplTimings::stopTimer(GreensFunctionTimer_m);
       // multiply transformed charge density
       // and transformed Green function
@@ -523,43 +522,42 @@ void FFTPoissonSolver::computePotential(Field_t &rho, Vector_t hr) {
       // end convolution
     } else {
 #ifdef OPAL_DKS
-      dksbase.syncDevice();
-      MPI_Barrier(Ippl::getComm());
+        dksbase.syncDevice();
+        MPI_Barrier(Ippl::getComm());
+
+        if (Ippl::myNode() == 0) {
+            IpplTimings::startTimer(GreensFunctionTimer_m);
+            integratedGreensFunction();
+            IpplTimings::stopTimer(GreensFunctionTimer_m);
+            //transform the greens function
+            int dimsize[3] = {2*nr_m[0], 2*nr_m[1], 2*nr_m[2]};
+            dksbase.callR2CFFT(rho2_m_ptr, grntr_m_ptr, 3, dimsize, streamGreens);
+        }
+        MPI_Barrier(Ippl::getComm());
 
-      if (Ippl::myNode() == 0) {
-	IpplTimings::startTimer(GreensFunctionTimer_m);
-	integratedGreensFunctionDKS();
-	IpplTimings::stopTimer(GreensFunctionTimer_m);
-	//transform the greens function
-	int dimsize[3] = {2*nr_m[0], 2*nr_m[1], 2*nr_m[2]}; 
-	dksbase.callR2CFFT(rho2_m_ptr, grntr_m_ptr, 3, dimsize, streamGreens);
-      }  
-      MPI_Barrier(Ippl::getComm());
+        //transform rho2_m keep pointer to GPU memory where results are stored in rho2tr_m_ptr
+        fft_m->transformDKSRC(-1, rho2_m, rho2real_m_ptr, rho2tr_m_ptr, dksbase, streamFFT, false);
 
-      //transform rho2_m keep pointer to GPU memory where results are stored in rho2tr_m_ptr  
-      fft_m->transformDKSRC(-1, rho2_m, rho2real_m_ptr, rho2tr_m_ptr, dksbase, streamFFT, false);
-      
-      if (Ippl::myNode() == 0) {
-	//transform the greens function
-	//int dimsize[3] = {2*nr_m[0], 2*nr_m[1], 2*nr_m[2]}; 
-	//dksbase.callR2CFFT(rho2_m_ptr, grntr_m_ptr, 3, dimsize, streamGreens);
-      
-	//multiply fields and free unneeded memory
-	int sizecomp = grntr_m.getLayout().getDomain().size();
-	dksbase.syncDevice();
-	dksbase.callMultiplyComplexFields(rho2tr_m_ptr, grntr_m_ptr, sizecomp);
-      }
-   
-      MPI_Barrier(Ippl::getComm());
-  
-      //inverse FFT and transfer result back to rho2_m
-      fft_m->transformDKSCR(+1, rho2_m, rho2real_m_ptr, rho2tr_m_ptr, dksbase);
+        if (Ippl::myNode() == 0) {
+            //transform the greens function
+            //int dimsize[3] = {2*nr_m[0], 2*nr_m[1], 2*nr_m[2]};
+            //dksbase.callR2CFFT(rho2_m_ptr, grntr_m_ptr, 3, dimsize, streamGreens);
 
-      MPI_Barrier(Ippl::getComm());
+            //multiply fields and free unneeded memory
+            int sizecomp = grntr_m.getLayout().getDomain().size();
+            dksbase.syncDevice();
+            dksbase.callMultiplyComplexFields(rho2tr_m_ptr, grntr_m_ptr, sizecomp);
+        }
+
+        MPI_Barrier(Ippl::getComm());
+
+        //inverse FFT and transfer result back to rho2_m
+        fft_m->transformDKSCR(+1, rho2_m, rho2real_m_ptr, rho2tr_m_ptr, dksbase);
+
+        MPI_Barrier(Ippl::getComm());
 #endif
     }
 
-
     // back to physical grid
     // reuse the charge density field to store the electrostatic potential
     rho[domain_m] = rho2_m[domain_m];
@@ -623,7 +621,7 @@ void FFTPoissonSolver::greensFunction() {
  */
 void FFTPoissonSolver::integratedGreensFunction() {
 
-    
+
 
     IpplTimings::startTimer(IntGreensFunctionTimer1_m);
 
@@ -658,7 +656,7 @@ void FFTPoissonSolver::integratedGreensFunction() {
             }
         }
     }
-    
+
     IpplTimings::stopTimer(IntGreensFunctionTimer1_m);
 
     IpplTimings::startTimer(IntGreensFunctionTimer2_m);
@@ -706,7 +704,7 @@ void FFTPoissonSolver::integratedGreensFunctionDKS() {
   NDIndex<3> idx =  layout4_m->getDomain();
   dksbase.callGreensIntegral(tmpgreen_ptr, idx[0].length(), idx[1].length(), idx[2].length(),
 			     nr_m[0]+1, nr_m[1]+1, hr_m[0], hr_m[1], hr_m[2], streamGreens);
-  
+
   IpplTimings::stopTimer(IntGreensFunctionTimer1_m);
 
   IpplTimings::startTimer(IntGreensFunctionTimer2_m);
@@ -714,8 +712,8 @@ void FFTPoissonSolver::integratedGreensFunctionDKS() {
   Index I = nr_m[0] + 1;
   Index J = nr_m[1] + 1;
   Index K = nr_m[2] + 1;
-    
-  dksbase.callGreensIntegration(rho2_m_ptr, tmpgreen_ptr, nr_m[0]+1, nr_m[1]+1, nr_m[2]+1, 
+
+  dksbase.callGreensIntegration(rho2_m_ptr, tmpgreen_ptr, nr_m[0]+1, nr_m[1]+1, nr_m[2]+1,
 				streamGreens);
 
   IpplTimings::stopTimer(IntGreensFunctionTimer2_m);
@@ -890,4 +888,4 @@ Inform &FFTPoissonSolver::print(Inform &os) const {
 /***************************************************************************
  * $RCSfile: FFTPoissonSolver.cc,v $   $Author: adelmann $
  * $Revision: 1.6 $   $Date: 2001/08/16 09:36:08 $
- ***************************************************************************/
+ ***************************************************************************/
\ No newline at end of file
diff --git a/src/Solvers/IrregularDomain.h b/src/Solvers/IrregularDomain.h
index 25044a9163edfb0b10a16e0b174e5525b4244d2f..ba98d61f27e1a4e4a6b684c74a22da7e997c00e5 100644
--- a/src/Solvers/IrregularDomain.h
+++ b/src/Solvers/IrregularDomain.h
@@ -5,6 +5,8 @@
 #include <vector>
 #include <string>
 #include "Algorithms/PBunchDefs.h"
+#include "Algorithms/Quaternion.h"
+
 #define TK_PRINT(...) do{printf("TK:%s:%d:",__FILE__,__LINE__);printf(__VA_ARGS__);fflush(stdout);}while(0)
 
 /// enumeration corresponding to different interpolation methods at the boundary
@@ -22,8 +24,8 @@ public:
     /** method to compute the intersection points with the boundary geometry (stored in some appropriate data structure)
      * \param hr updated mesh spacings
      */
-    virtual void Compute(Vector_t hr) = 0;
-    virtual void Compute(Vector_t hr, NDIndex<3> localId) = 0;
+    virtual void compute(Vector_t hr) = 0;
+    virtual void compute(Vector_t hr, NDIndex<3> localId) = 0;
     /** method to get the number of gridpoints in a given z plane
      * \param z coordinate of the z plane
      * \return int number of grid nodes in the given z plane
@@ -122,4 +124,4 @@ protected:
 };
 
 #endif //#ifdef HAVE_SAAMG_SOLVER
-#endif //#ifndef IRREGULAR_DOMAIN_H
+#endif //#ifndef IRREGULAR_DOMAIN_H
\ No newline at end of file
diff --git a/src/Solvers/MGPoissonSolver.cpp b/src/Solvers/MGPoissonSolver.cpp
index c2c28de4f5e5f521c02ffe505c27d4c65bc4281f..efd67ee51a3155655a417d9a46c86481c16091a5 100644
--- a/src/Solvers/MGPoissonSolver.cpp
+++ b/src/Solvers/MGPoissonSolver.cpp
@@ -80,7 +80,7 @@ MGPoissonSolver::MGPoissonSolver ( PartBunch &beam,
     }
 
     if(itsolver == "CG") itsolver_m = AZ_cg;
-    else if(itsolver == "BiCGStab") itsolver_m = AZ_bicgstab;
+    else if(itsolver == "BICGSTAB") itsolver_m = AZ_bicgstab;
     else if(itsolver == "GMRES") itsolver_m = AZ_gmres;
     else throw OpalException("MGPoissonSolver", "No valid iterative solver selected!");
 
@@ -95,7 +95,7 @@ MGPoissonSolver::MGPoissonSolver ( PartBunch &beam,
     forcePreconditionerRecomputation_m = false;
 
     hasParallelDecompositionChanged_m = true;
-    repartFreq_m = 1000; 
+    repartFreq_m = 1000;
     useRCB_m = false;
     if(Ippl::Info->getOutputLevel() > 1)
         verbose_m = true;
@@ -109,12 +109,12 @@ MGPoissonSolver::MGPoissonSolver ( PartBunch &beam,
             bp = new EllipticDomain(currentGeometry, orig_nr_m, hr_m, interpl);
 	} else if (currentGeometry->getTopology() == "BOXCORNER") {
             bp = new BoxCornerDomain(currentGeometry->getA(), currentGeometry->getB(), currentGeometry->getC(), currentGeometry->getLength(),currentGeometry->getL1(), currentGeometry->getL2(), orig_nr_m, hr_m, interpl);
-            bp->Compute(itsBunch_m->get_hr());
+            bp->compute(itsBunch_m->get_hr());
         } else {
             throw OpalException("MGPoissonSolver::MGPoissonSolver",
                                 "Geometry not known");
         }
-    } else 
+    } else
 	bp = new ArbitraryDomain(currentGeometry, orig_nr_m, hr_m, interpl);
 
     Map = 0;
@@ -183,7 +183,7 @@ void MGPoissonSolver::computePotential(Field_t &rho, Vector_t hr, double zshift)
 
 void MGPoissonSolver::computeMap(NDIndex<3> localId) {
     if (itsBunch_m->getLocalTrackStep()%repartFreq_m == 0){
-        deletePtr(); 
+        deletePtr();
         if(useRCB_m)
             redistributeWithRCB(localId);
         else
@@ -267,7 +267,7 @@ void MGPoissonSolver::computePotential(Field_t &rho, Vector_t hr) {
     IpplTimings::startTimer(FunctionTimer1_m);
     // Compute boundary intersections (only do on the first step)
     if(!itsBunch_m->getLocalTrackStep())
-        bp->Compute(hr, localId);
+        bp->compute(hr, localId);
     IpplTimings::stopTimer(FunctionTimer1_m);
 
     // Define the Map
@@ -278,7 +278,7 @@ void MGPoissonSolver::computePotential(Field_t &rho, Vector_t hr) {
     INFOMSG(level2 << "* Done." << endl);
 
     // Allocate the RHS with the new Epetra Map
-    if (Teuchos::is_null(RHS)) 
+    if (Teuchos::is_null(RHS))
         RHS = rcp(new Epetra_Vector(*Map));
     RHS->PutScalar(0.0);
 
@@ -290,7 +290,7 @@ void MGPoissonSolver::computePotential(Field_t &rho, Vector_t hr) {
     int id = 0;
     float scaleFactor = itsBunch_m->getdT();
 
- 
+
     std::cout << "* Node:" << Ippl::myNode() << ", Rho for final element: " << rho[localId[0].last()][localId[1].last()][localId[2].last()].get() << std::endl;
 
     Ippl::Comm->barrier();
@@ -411,7 +411,7 @@ void MGPoissonSolver::computePotential(Field_t &rho, Vector_t hr) {
         LHS = Teuchos::null;
         RHS = Teuchos::null;
         prec_m = Teuchos::null;
-    }	
+    }
 }
 
 
@@ -589,4 +589,4 @@ Inform &MGPoissonSolver::print(Inform &os) const {
     return os;
 }
 
-#endif /* HAVE_SAAMG_SOLVER */
+#endif /* HAVE_SAAMG_SOLVER */
\ No newline at end of file
diff --git a/src/Solvers/MGPoissonSolver.h b/src/Solvers/MGPoissonSolver.h
index 08a5ed05286cc342bf815a449faaddccb471423f..45c145357e5848e31e66da2a230135ed5b6f5984 100644
--- a/src/Solvers/MGPoissonSolver.h
+++ b/src/Solvers/MGPoissonSolver.h
@@ -123,7 +123,7 @@ public:
     double getYRangeMax() { return bp->getYRangeMax(); }
     double getZRangeMin() { return bp->getZRangeMin(); }
     double getZRangeMax() { return bp->getZRangeMax(); }
-    void test(PartBunch &bunch) { } 
+    void test(PartBunch &bunch) { }
     /// useful load balance information
     void printLoadBalanceStats();
 
diff --git a/src/Solvers/P3MPoissonSolver.cpp b/src/Solvers/P3MPoissonSolver.cpp
index 5063da7a5a6b68ec1302bb5bfa756db0993023f0..613752add65c5c282eaadabb45266cfa532e06d9 100644
--- a/src/Solvers/P3MPoissonSolver.cpp
+++ b/src/Solvers/P3MPoissonSolver.cpp
@@ -76,10 +76,10 @@ struct ApplyField {
     {
         Vector_t diff = P.R[i] - (P.R[j]+shift);
         double sqr = 0;
-        
+
         for (unsigned d = 0; d<Dim; ++d)
             sqr += diff[d]*diff[d];
-        
+
         //compute r with softening parameter, unsoftened r is obtained by sqrt(sqr)
         if(sqr!=0) {
             double r = std::sqrt(sqr+eps*eps);
@@ -87,10 +87,10 @@ struct ApplyField {
             if (P.Q[i]!=0 && P.Q[j]!=0) {
                 //compute potential energy
                 double phi =ke*(1.-erf(a*sqrt(sqr)))/r;
-                
+
                 //compute force
                 Vector_t Fij = ke*C*(diff/sqrt(sqr))*((2.*a*exp(-a*a*sqr))/(sqrt(M_PI)*r)+(1.-erf(a*sqrt(sqr)))/(r*r));
-                
+
                 //Actual Force is F_ij multiplied by Qi*Qj
                 //The electrical field on particle i is E=F/q_i and hence:
                 P.Ef[i] -= P.Q[j]*Fij;
@@ -114,16 +114,16 @@ struct ApplyField {
 
 
 P3MPoissonSolver::P3MPoissonSolver(Mesh_t *mesh, FieldLayout_t *fl, double interaction_radius, double alpha, double eps):
-mesh_m(mesh),
-layout_m(fl),
-interaction_radius_m(interaction_radius),
-alpha_m(alpha),
-eps_m(eps)
+    mesh_m(mesh),
+    layout_m(fl),
+    interaction_radius_m(interaction_radius),
+    alpha_m(alpha),
+    eps_m(eps)
 {
     Inform msg("P3MPoissonSolver::P3MPoissonSolver ");
-    
+
     domain_m = layout_m->getDomain();
-    
+
     for (unsigned int i = 0; i < 2 * Dim; ++i) {
         if (Ippl::getNodes()>1) {
             bc_m[i] = new ParallelInterpolationFace<double, Dim, Mesh_t, Center_t>(i);
@@ -138,7 +138,7 @@ eps_m(eps)
             bcp_m[i] = new PeriodicFace<double, Dim, Mesh_t, Center_t>(i);
         }
     }
-    
+
     for (unsigned int i = 0; i < 2 * Dim; ++i) {
         if (Ippl::getNodes()>1) {
             bc_m[i] = new ParallelInterpolationFace<double, Dim, Mesh_t, Center_t>(i);
@@ -153,15 +153,15 @@ eps_m(eps)
             bcp_m[i] = new PeriodicFace<double, Dim, Mesh_t, Center_t>(i);
         }
     }
-    
-    
+
+
     // For efficiency in the FFT's, we can use a parallel decomposition
     // which can be serial in the first dimension.
     // e_dim_tag decomp[3];
     // for(int d = 0; d < 3; ++d) {
     //     decomp[d] = layout_m->getRequestedDistribution(d);
     // }
-    
+
     // The FFT's require double-sized field sizes in order to (more closely
     // do not understand this ...)
     // simulate an isolated system.  The FFT of the charge density field, rho,
@@ -172,14 +172,14 @@ eps_m(eps)
         hr_m[i] = mesh_m->get_meshSpacing(i);
         nr_m[i] = domain_m[i].length();
     }
-    
+
     rhocmpl_m.initialize(*mesh_m, *layout_m, GuardCellSizes<Dim>(1));
     grncmpl_m.initialize(*mesh_m, *layout_m, GuardCellSizes<Dim>(1));
-    
+
     rho_m.initialize(*mesh_m, *layout_m, GuardCellSizes<Dim>(1), bc_m);
     phi_m.initialize(*mesh_m, *layout_m, GuardCellSizes<Dim>(1), bcp_m);
     eg_m.initialize (*mesh_m, *layout_m, GuardCellSizes<Dim>(1), vbc_m);
-    
+
     bool compressTemps = true;
     // create the FFT object
     fft_m = std::unique_ptr<FFTC_t>(new FFTC_t(layout_m->getDomain(), compressTemps));
@@ -188,9 +188,9 @@ eps_m(eps)
 }
 
 void P3MPoissonSolver::initFields() {
-    
+
     domain_m = layout_m->getDomain();
-    
+
     for (unsigned int i = 0; i < 2 * Dim; ++i) {
         if (Ippl::getNodes()>1) {
             bc_m[i] = new ParallelInterpolationFace<double, Dim, Mesh_t, Center_t>(i);
@@ -205,7 +205,7 @@ void P3MPoissonSolver::initFields() {
             bcp_m[i] = new PeriodicFace<double, Dim, Mesh_t, Center_t>(i);
         }
     }
-    
+
     for (unsigned int i = 0; i < 2 * Dim; ++i) {
         if (Ippl::getNodes()>1) {
             bc_m[i] = new ParallelInterpolationFace<double, Dim, Mesh_t, Center_t>(i);
@@ -220,28 +220,28 @@ void P3MPoissonSolver::initFields() {
             bcp_m[i] = new PeriodicFace<double, Dim, Mesh_t, Center_t>(i);
         }
     }
-    
+
     for(unsigned int i = 0; i < 3; i++) {
         hr_m[i] = mesh_m->get_meshSpacing(i);
         nr_m[i] = domain_m[i].length();
     }
-    
+
     rhocmpl_m.initialize(*mesh_m, *layout_m, GuardCellSizes<Dim>(1));
     grncmpl_m.initialize(*mesh_m, *layout_m, GuardCellSizes<Dim>(1));
-    
+
     rho_m.initialize(*mesh_m, *layout_m, GuardCellSizes<Dim>(1), bc_m);
     phi_m.initialize(*mesh_m, *layout_m, GuardCellSizes<Dim>(1), bcp_m);
     eg_m.initialize (*mesh_m, *layout_m, GuardCellSizes<Dim>(1), vbc_m);
-    
+
     bool compressTemps = true;
     if (fft_m)
         fft_m.reset();
-    
+
     // create the FFT object
     fft_m = std::unique_ptr<FFTC_t>(new FFTC_t(layout_m->getDomain(), compressTemps));
     fft_m->setDirectionName(+1, "forward");
     fft_m->setDirectionName(-1, "inverse");
-    
+
 }
 
 
@@ -262,25 +262,25 @@ void P3MPoissonSolver::calculatePairForces(PartBunch &bunch, double interaction_
             HPB.for_each(RadiusCondition<double, Dim>(interaction_radius), ApplyField<double>(-1,interaction_radius,eps,alpha),extend_l, extend_r);
         }
     }
-    
+
 }
 
 void P3MPoissonSolver::calculateGridForces(PartBunch &bunch, double interaction_radius, double alpha, double eps){
-    
+
     Inform msg ("calculateGridForces ");
     Vector_t l,h;
-    
+
     // (1) scatter charge to charge density grid and transform to fourier space
     rho_m[domain_m]=0;
     bunch.Q.scatter(rho_m, bunch.R, IntrplCIC_t());
-    
+
     rhocmpl_m[domain_m] = rho_m[domain_m]/(hr_m[0]*hr_m[1]*hr_m[2]);
-    
+
     fft_m->transform("inverse", rhocmpl_m);
-    
+
     // (2) compute Greens function in real space and transform to fourier space
     IField_t grnIField[3];
-    
+
     // This loop stores in grnIField_m[i] the index of the ith dimension mirrored at the central axis. e.g.
     // grnIField_m[0]=[(0 1 2 3 ... 3 2 1) ; (0 1 2 3 ... 3 2 1; ...)]
     for (int i = 0; i < 3; ++i) {
@@ -292,23 +292,23 @@ void P3MPoissonSolver::calculateGridForces(PartBunch &bunch, double interaction_
     }
     Vector_t hrsq(hr_m * hr_m);
     SpecializedGreensFunction<3>::calculate(hrsq, grncmpl_m, grnIField, alpha, eps);
-    
+
     //transform G -> Ghat and store in grncmpl_m
     fft_m->transform("inverse", grncmpl_m);
     //multiply in fourier space and obtain PhiHat in rhocmpl_m
     rhocmpl_m *= grncmpl_m;
-    
+
     // (3) Backtransformation: compute potential field in real space and E=-Grad Phi
     //compute electrostatic potential Phi in real space by FFT PhiHat -> Phi and store it in rhocmpl_m
     fft_m->transform("forward", rhocmpl_m);
-    
+
     //take only the real part and store in phi_m (has periodic bc instead of interpolation bc)
     phi_m = real(rhocmpl_m)*hr_m[0]*hr_m[1]*hr_m[2];
     //dumpVTKScalar( phi_m, this,it, "Phi_m") ;
-    
+
     //compute Electric field on the grid by -Grad(Phi) store in eg_m
     eg_m = -Grad1Ord(phi_m, eg_m);
-    
+
     //interpolate the electric field to the particle positions
     bunch.Ef.gather(eg_m, bunch.R,  IntrplCIC_t());
     //interpolate electrostatic potenital to the particle positions
@@ -323,14 +323,14 @@ void P3MPoissonSolver::calculateGridForces(PartBunch &bunch, double interaction_
 // the Poisson's equation
 
 void P3MPoissonSolver::computePotential(Field_t &rho, Vector_t hr, double zshift) {
-    
-    
+
+
 }
 
 void P3MPoissonSolver::computeAvgSpaceChargeForces(PartBunch &bunch) {
-    
+
     Inform m("computeAvgSpaceChargeForces ");
-    
+
     const double N =  static_cast<double>(bunch.getTotalNum());
     double locAvgEf[Dim]={};
     for (unsigned i=0; i<bunch.getLocalNum(); ++i) {
@@ -338,16 +338,16 @@ void P3MPoissonSolver::computeAvgSpaceChargeForces(PartBunch &bunch) {
         locAvgEf[1]+=fabs(bunch.Ef[i](1));
         locAvgEf[2]+=fabs(bunch.Ef[i](2));
     }
-    
+
     reduce(&(locAvgEf[0]), &(locAvgEf[0]) + Dim,
            &(globSumEf_m[0]), OpAddAssign());
-    
+
     //    m << "globSumEF = " << globSumEf_m[0] << "\t" << globSumEf_m[1] << "\t" << globSumEf_m[2] << endl;
-    
+
     avgEF_m[0]=globSumEf_m[0]/N;
     avgEF_m[1]=globSumEf_m[1]/N;
     avgEF_m[2]=globSumEf_m[2]/N;
-    
+
 }
 
 
@@ -359,50 +359,50 @@ void P3MPoissonSolver::applyConstantFocusing(PartBunch &bunch, double f, double
         Rrel=bunch.R[i] - beam_center;
         bunch.Ef[i] += Rrel/r*f*scFoc;
     }
-    
+
 }
 
 // given a charge-density field rho and a set of mesh spacings hr,
 // compute the scalar potential in open space
 void P3MPoissonSolver::computePotential(Field_t &rho, Vector_t hr) {
-    
-    
+
+
 }
 
 void P3MPoissonSolver::compute_temperature(PartBunch &bunch) {
 
-  Inform m("compute_temperature ");
-  // double loc_temp[Dim]={0.0,0.0,0.0};
-  double loc_avg_vel[Dim]={0.0,0.0,0.0};
-  double avg_vel[Dim]={0.0,0.0,0.0};
-  
-  for(unsigned long k = 0; k < bunch.getLocalNum(); ++k) {
-    for(unsigned i = 0; i < Dim; i++) {
-      loc_avg_vel[i]   += bunch.P[k](i);
+    Inform m("compute_temperature ");
+    // double loc_temp[Dim]={0.0,0.0,0.0};
+    double loc_avg_vel[Dim]={0.0,0.0,0.0};
+    double avg_vel[Dim]={0.0,0.0,0.0};
+
+    for(unsigned long k = 0; k < bunch.getLocalNum(); ++k) {
+        for(unsigned i = 0; i < Dim; i++) {
+            loc_avg_vel[i]   += bunch.P[k](i);
+        }
     }
-  }
-  reduce(&(loc_avg_vel[0]), &(loc_avg_vel[0]) + Dim,
-	 &(avg_vel[0]), OpAddAssign());
+    reduce(&(loc_avg_vel[0]), &(loc_avg_vel[0]) + Dim,
+           &(avg_vel[0]), OpAddAssign());
 
-  const double N =  static_cast<double>(bunch.getTotalNum());
-  avg_vel[0]=avg_vel[0]/N;
-  avg_vel[1]=avg_vel[1]/N;
-  avg_vel[2]=avg_vel[2]/N;
+    const double N =  static_cast<double>(bunch.getTotalNum());
+    avg_vel[0]=avg_vel[0]/N;
+    avg_vel[1]=avg_vel[1]/N;
+    avg_vel[2]=avg_vel[2]/N;
 
-  m << "avg_vel[0]= " << avg_vel[0] << " avg_vel[1]= " << avg_vel[1]  << " avg_vel[2]= " << avg_vel[2] << endl;
+    m << "avg_vel[0]= " << avg_vel[0] << " avg_vel[1]= " << avg_vel[1]  << " avg_vel[2]= " << avg_vel[2] << endl;
 
-  /*
-  for(unsigned long k = 0; k < bunch.getLocalNum(); ++k) {
-    for(unsigned i = 0; i < Dim; i++) {
+    /*
+      for(unsigned long k = 0; k < bunch.getLocalNum(); ++k) {
+      for(unsigned i = 0; i < Dim; i++) {
       loc_temp[i]   += (bunch.P[k](i)-avg_vel[i])*(bunch.P[k](i)-avg_vel[i]);
-    }
-  }
-  reduce(&(loc_temp[0]), &(loc_temp[0]) + Dim,
-	 &(temperature[0]), OpAddAssign());
-  temperature[0]=temperature[0]/N;
-  temperature[1]=temperature[1]/N;
-  temperature[2]=temperature[2]/N;
-  */
+      }
+      }
+      reduce(&(loc_temp[0]), &(loc_temp[0]) + Dim,
+      &(temperature[0]), OpAddAssign());
+      temperature[0]=temperature[0]/N;
+      temperature[1]=temperature[1]/N;
+      temperature[2]=temperature[2]/N;
+    */
 }
 
 void P3MPoissonSolver::test(PartBunch &bunch) {
@@ -412,62 +412,62 @@ void P3MPoissonSolver::test(PartBunch &bunch) {
     const double mi = 1.0;
     const double qi = -1.0;
     const double qom = qi/mi;
-    const double beam_radius = 0.001774; 
+    const double beam_radius = 0.001774;
     const double f = 1.5;
-    const double dt = bunch.getdT();    
+    const double dt = bunch.getdT();
 
     OpalData *opal = OpalData::getInstance();
     DataSink *ds = opal->getDataSink();
-    
+
     std::vector<std::pair<std::string, unsigned int> > collimatorLosses; // just empty
     Vector_t FDext[6];
 
     bunch.Q = qi;
     bunch.M = mi;
-    
+
     bunch.calcBeamParameters();
 
     initFields();
-    
+
     for (int i=0; i<3; i++) {
         extend_r[i] =  hr_m[i]*nr_m[i]/2;
         extend_l[i] = -hr_m[i]*nr_m[i]/2;
     }
 
     msg << *this << endl;
-    
+
     // calculate initial space charge forces
-    this->calculateGridForces(bunch, interaction_radius_m, alpha_m, eps_m);
-    this->calculatePairForces(bunch, interaction_radius_m, alpha_m, eps_m);
+    calculateGridForces(bunch, interaction_radius_m, alpha_m, eps_m);
+    calculatePairForces(bunch, interaction_radius_m, alpha_m, eps_m);
 
     //avg space charge forces for constant focusing
-    this->computeAvgSpaceChargeForces(bunch);
+    computeAvgSpaceChargeForces(bunch);
 
     for (int it=0; it<1000; it++) {
-      
-      // advance the particle positions
-      // basic leapfrogging timestep scheme.  velocities are offset
-      // by half a timestep from the positions.
-        
-      assign(bunch.R, bunch.R + dt * bunch.P);
-      
-      bunch.update();
-        
-      this->calculateGridForces(bunch, interaction_radius_m, alpha_m, eps_m);
-      this->calculatePairForces(bunch, interaction_radius_m, alpha_m, eps_m);
-      this->applyConstantFocusing(bunch,f,beam_radius);
-        
-      assign(bunch.P, bunch.P + dt * qom * bunch.Ef);
-      
-      if (it%10==0){
-        bunch.calcBeamParameters();
-        ds->writeStatData(bunch, FDext, 0.0, it, 0.0, 0);
-      }
-      msg << "Finished iteration " << it << endl;
+
+        // advance the particle positions
+        // basic leapfrogging timestep scheme.  velocities are offset
+        // by half a timestep from the positions.
+
+        assign(bunch.R, bunch.R + dt * bunch.P);
+
+        bunch.update();
+
+        calculateGridForces(bunch, interaction_radius_m, alpha_m, eps_m);
+        calculatePairForces(bunch, interaction_radius_m, alpha_m, eps_m);
+        applyConstantFocusing(bunch,f,beam_radius);
+
+        assign(bunch.P, bunch.P + dt * qom * bunch.Ef);
+
+        if (it%10 == 0){
+            bunch.calcBeamParameters();
+            ds->writeStatData(bunch, FDext, it);
+        }
+        msg << "Finished iteration " << it << endl;
     }
 }
 
-                                                                              
+
 Inform &P3MPoissonSolver::print(Inform &os) const {
     os << "* ************* P 3 M - P o i s s o n S o l v e r *************** " << endl;
     os << "* h        " << hr_m << '\n';
@@ -477,7 +477,7 @@ Inform &P3MPoissonSolver::print(Inform &os) const {
     os << "* Extend L " << extend_l << '\n';
     os << "* Extend R " << extend_r << '\n';
     os << "* hr       " << hr_m << '\n';
-    os << "* nr       " << nr_m << '\n';                                    
+    os << "* nr       " << nr_m << '\n';
     os << "* *************************************************************** " << endl;
     return os;
 }
diff --git a/src/Solvers/P3MPoissonSolver.h b/src/Solvers/P3MPoissonSolver.h
index 21e2987b209645e2a6021daf4a7d110cb0e34c85..3ae5875ac190e306af42809b0e3ee32a213fb2a5 100644
--- a/src/Solvers/P3MPoissonSolver.h
+++ b/src/Solvers/P3MPoissonSolver.h
@@ -44,9 +44,9 @@ public:
     ~P3MPoissonSolver();
 
     void initFields();
-    
+
     void calculateGridForces(PartBunch &bunch, double interaction_radius, double alpha, double eps);
-    
+
     void calculatePairForces(PartBunch &bunch, double interaction_radius, double alpha, double eps);
 
     // given a charge-density field rho and a set of mesh spacings hr,
@@ -59,7 +59,7 @@ public:
 
     void applyConstantFocusing(PartBunch &bunch, double f, double r);
     void test(PartBunch &bunch);
-    
+
     double getXRangeMin() {return 1.0;}
     double getXRangeMax() {return 1.0;}
     double getYRangeMin() {return 1.0;}
@@ -71,59 +71,59 @@ public:
     void compute_temperature(PartBunch &bunch);
     Inform &print(Inform &os) const;
 private:
-    
+
     BConds<double, Dim, Mesh_t, Center_t> bc_m;
     BConds<double, Dim, Mesh_t, Center_t> bcp_m;
     BConds<Vector_t, Dim, Mesh_t, Center_t> vbc_m;
-    
+
     // rho_m is the charge-density field with mesh doubled in each dimension
     Field_t rho_m;
     Field_t phi_m;
-    
+
     VField_t eg_m;
-    
+
     // real field with layout of complex field: domain3_m
     Field_t greentr_m;
 
     CxField_t rhocmpl_m;
     CxField_t grncmpl_m;
-    
+
     // grntr_m is the Fourier transformed Green's function
     // domain3_m and mesh3_ are used
     CxField_t grntr_m;
 
     // the FFT object
     std::unique_ptr<FFTC_t> fft_m;
-    
+
 
     // Fields used to eliminate excess calculation in greensFunction()
     // mesh2_m and layout2_m are used
     IField_t grnIField_m[3];
 
-    
+
     // mesh and layout objects for rho_m
     Mesh_t *mesh_m;
     FieldLayout_t *layout_m;
 
-    
+
     // tmp
     Field_t tmpgreen;
 
     // domains for the various fields
     NDIndex<3> domain_m;             // original domain, gridsize
     // mesh and gridsize defined outside of P3M class, given as
-    
-    
+
+
     NDIndex<3> domainP3MConstruct_m;
- 
-    
+
+
     double interaction_radius_m;
     double alpha_m;
     double eps_m;
-    
+
     Vector_t hr_m;
     Vektor<int, 3> nr_m;
-    
+
     // for tests
     Vektor<double,Dim> avgEF_m;
     double globSumEf_m[Dim];
@@ -133,7 +133,7 @@ public:
     Vektor<double,3> extend_l;
     Vektor<double,3> extend_r;
 
-    
+
 };
 
 inline Inform &operator<<(Inform &os, const P3MPoissonSolver &fs) {
diff --git a/src/Solvers/PoissonSolver.h b/src/Solvers/PoissonSolver.h
index 082daaf934cacda96385615cbc903a797c572320..a72aef3f7e0e84ddc8730e2a3e1068660477614a 100644
--- a/src/Solvers/PoissonSolver.h
+++ b/src/Solvers/PoissonSolver.h
@@ -31,7 +31,7 @@ public:
     virtual double getZRangeMax() = 0;
     virtual void test(PartBunch &bunch) = 0 ;
     virtual ~PoissonSolver(){};
-    
+
 };
 
 inline Inform &operator<<(Inform &os, const PoissonSolver &fs) {
diff --git a/src/Solvers/RectangularDomain.cpp b/src/Solvers/RectangularDomain.cpp
index e8cd2baa8c7e25baca36648df01f5bba26bde601..663825133a144a134be39e602fad16adb60705c2 100644
--- a/src/Solvers/RectangularDomain.cpp
+++ b/src/Solvers/RectangularDomain.cpp
@@ -18,7 +18,7 @@ RectangularDomain::RectangularDomain(double a, double b, Vector_t nr, Vector_t h
     nxy_m = nr[0] * nr[1];
 }
 
-void RectangularDomain::Compute(Vector_t hr){
+void RectangularDomain::compute(Vector_t hr){
     setHr(hr);
     nxy_m = nr[0] * nr[1];
 }
@@ -159,7 +159,7 @@ void RectangularDomain::getNeighbours(int x, int y, int z, double &W, double &E,
 }
 
 /*
-void MGPoissonSolver::GetNeighbours(const int idx, int& W, int& E, int& S, int& N, int& F, int& B, int& numOutOfDomain)
+void MGPoissonSolver::getNeighbours(const int idx, int& W, int& E, int& S, int& N, int& F, int& B, int& numOutOfDomain)
 {
 
     int ixy, iz, iy, ix;
@@ -223,7 +223,7 @@ void MGPoissonSolver::GetNeighbours(const int idx, int& W, int& E, int& S, int&
 
 //at the moment this stencil has neumann everywhere except on the z=0 plane (Dirichlet)
 //this code is experimental/not-optimized/not-final at the moment
-inline Epetra_CrsMatrix* MGPoissonSolver::Stencil3DOneSidedDirichlet(Vector_t hr)
+inline Epetra_CrsMatrix* MGPoissonSolver::stencil3DOneSidedDirichlet(Vector_t hr)
 {
     Epetra_CrsMatrix* Matrix = new Epetra_CrsMatrix(Copy, *Map,  7);
 
@@ -242,7 +242,7 @@ inline Epetra_CrsMatrix* MGPoissonSolver::Stencil3DOneSidedDirichlet(Vector_t hr
 
     for (int i = 0 ; i < NumMyElements ; ++i)
     {
-        GetNeighbours(MyGlobalElements[i], W, E, S, N, F, B, numout);
+        getNeighbours(MyGlobalElements[i], W, E, S, N, F, B, numout);
 
         int NumEntries = 0;
         double diag = a;
@@ -555,7 +555,7 @@ inline Epetra_CrsMatrix* MGPoissonSolver::Stencil3DOneSidedDirichlet(Vector_t hr
 
 //stencil for longitudinal neumann and transversal dirichlet BC
 //this code is experimental/not-optimized/not-final at the moment
-inline Epetra_CrsMatrix* MGPoissonSolver::Stencil3DLongitudinalNeumann(Vector_t hr)
+inline Epetra_CrsMatrix* MGPoissonSolver::stencil3DLongitudinalNeumann(Vector_t hr)
 {
     Epetra_CrsMatrix* Matrix = new Epetra_CrsMatrix(Copy, *Map,  7);
 
@@ -574,7 +574,7 @@ inline Epetra_CrsMatrix* MGPoissonSolver::Stencil3DLongitudinalNeumann(Vector_t
 
     for (int i = 0 ; i < NumMyElements ; ++i)
     {
-        GetNeighbours(MyGlobalElements[i], W, E, S, N, F, B, numout);
+        getNeighbours(MyGlobalElements[i], W, E, S, N, F, B, numout);
 
         int NumEntries = 0;
         double diag = a;
diff --git a/src/Solvers/RectangularDomain.h b/src/Solvers/RectangularDomain.h
index 40fb6b97c5e1eeb2783371a02f9d8d430515bc1c..47265332bd0c39e5a42ba608950cefb07fac8c81 100644
--- a/src/Solvers/RectangularDomain.h
+++ b/src/Solvers/RectangularDomain.h
@@ -16,7 +16,7 @@ public:
     RectangularDomain(double a, double b, Vector_t nr, Vector_t hr);
 
     /// calculates intersection with the beam pipe
-    void Compute(Vector_t hr);
+    void compute(Vector_t hr);
 
     /// returns number of nodes in xy plane (here independent of z coordinate)
     int getNumXY(int z);
diff --git a/src/Solvers/TaperDomain.cpp b/src/Solvers/TaperDomain.cpp
index 2514ea4df32ab81673cee5a95236c4354c9e2a56..c08d8f259a5a959b826929121270f08506c1ba26 100644
--- a/src/Solvers/TaperDomain.cpp
+++ b/src/Solvers/TaperDomain.cpp
@@ -15,11 +15,11 @@ TaperDomain::TaperDomain(double rb, double rs, Vector_t nr, Vector_t hr, std::st
     setNr(nr);
     setHr(hr);
 
-    if(interpl == "constant")
+    if(interpl == "CONSTANT")
         interpolationMethod = CONSTANT;
-    else if(interpl == "linear")
+    else if(interpl == "LINEAR")
         interpolationMethod = LINEAR;
-    else if(interpl == "quadratic")
+    else if(interpl == "QUADRATIC")
         interpolationMethod = QUADRATIC;
 }
 
@@ -31,7 +31,7 @@ TaperDomain::~TaperDomain() {
 // for this domain we only have to calculate the intersection on one z
 // cross-section
 //if(hr[0] == getHr()[0] && hr[1] == getHr()[1])
-void TaperDomain::Compute(Vector_t hr) {
+void TaperDomain::compute(Vector_t hr) {
 
     setHr(hr);
     nxy_m = 0;
@@ -115,13 +115,13 @@ void TaperDomain::getBoundaryStencil(int x, int y, int z, double &W, double &E,
     // determine which interpolation method we use for points near the boundary
     switch(interpolationMethod) {
         case CONSTANT:
-            ConstantInterpolation(x, y, z, W, E, S, N, F, B, C, scaleFactor);
+            constantInterpolation(x, y, z, W, E, S, N, F, B, C, scaleFactor);
             break;
         case LINEAR:
-            LinearInterpolation(x, y, z, W, E, S, N, F, B, C, scaleFactor);
+            linearInterpolation(x, y, z, W, E, S, N, F, B, C, scaleFactor);
             break;
         case QUADRATIC:
-            QuadraticInterpolation(x, y, z, W, E, S, N, F, B, C, scaleFactor);
+            quadraticInterpolation(x, y, z, W, E, S, N, F, B, C, scaleFactor);
             break;
     }
 
@@ -134,7 +134,7 @@ void TaperDomain::getBoundaryStencil(int x, int y, int z, double &W, double &E,
 
 // here we do not need to calculate intersection so we make use of the
 // isInside function to determin if a given point is inside the domain
-void TaperDomain::ConstantInterpolation(int x, int y, int z, double &W, double &E, double &S, double &N, double &F, double &B, double &C, double &scaleFactor) {
+void TaperDomain::constantInterpolation(int x, int y, int z, double &W, double &E, double &S, double &N, double &F, double &B, double &C, double &scaleFactor) {
 
     //scaleFactor = hr[0]*hr[1]*hr[2];
     scaleFactor = 1.0;
@@ -200,7 +200,7 @@ void TaperDomain::ConstantInterpolation(int x, int y, int z, double &W, double &
 }
 
 //TODO: remove isInside()
-void TaperDomain::LinearInterpolation(int x, int y, int z, double &W, double &E, double &S, double &N, double &F, double &B, double &C, double &scaleFactor) {
+void TaperDomain::linearInterpolation(int x, int y, int z, double &W, double &E, double &S, double &N, double &F, double &B, double &C, double &scaleFactor) {
 
     scaleFactor = 1.0;
 
@@ -299,7 +299,7 @@ void TaperDomain::LinearInterpolation(int x, int y, int z, double &W, double &E,
 
 }
 
-void TaperDomain::QuadraticInterpolation(int x, int y, int z, double &W, double &E, double &S, double &N, double &F, double &B, double &C, double &scaleFactor) {
+void TaperDomain::quadraticInterpolation(int x, int y, int z, double &W, double &E, double &S, double &N, double &F, double &B, double &C, double &scaleFactor) {
 
     double cx = (x - floor((double)(nr[0] / 2.0))) * hr[0];
     double cy = (y - floor((double)(nr[1] / 2.0))) * hr[1];
diff --git a/src/Solvers/TaperDomain.h b/src/Solvers/TaperDomain.h
index 3c7c90f594483aed7fab04114fbdbf69ff85c68c..420b4274c81121ee46637206d2bad306561fe6d7 100644
--- a/src/Solvers/TaperDomain.h
+++ b/src/Solvers/TaperDomain.h
@@ -25,7 +25,7 @@ public:
     ~TaperDomain();
 
     /// calculates intersection with the elliptic beam pipe
-    void Compute(Vector_t hr);
+    void compute(Vector_t hr);
     //TODO: do we need to export this function??
     std::vector<double> getYDirIntersect(int x, int z);
     /// returns number of nodes in xy plane (here independent of z coordinate)
@@ -138,9 +138,9 @@ private:
     */
 
     /// different interpolation methods for boundary points
-    void ConstantInterpolation(int x, int y, int z, double &W, double &E, double &S, double &N, double &F, double &B, double &C, double &scaleFactor);
-    void LinearInterpolation(int x, int y, int z, double &W, double &E, double &S, double &N, double &F, double &B, double &C, double &scaleFactor);
-    void QuadraticInterpolation(int x, int y, int z, double &W, double &E, double &S, double &N, double &F, double &B, double &C, double &scaleFactor);
+    void constantInterpolation(int x, int y, int z, double &W, double &E, double &S, double &N, double &F, double &B, double &C, double &scaleFactor);
+    void linearInterpolation(int x, int y, int z, double &W, double &E, double &S, double &N, double &F, double &B, double &C, double &scaleFactor);
+    void quadraticInterpolation(int x, int y, int z, double &W, double &E, double &S, double &N, double &F, double &B, double &C, double &scaleFactor);
 
 };
 
diff --git a/src/Structure/BoundaryGeometry.cpp b/src/Structure/BoundaryGeometry.cpp
index 425af15fb357dbf2cf895890179bc8695e0415b0..b5e98e1d2796f484d5cfc212cf96ba9282eea4dc 100644
--- a/src/Structure/BoundaryGeometry.cpp
+++ b/src/Structure/BoundaryGeometry.cpp
@@ -1595,7 +1595,7 @@ Change orientation if diff is:
             const Vector_t& B = bg->getPoint (triangle_id, 2);
             const Vector_t& C = bg->getPoint (triangle_id, 3);
             const Vector_t  triNormal = normalVector (A, B, C);
-            
+
             // choose a point P close to the center of the triangle
             //const Vector_t P = (A+B+C)/3 + triNormal * 0.1;
             double minvoxelmesh = bg->voxelMesh_m.sizeOfVoxel[0];
@@ -1732,7 +1732,7 @@ Change orientation if diff is:
 #else
     h5_file_t *f = H5OpenFile (h5FileName_m.c_str(), H5_O_RDONLY, Ippl::getComm());
 #endif
-    
+
     h5t_mesh_t* m = NULL;
     H5FedOpenTriangleMesh (f, "0", &m);
     H5FedSetLevel (m, 0);
@@ -2039,7 +2039,7 @@ BoundaryGeometry::intersectLineSegmentBoundary (
         0   particle will collide with boundary in next time step
  */
 int
-BoundaryGeometry::PartInside (
+BoundaryGeometry::partInside (
     const Vector_t& r,                  // [in] particle position
     const Vector_t& v,                  // [in] momentum
     const double dt,                    // [in]
@@ -2601,4 +2601,4 @@ void BoundaryGeometry::createPriPart (
 // mode:c
 // c-basic-offset: 4
 // indent-tabs-mode:nil
-// End:
+// End:
\ No newline at end of file
diff --git a/src/Structure/BoundaryGeometry.h b/src/Structure/BoundaryGeometry.h
index b115e15993d3d96c5b55388eedff6313406102c2..f6ab9b7573ee7de2d4734bdab8875c7c59fcd02a 100644
--- a/src/Structure/BoundaryGeometry.h
+++ b/src/Structure/BoundaryGeometry.h
@@ -80,7 +80,7 @@ public:
         OpalBeamline& itsOpalBeamline,
         PartBunch* itsBunch);
 
-    int PartInside (
+    int partInside (
         const Vector_t& r,
         const Vector_t& v,
         const double dt,
@@ -535,4 +535,4 @@ inline Inform &operator<< (Inform& os, const BoundaryGeometry& b) {
 // mode:c
 // c-basic-offset: 4
 // indent-tabs-mode:nil
-// End:
+// End:
\ No newline at end of file
diff --git a/src/Structure/CMakeLists.txt b/src/Structure/CMakeLists.txt
index 48224582d9e3470c22b044ac0481e2e4bb869f94..768dc0488e25a9ae1cd32f963b53d98361837cd8 100644
--- a/src/Structure/CMakeLists.txt
+++ b/src/Structure/CMakeLists.txt
@@ -11,10 +11,64 @@ set (_SRCS
   H5PartWrapperForPC.cpp
   H5PartWrapperForPS.cpp
   H5PartWrapperForPT.cpp
-  )
+  SDDSParser/array.cpp
+  SDDSParser/associate.cpp
+  SDDSParser/ast.cpp
+  SDDSParser/column.cpp
+  SDDSParser/data.cpp
+  SDDSParser/description.cpp
+  SDDSParser/file.cpp
+  SDDSParser/include.cpp
+  SDDSParser/parameter.cpp
+  SDDSParser/version.cpp
+  OpalInputInterpreter.cpp
+  IpplInfoWrapper.cpp
+)
 
 include_directories (
   ${CMAKE_CURRENT_SOURCE_DIR}
 )
 
-add_sources(${_SRCS})
\ No newline at end of file
+add_opal_sources(${_SRCS})
+
+set (HDRS
+    Beam.h
+    BoundaryGeometry.h
+    DataSink.h
+    FieldSolver.h
+    H5PartWrapperForPC.h
+    H5PartWrapperForPS.h
+    H5PartWrapperForPT.h
+    H5PartWrapper.h
+    IpplInfoWrapper.h
+    OpalInputInterpreter.h
+    OpalWake.h
+    PriEmissionPhysics.h
+    SDDSParser.h
+    SecondaryEmissionPhysics.h
+    SurfacePhysics.h
+    SDDSParser/array_def.hpp
+    SDDSParser/array.hpp
+    SDDSParser/associate_def.hpp
+    SDDSParser/associate.hpp
+    SDDSParser/ast_def.hpp
+    SDDSParser/ast.hpp
+    SDDSParser/column_def.hpp
+    SDDSParser/column.hpp
+    SDDSParser/data_def.hpp
+    SDDSParser/data.hpp
+    SDDSParser/description_def.hpp
+    SDDSParser/description.hpp
+    SDDSParser/error_handler.hpp
+    SDDSParser/file_def.hpp
+    SDDSParser/file.hpp
+    SDDSParser/include_def.hpp
+    SDDSParser/include.hpp
+    SDDSParser/parameter_def.hpp
+    SDDSParser/parameter.hpp
+    SDDSParser/skipper.hpp
+    SDDSParser/version_def.hpp
+    SDDSParser/version.hpp
+)
+
+install (FILES ${HDRS} DESTINATION "${CMAKE_INSTALL_PREFIX}/include/Structure")
\ No newline at end of file
diff --git a/src/Structure/DataSink.cpp b/src/Structure/DataSink.cpp
index c8c6a60e432554aecd331345a5eaf1107421cd85..3d07729849bb2e2aceed4a49bd91a99cdf4acd4f 100644
--- a/src/Structure/DataSink.cpp
+++ b/src/Structure/DataSink.cpp
@@ -4,12 +4,11 @@
 
 #include "Structure/DataSink.h"
 
-#include "config.h"
-#include "revision.h"
+#include "OPALconfig.h"
 #include "Algorithms/bet/EnvelopeBunch.h"
 #include "AbstractObjects/OpalData.h"
 #include "Utilities/Options.h"
-#include "Utilities/Options.h"
+#include "Utilities/Util.h"
 #include "Fields/Fieldmap.h"
 #include "Structure/BoundaryGeometry.h"
 #include "Structure/H5PartWrapper.h"
@@ -55,8 +54,8 @@ DataSink::DataSink(H5PartWrapper *h5wrapper, int restartStep):
                             "Can not restart when HDF5 is disabled");
     }
 
-    H5PartTimer_m = IpplTimings::getTimer("H5PartTimer");
-    StatMarkerTimer_m = IpplTimings::getTimer("StatMarkerTimer");
+    H5PartTimer_m = IpplTimings::getTimer("Write H5-File");
+    StatMarkerTimer_m = IpplTimings::getTimer("Write Stat");
 
     /// Set flags whether SDDS file exists or have to write header first.
     firstWriteToStat_m = true;
@@ -91,8 +90,8 @@ DataSink::DataSink(H5PartWrapper *h5wrapper):
 {
     /// Constructor steps:
     /// Get timers from IPPL.
-    H5PartTimer_m = IpplTimings::getTimer("H5PartTimer");
-    StatMarkerTimer_m = IpplTimings::getTimer("StatMarkerTimer");
+    H5PartTimer_m = IpplTimings::getTimer("Write H5-File");
+    StatMarkerTimer_m = IpplTimings::getTimer("Write Stat");
 
     /// Set file write flags to true. These will be set to false after first
     /// write operation.
@@ -119,33 +118,18 @@ void DataSink::storeCavityInformation() {
     h5wrapper_m->storeCavityInformation();
 }
 
-void DataSink::writePhaseSpace(PartBunch &beam, Vector_t FDext[], double sposHead, double sposRef, double sposTail) {
+void DataSink::writePhaseSpace(PartBunch &beam, Vector_t FDext[]) {
 
     if (!doHDF5_m) return;
 
     IpplTimings::startTimer(H5PartTimer_m);
     std::map<std::string, double> additionalAttributes = {
-        std::make_pair("sposHead", sposHead),
-        std::make_pair("sposRef", sposRef),
-        std::make_pair("sposTail", sposTail),
-        std::make_pair("B-head_x", FDext[0](0)),
-        std::make_pair("B-head_z", FDext[0](1)),
-        std::make_pair("B-head_y", FDext[0](2)),
-        std::make_pair("E-head_x", FDext[1](0)),
-        std::make_pair("E-head_z", FDext[1](1)),
-        std::make_pair("E-head_y", FDext[1](2)),
-        std::make_pair("B-ref_x", FDext[2](0)),
-        std::make_pair("B-ref_z", FDext[2](1)),
-        std::make_pair("B-ref_y", FDext[2](2)),
-        std::make_pair("E-ref_x", FDext[3](0)),
-        std::make_pair("E-ref_z", FDext[3](1)),
-        std::make_pair("E-ref_y", FDext[3](2)),
-        std::make_pair("B-tail_x", FDext[4](0)),
-        std::make_pair("B-tail_z", FDext[4](1)),
-        std::make_pair("B-tail_y", FDext[4](2)),
-        std::make_pair("E-tail_x", FDext[5](0)),
-        std::make_pair("E-tail_z", FDext[5](1)),
-        std::make_pair("E-tail_y", FDext[5](2))};
+        std::make_pair("B-ref_x", FDext[0](0)),
+        std::make_pair("B-ref_z", FDext[0](1)),
+        std::make_pair("B-ref_y", FDext[0](2)),
+        std::make_pair("E-ref_x", FDext[1](0)),
+        std::make_pair("E-ref_z", FDext[1](1)),
+        std::make_pair("E-ref_y", FDext[1](2))};
 
     h5wrapper_m->writeStep(beam, additionalAttributes);
     IpplTimings::stopTimer(H5PartTimer_m);
@@ -259,18 +243,16 @@ void DataSink::dumpStashedPhaseSpaceEnvelope() {
     IpplTimings::stopTimer(H5PartTimer_m);
 }
 
-void DataSink::writeStatData(PartBunch &beam, Vector_t FDext[], double sposHead, double sposRef, double sposTail, double E) {
-    doWriteStatData(beam, FDext, sposHead, sposRef, sposTail, E, std::vector<std::pair<std::string, unsigned int> >());
+void DataSink::writeStatData(PartBunch &beam, Vector_t FDext[], double E) {
+    doWriteStatData(beam, FDext, E, std::vector<std::pair<std::string, unsigned int> >());
 }
 
-void DataSink::writeStatData(PartBunch &beam, Vector_t FDext[], double sposHead, double sposRef, double sposTail, const std::vector<std::pair<std::string, unsigned int> >& losses) {
-    doWriteStatData(beam, FDext, sposHead, sposRef, sposTail, beam.get_meanEnergy(), losses);
+void DataSink::writeStatData(PartBunch &beam, Vector_t FDext[], const std::vector<std::pair<std::string, unsigned int> >& losses) {
+    doWriteStatData(beam, FDext, beam.get_meanKineticEnergy(), losses);
 }
 
 
-void DataSink::doWriteStatData(PartBunch &beam, Vector_t FDext[], double sposHead, double sposRef, double sposTail, double E, const std::vector<std::pair<std::string, unsigned int> > &losses) {
-
-    /// Function steps:
+void DataSink::doWriteStatData(PartBunch &beam, Vector_t FDext[], double E, const std::vector<std::pair<std::string, unsigned int> > &losses) {
 
     /// Start timer.
     IpplTimings::startTimer(StatMarkerTimer_m);
@@ -279,7 +261,7 @@ void DataSink::doWriteStatData(PartBunch &beam, Vector_t FDext[], double sposHea
     unsigned int pwi = 10;
 
     /// Calculate beam statistics and gather load balance statistics.
-//    beam.calcBeamParameters_cycl();
+    beam.calcBeamParameters();
     beam.gatherLoadBalanceStatistics();
 
     size_t npOutside = 0;
@@ -291,7 +273,7 @@ void DataSink::doWriteStatData(PartBunch &beam, Vector_t FDext[], double sposHea
     if (OpalData::getInstance()->isInOPALCyclMode())
         pathLength = beam.getLPath();
     else
-        pathLength = sposRef;
+        pathLength = beam.get_sPos();
 
     /// Write data to files. If this is the first write to the beam statistics file, write SDDS
     /// header information.
@@ -322,7 +304,7 @@ void DataSink::doWriteStatData(PartBunch &beam, Vector_t FDext[], double sposHea
             os_lBalData.setf(ios::scientific, ios::floatfield);
         }
 
-        os_statData << beam.getT() << setw(pwi) << "\t"                                       // 1
+        os_statData << beam.getT() * 1e9 << setw(pwi) << "\t"                                 // 1
                     << pathLength << setw(pwi) << "\t"                                        // 2
 
                     << beam.getTotalNum() << setw(pwi) << "\t"                                // 3
@@ -346,79 +328,50 @@ void DataSink::doWriteStatData(PartBunch &beam, Vector_t FDext[], double sposHea
                     << beam.get_rmean()(1)  << setw(pwi) << "\t"                              // 16
                     << beam.get_rmean()(2)  << setw(pwi) << "\t"                              // 17
 
-                    << beam.get_maxExtend()(0) << setw(pwi) << "\t"                           // 18
-                    << beam.get_maxExtend()(1) << setw(pwi) << "\t"                           // 19
-                    << beam.get_maxExtend()(2) << setw(pwi) << "\t"                           // 20
+                    << beam.RefPartR_m(0) << setw(pwi) << "\t"                                // 18
+                    << beam.RefPartR_m(1) << setw(pwi) << "\t"                                // 19
+                    << beam.RefPartR_m(2) << setw(pwi) << "\t"                                // 20
 
-            // Write out Courant Snyder parameters.
-                    << beam.get_rprrms()(0) << setw(pwi) << "\t"                              // 21
-                    << beam.get_rprrms()(1) << setw(pwi) << "\t"                              // 22
-                    << beam.get_rprrms()(2) << setw(pwi) << "\t"                              // 23
+                    << beam.RefPartP_m(0) << setw(pwi) << "\t"                                // 21
+                    << beam.RefPartP_m(1) << setw(pwi) << "\t"                                // 22
+                    << beam.RefPartP_m(2) << setw(pwi) << "\t"                                // 23
 
-                    << 0.0 << setw(pwi) << "\t"                                                // 24
-                    << 0.0 << setw(pwi) << "\t"                                                // 25
+                    << beam.get_maxExtent()(0) << setw(pwi) << "\t"                           // 24
+                    << beam.get_maxExtent()(1) << setw(pwi) << "\t"                           // 25
+                    << beam.get_maxExtent()(2) << setw(pwi) << "\t"                           // 26
+
+            // Write out Courant Snyder parameters.
+                    << beam.get_rprms()(0) << setw(pwi) << "\t"                               // 27
+                    << beam.get_rprms()(1) << setw(pwi) << "\t"                               // 28
+                    << beam.get_rprms()(2) << setw(pwi) << "\t"                               // 29
 
             // Write out dispersion.
-                    << beam.get_Dx() << setw(pwi) << "\t"                                      // 26
-                    << beam.get_DDx() << setw(pwi) << "\t"                                     // 27
-                    << beam.get_Dy() << setw(pwi) << "\t"                                      // 28
-                    << beam.get_DDy() << setw(pwi) << "\t"                                     // 29
+                    << beam.get_Dx() << setw(pwi) << "\t"                                      // 30
+                    << beam.get_DDx() << setw(pwi) << "\t"                                     // 31
+                    << beam.get_Dy() << setw(pwi) << "\t"                                      // 32
+                    << beam.get_DDy() << setw(pwi) << "\t"                                     // 33
 
 
             // Write head/reference particle/tail field information.
-                    << FDext[0](0) << setw(pwi) << "\t"                                         // 30 B-head x
-                    << FDext[0](1) << setw(pwi) << "\t"                                         // 31 B-head y
-                    << FDext[0](2) << setw(pwi) << "\t"                                         // 32 B-head z
-
-                    << FDext[1](0) << setw(pwi) << "\t"                                         // 33 E-head x
-                    << FDext[1](1) << setw(pwi) << "\t"                                         // 34 E-head y
-                    << FDext[1](2) << setw(pwi) << "\t"                                         // 35 E-head z
+                    << FDext[0](0) << setw(pwi) << "\t"                                         // 34 B-ref x
+                    << FDext[0](1) << setw(pwi) << "\t"                                         // 35 B-ref y
+                    << FDext[0](2) << setw(pwi) << "\t"                                         // 36 B-ref z
 
-                    << FDext[2](0) << setw(pwi) << "\t"                                         // 36 B-ref x
-                    << FDext[2](1) << setw(pwi) << "\t"                                         // 37 B-ref y
-                    << FDext[2](2) << setw(pwi) << "\t"                                         // 38 B-ref z
+                    << FDext[1](0) << setw(pwi) << "\t"                                         // 37 E-ref x
+                    << FDext[1](1) << setw(pwi) << "\t"                                         // 38 E-ref y
+                    << FDext[1](2) << setw(pwi) << "\t"                                         // 39 E-ref z
 
-                    << FDext[3](0) << setw(pwi) << "\t"                                         // 39 E-ref x
-                    << FDext[3](1) << setw(pwi) << "\t"                                         // 40 E-ref y
-                    << FDext[3](2) << setw(pwi) << "\t"                                         // 41 E-ref z
-
-                    << FDext[4](0) << setw(pwi) << "\t"                                         // 42 B-tail x
-                    << FDext[4](1) << setw(pwi) << "\t"                                         // 43 B-tail y
-                    << FDext[4](2) << setw(pwi) << "\t"                                         // 44 B-tail z
-
-                    << FDext[5](0) << setw(pwi) << "\t"                                         // 45 E-tail x
-                    << FDext[5](1) << setw(pwi) << "\t"                                         // 46 E-tail y
-                    << FDext[5](2) << setw(pwi) << "\t"                                         // 47 E-tail z
-
-                    << beam.getdE() << setw(pwi) << "\t"                                        // 48 dE energy spread
-
-                    << npOutside << setw(pwi) << "\t";                                          // 49 number of particles outside n*sigma
+                    << beam.getdE() << setw(pwi) << "\t"                                        // 40 dE energy spread
+                    << beam.getdT() * 1e9 << setw(pwi) << "\t"                                        // 41 dt time step size
+                    << npOutside << setw(pwi) << "\t";                                          // 42 number of particles outside n*sigma
 
         if(Ippl::getNodes() == 1 && beam.getLocalNum() > 0) {
-            os_statData << beam.R[0](0) << setw(pwi) << "\t";                                   // 50 R0_x
-            os_statData << beam.R[0](1) << setw(pwi) << "\t";                                   // 51 R0_y
-            os_statData << beam.R[0](2) << setw(pwi) << "\t";                                   // 52 R0_z
-            os_statData << beam.P[0](0) << setw(pwi) << "\t";                                   // 53 P0_x
-            os_statData << beam.P[0](1) << setw(pwi) << "\t";                                   // 54 P0_y
-            os_statData << beam.P[0](2) << setw(pwi) << "\t";                                   // 55 P0_z
-            os_statData << beam.R[0](0) << setw(pwi) << "\t";                                   // 50 R0_x
-            os_statData << beam.R[1](1) << setw(pwi) << "\t";                                   // 51 R0_y
-            os_statData << beam.R[1](2) << setw(pwi) << "\t";                                   // 52 R0_z
-            os_statData << beam.P[1](0) << setw(pwi) << "\t";                                   // 53 P0_x
-            os_statData << beam.P[1](1) << setw(pwi) << "\t";                                   // 54 P0_y
-            os_statData << beam.P[1](2) << setw(pwi) << "\t";                                   // 55 P0_z
-            os_statData << beam.R[2](0) << setw(pwi) << "\t";                                   // 50 R0_x
-            os_statData << beam.R[2](1) << setw(pwi) << "\t";                                   // 51 R0_y
-            os_statData << beam.R[2](2) << setw(pwi) << "\t";                                   // 52 R0_z
-            os_statData << beam.P[2](0) << setw(pwi) << "\t";                                   // 53 P0_x
-            os_statData << beam.P[2](1) << setw(pwi) << "\t";                                   // 54 P0_y
-            os_statData << beam.P[2](2) << setw(pwi) << "\t";                                   // 55 P0_z
-            os_statData << beam.R[3](0) << setw(pwi) << "\t";                                   // 50 R0_x
-            os_statData << beam.R[3](1) << setw(pwi) << "\t";                                   // 51 R0_y
-            os_statData << beam.R[3](2) << setw(pwi) << "\t";                                   // 52 R0_z
-            os_statData << beam.P[3](0) << setw(pwi) << "\t";                                   // 53 P0_x
-            os_statData << beam.P[3](1) << setw(pwi) << "\t";                                   // 54 P0_y
-            os_statData << beam.P[3](2) << setw(pwi) << "\t";                                   // 55 P0_z
+            os_statData << beam.R[0](0) << setw(pwi) << "\t";                                   // 43 R0_x
+            os_statData << beam.R[0](1) << setw(pwi) << "\t";                                   // 44 R0_y
+            os_statData << beam.R[0](2) << setw(pwi) << "\t";                                   // 45 R0_z
+            os_statData << beam.P[0](0) << setw(pwi) << "\t";                                   // 46 P0_x
+            os_statData << beam.P[0](1) << setw(pwi) << "\t";                                   // 47 P0_y
+            os_statData << beam.P[0](2) << setw(pwi) << "\t";                                   // 48 P0_z
         }
 
 
@@ -455,7 +408,7 @@ void DataSink::writeStatData(EnvelopeBunch &beam, Vector_t FDext[], double sposH
     /// header information.
     ofstream os_statData;
     ofstream os_lBalData;
-    double en = beam.get_meanEnergy() * 1e-6;
+    double en = beam.get_meanKineticEnergy() * 1e-6;
 
     if(Ippl::myNode() == 0) {
         if(firstWriteToStat_m) {
@@ -504,9 +457,9 @@ void DataSink::writeStatData(EnvelopeBunch &beam, Vector_t FDext[], double sposH
                     << beam.get_rmean()(1)  << setw(pwi) << "\t"                              // 16
                     << beam.get_rmean()(2)  << setw(pwi) << "\t"                              // 17
 
-                    << beam.get_maxExtend()(0) << setw(pwi) << "\t"                           // 18
-                    << beam.get_maxExtend()(1) << setw(pwi) << "\t"                           // 19
-                    << beam.get_maxExtend()(2) << setw(pwi) << "\t"                           // 20
+                    << beam.get_maxExtent()(0) << setw(pwi) << "\t"                           // 18
+                    << beam.get_maxExtent()(1) << setw(pwi) << "\t"                           // 19
+                    << beam.get_maxExtent()(2) << setw(pwi) << "\t"                           // 20
 
             // Write out Courant Snyder parameters.
                     << 0.0  << setw(pwi) << "\t"                                              // 21
@@ -523,31 +476,15 @@ void DataSink::writeStatData(EnvelopeBunch &beam, Vector_t FDext[], double sposH
 
 
             // Write head/reference particle/tail field information.
-                    << FDext[0](0) << setw(pwi) << "\t"                                       // 29 B-head x
-                    << FDext[0](1) << setw(pwi) << "\t"                                       // 30 B-head y
-                    << FDext[0](2) << setw(pwi) << "\t"                                       // 31 B-head z
-
-                    << FDext[1](0) << setw(pwi) << "\t"                                       // 32 E-head x
-                    << FDext[1](1) << setw(pwi) << "\t"                                       // 33 E-head y
-                    << FDext[1](2) << setw(pwi) << "\t"                                       // 34 E-head z
+                    << FDext[2](0) << setw(pwi) << "\t"                                       // 29 B-ref x
+                    << FDext[2](1) << setw(pwi) << "\t"                                       // 30 B-ref y
+                    << FDext[2](2) << setw(pwi) << "\t"                                       // 31 B-ref z
 
-                    << FDext[2](0) << setw(pwi) << "\t"                                       // 35 B-ref x
-                    << FDext[2](1) << setw(pwi) << "\t"                                       // 36 B-ref y
-                    << FDext[2](2) << setw(pwi) << "\t"                                       // 37 B-ref z
+                    << FDext[3](0) << setw(pwi) << "\t"                                       // 32 E-ref x
+                    << FDext[3](1) << setw(pwi) << "\t"                                       // 33 E-ref y
+                    << FDext[3](2) << setw(pwi) << "\t"                                       // 34 E-ref z
 
-                    << FDext[3](0) << setw(pwi) << "\t"                                       // 38 E-ref x
-                    << FDext[3](1) << setw(pwi) << "\t"                                       // 39 E-ref y
-                    << FDext[3](2) << setw(pwi) << "\t"                                       // 40 E-ref z
-
-                    << FDext[4](0) << setw(pwi) << "\t"                                       // 41 B-tail x
-                    << FDext[4](1) << setw(pwi) << "\t"                                       // 42 B-tail y
-                    << FDext[4](2) << setw(pwi) << "\t"                                       // 43 B-tail z
-
-                    << FDext[5](0) << setw(pwi) << "\t"                                       // 44 E-tail x
-                    << FDext[5](1) << setw(pwi) << "\t"                                       // 45 E-tail y
-                    << FDext[5](2) << setw(pwi) << "\t"                                       // 46 E-tail z
-
-                    << beam.get_dEdt() << setw(pwi) << "\t"                                   // 47 dE energy spread
+                    << beam.get_dEdt() << setw(pwi) << "\t"                                   // 35 dE energy spread
 
                     << endl;
 
@@ -574,214 +511,331 @@ void DataSink::writeSDDSHeader(ofstream &outputFile,
 
     string dateStr(simtimer.date());
     string timeStr(simtimer.time());
+    string indent("        ");
 
     outputFile << "SDDS1" << endl;
-    outputFile << "&description text=\"Statistics data " << OpalData::getInstance()->getInputFn() << " " << dateStr << " " << timeStr << "\" " << endl;
-    outputFile << ", contents=\"stat parameters\" &end" << endl;
-
-    outputFile << "&parameter name=processors, type=long, ";
-    outputFile << "description=\"Number of Cores used\" &end" << endl;
-
-    outputFile << "&parameter name=revision, type=string, "
-               << "description=\"git revision of opal\" &end\n";
-
-    outputFile << "&column name=t, type=double, units=s, ";
-    outputFile << "description=\"1 Time\" &end" << endl;
-    outputFile << "&column name=s, type=double, units=m, ";
-    outputFile << "description=\"2 Average Longitudinal Position\" &end" << endl;
-
-    outputFile << "&column name=numParticles, type=long, units=1, ";
-    outputFile << "description=\"3 Number of Macro Particles\" &end" << endl;
-    outputFile << "&column name=charge, type=double, units=1, ";
-    outputFile << "description=\"4 Bunch Charge\" &end" << endl;
-
-    outputFile << "&column name=energy, type=double, units=MeV, ";
-    outputFile << "description=\"5 Mean Energy\" &end" << endl;
-
-    outputFile << "&column name=rms_x, type=double, units=m , ";
-    outputFile << "description=\"6 RMS Beamsize in x  \" &end" << endl;
-    outputFile << "&column name=rms_y, type=double, units=m , ";
-    outputFile << "description=\"7 RMS Beamsize in y  \" &end" << endl;
-    outputFile << "&column name=rms_s, type=double, units=m , ";
-    outputFile << "description=\"8 RMS Beamsize in s  \" &end" << endl;
-
-    outputFile << "&column name=rms_px, type=double, units=1 , ";
-    outputFile << "description=\"9 RMS Momenta in x  \" &end" << endl;
-    outputFile << "&column name=rms_py, type=double, units=1 , ";
-    outputFile << "description=\"10 RMS Momenta in y  \" &end" << endl;
-    outputFile << "&column name=rms_ps, type=double, units=1 , ";
-    outputFile << "description=\"11 RMS Momenta in s  \" &end" << endl;
-
-    outputFile << "&column name=emit_x, type=double, units=m , ";
-    outputFile << "description=\"12 Normalized Emittance x  \" &end" << endl;
-    outputFile << "&column name=emit_y, type=double, units=m , ";
-    outputFile << "description=\"13 Normalized Emittance y  \" &end" << endl;
-    outputFile << "&column name=emit_s, type=double, units=m , ";
-    outputFile << "description=\"14 Normalized Emittance s  \" &end" << endl;
-
-    outputFile << "&column name=mean_x, type=double, units=m , ";
-    outputFile << "description=\"15 Mean Beam Position in x  \" &end" << endl;
-    outputFile << "&column name=mean_y, type=double, units=m , ";
-    outputFile << "description=\"16 Mean Beam Position in y  \" &end" << endl;
-    outputFile << "&column name=mean_s, type=double, units=m , ";
-    outputFile << "description=\"17 Mean Beam Position in s  \" &end" << endl;
-
-    outputFile << "&column name=max_x, type=double, units=m , ";
-    outputFile << "description=\"18 Max Beamsize in x  \" &end" << endl;
-    outputFile << "&column name=max_y, type=double, units=m , ";
-    outputFile << "description=\"19 Max Beamsize in y  \" &end" << endl;
-    outputFile << "&column name=max_s, type=double, units=m , ";
-    outputFile << "description=\"20 Max Beamsize in s  \" &end" << endl;
-
-    outputFile << "&column name=xpx, type=double, units=1 , ";
-    outputFile << "description=\"21 Correlation xpx  \" &end" << endl;
-    outputFile << "&column name=ypy, type=double, units=1 , ";
-    outputFile << "description=\"22 Correlation ypyy  \" &end" << endl;
-
-    outputFile << "&column name=zpz, type=double, units=1 , ";
-    outputFile << "description=\"23 Correlation zpz  \" &end" << endl;
-
-    outputFile << "&column name=notused1, type=double, units=1 , ";
-    outputFile << "description=\"24 notused1 in y  \" &end" << endl;
-
-    outputFile << "&column name=notused2, type=double, units=1 , ";
-    outputFile << "description=\"25 notused2 in y  \" &end" << endl;
-
-    if (Ippl::getNodes()>1) {
-      outputFile << "&column name=Dx, type=double, units=m , ";
-      outputFile << "description=\"26 Dispersion in x  \" &end" << endl;
-      outputFile << "&column name=DDx, type=double, units=1 , ";
-      outputFile << "description=\"27 Derivative of dispersion in x  \" &end" << endl;
-
-      outputFile << "&column name=Dy, type=double, units=m , ";
-      outputFile << "description=\"28 Dispersion in y  \" &end" << endl;
-      outputFile << "&column name=DDy, type=double, units=1 , ";
-      outputFile << "description=\"29 Derivative of dispersion in y  \" &end" << endl;
-    }
-    else {
-      outputFile << "&column name=Dx1, type=double, units=m , ";
-      outputFile << "description=\"26 Dispersion in x particle 1  \" &end" << endl;
-      outputFile << "&column name=Dx2, type=double, units=m , ";
-      outputFile << "description=\"27 Dispersion in x particle 2  \" &end" << endl;
-
-      outputFile << "&column name=Dx3, type=double, units=m , ";
-      outputFile << "description=\"28 Dispersion in x particle 3  \" &end" << endl;
-      outputFile << "&column name=Dx4, type=double, units=m , ";
-      outputFile << "description=\"29 Dispersion in x particle 4  \" &end" << endl;
-    }
-    outputFile << "&column name=Bx_head, type=double, units=T , ";
-    outputFile << "description=\"30 Bx-Field component of head particle  \" &end" << endl;
-    outputFile << "&column name=By_head, type=double, units=T , ";
-    outputFile << "description=\"31 By-Field component of head particle  \" &end" << endl;
-    outputFile << "&column name=Bz_head, type=double, units=T , ";
-    outputFile << "description=\"32 Bz-Field component of head particle  \" &end" << endl;
-
-    outputFile << "&column name=Ex_head, type=double, units=MV/m , ";
-    outputFile << "description=\"33 Ex-Field component of head particle  \" &end" << endl;
-    outputFile << "&column name=Ey_head, type=double, units=MV/m , ";
-    outputFile << "description=\"34 Ey-Field component of head particle  \" &end" << endl;
-    outputFile << "&column name=Ez_head, type=double, units=MV/m , ";
-    outputFile << "description=\"35 Ez-Field component of head particle  \" &end" << endl;
-
-    outputFile << "&column name=Bx_ref, type=double, units=T , ";
-    outputFile << "description=\"36 Bx-Field component of ref particle  \" &end" << endl;
-    outputFile << "&column name=By_ref, type=double, units=T , ";
-    outputFile << "description=\"37 By-Field component of ref particle  \" &end" << endl;
-    outputFile << "&column name=Bz_ref, type=double, units=T , ";
-    outputFile << "description=\"38 Bz-Field component of ref particle  \" &end" << endl;
-
-    outputFile << "&column name=Ex_ref, type=double, units=MV/m , ";
-    outputFile << "description=\"39 Ex-Field component of ref particle  \" &end" << endl;
-    outputFile << "&column name=Ey_ref, type=double, units=MV/m , ";
-    outputFile << "description=\"40 Ey-Field component of ref particle  \" &end" << endl;
-    outputFile << "&column name=Ez_ref, type=double, units=MV/m , ";
-    outputFile << "description=\"41 Ez-Field component of ref particle  \" &end" << endl;
-
-    outputFile << "&column name=Bx_tail, type=double, units=T , ";
-    outputFile << "description=\"42 Bx-Field component of tail particle  \" &end" << endl;
-    outputFile << "&column name=By_tail, type=double, units=T , ";
-    outputFile << "description=\"43 By-Field component of tail particle  \" &end" << endl;
-    outputFile << "&column name=Bz_tail, type=double, units=T , ";
-    outputFile << "description=\"44 Bz-Field component of tail particle  \" &end" << endl;
-
-    outputFile << "&column name=Ex_tail, type=double, units=MV/m , ";
-    outputFile << "description=\"45 Ex-Field component of tail particle  \" &end" << endl;
-    outputFile << "&column name=Ey_tail, type=double, units=MV/m , ";
-    outputFile << "description=\"46 Ey-Field component of tail particle  \" &end" << endl;
-    outputFile << "&column name=Ez_tail, type=double, units=MV/m , ";
-    outputFile << "description=\"47 Ez-Field component of tail particle  \" &end" << endl;
-
-    outputFile << "&column name=dE, type=double, units=MeV , ";
-    outputFile << "description=\"48 energy spread of the beam  \" &end" << endl;
-
-    outputFile << "&column name=partsOutside, type=double, units=1 , ";
-    outputFile << "description=\"49 outside n*sigma of the beam  \" &end" << endl;
-
-    unsigned int columnStart = 49;
+    outputFile << "&description\n"
+               << indent << "text=\"Statistics data '" << OpalData::getInstance()->getInputFn() << "' " << dateStr << "" << timeStr << "\",\n"
+               << indent << "contents=\"stat parameters\"\n"
+               << "&end\n";
+    outputFile << "&parameter\n"
+               << indent << "name=processors,\n"
+               << indent << "type=long,\n"
+               << indent << "description=\"Number of Cores used\"\n"
+               << "&end\n";
+    outputFile << "&parameter\n"
+               << indent << "name=revision,\n"
+               << indent << "type=string,\n"
+               << indent << "description=\"git revision of opal\" &end\n";
+    outputFile << "&column\n"
+               << indent << "name=t,\n"
+               << indent << "type=double,\n"
+               << indent << "units=ns,\n"
+               << indent << "description=\"1 Time\"\n"
+               << "&end\n";
+    outputFile << "&column\n"
+               << indent << "name=s,\n"
+               << indent << "type=double,\n"
+               << indent << "units=m,\n"
+               << indent << "description=\"2 Average Longitudinal Position\"\n"
+               << "&end\n";
+    outputFile << "&column\n"
+               << indent << "name=numParticles,\n"
+               << indent << "type=long,\n"
+               << indent << "units=1,\n"
+               << indent << "description=\"3 Number of Macro Particles\"\n"
+               << "&end\n";
+    outputFile << "&column\n"
+               << indent << "name=charge,\n"
+               << indent << "type=double,\n"
+               << indent << "units=1,\n"
+               << indent << "description=\"4 Bunch Charge\"\n"
+               << "&end\n";
+    outputFile << "&column\n"
+               << indent << "name=energy,\n"
+               << indent << "type=double,\n"
+               << indent << "units=MeV,\n"
+               << indent << "description=\"5 Mean Energy\"\n"
+               << "&end\n";
+    outputFile << "&column\n"
+               << indent << "name=rms_x,\n"
+               << indent << "type=double,\n"
+               << indent << "units=m,\n"
+               << indent << "description=\"6 RMS Beamsize in x\"\n"
+               << "&end\n";
+    outputFile << "&column\n"
+               << indent << "name=rms_y,\n"
+               << indent << "type=double,\n"
+               << indent << "units=m,\n"
+               << indent << "description=\"7 RMS Beamsize in y\"\n"
+               << "&end\n";
+    outputFile << "&column\n"
+               << indent << "name=rms_s,\n"
+               << indent << "type=double,\n"
+               << indent << "units=m,\n"
+               << indent << "description=\"8 RMS Beamsize in s\"\n"
+               << "&end\n";
+    outputFile << "&column\n"
+               << indent << "name=rms_px,\n"
+               << indent << "type=double,\n"
+               << indent << "units=1,\n"
+               << indent << "description=\"9 RMS Momenta in x\"\n"
+               << "&end\n";
+    outputFile << "&column\n"
+               << indent << "name=rms_py,\n"
+               << indent << "type=double,\n"
+               << indent << "units=1,\n"
+               << indent << "description=\"10 RMS Momenta in y\"\n"
+               << "&end\n";
+    outputFile << "&column\n"
+               << indent << "name=rms_ps,\n"
+               << indent << "type=double,\n"
+               << indent << "units=1,\n"
+               << indent << "description=\"11 RMS Momenta in s\"\n"
+               << "&end\n";
+    outputFile << "&column\n"
+               << indent << "name=emit_x,\n"
+               << indent << "type=double,\n"
+               << indent << "units=m,\n"
+               << indent << "description=\"12 Normalized Emittance x\"\n"
+               << "&end\n";
+    outputFile << "&column\n"
+               << indent << "name=emit_y,\n"
+               << indent << "type=double,\n"
+               << indent << "units=m,\n"
+               << indent << "description=\"13 Normalized Emittance y\"\n"
+               << "&end\n";
+    outputFile << "&column\n"
+               << indent << "name=emit_s,\n"
+               << indent << "type=double,\n"
+               << indent << "units=m,\n"
+               << indent << "description=\"14 Normalized Emittance s\"\n"
+               << "&end\n";
+    outputFile << "&column\n"
+               << indent << "name=mean_x,\n"
+               << indent << "type=double,\n"
+               << indent << "units=m,\n"
+               << indent << "description=\"15 Mean Beam Position in x\"\n"
+               << "&end\n";
+    outputFile << "&column\n"
+               << indent << "name=mean_y,\n"
+               << indent << "type=double,\n"
+               << indent << "units=m,\n"
+               << indent << "description=\"16 Mean Beam Position in y\"\n"
+               << "&end\n";
+    outputFile << "&column\n"
+               << indent << "name=mean_s,\n"
+               << indent << "type=double,\n"
+               << indent << "units=m,\n"
+               << indent << "description=\"17 Mean Beam Position in s\"\n"
+               << "&end\n";
+    outputFile << "&column\n"
+               << indent << "name=ref_x,\n"
+               << indent << "type=double,\n"
+               << indent << "units=m,\n"
+               << indent << "description=\"18 x coordinate of reference particle in lab cs\"\n"
+               << "&end\n";
+    outputFile << "&column\n"
+               << indent << "name=ref_y,\n"
+               << indent << "type=double,\n"
+               << indent << "units=m,\n"
+               << indent << "description=\"19 y coordinate of reference particle in lab cs\"\n"
+               << "&end\n";
+    outputFile << "&column\n"
+               << indent << "name=ref_z,\n"
+               << indent << "type=double,\n"
+               << indent << "units=m,\n"
+               << indent << "description=\"20 z coordinate of reference particle in lab cs\"\n"
+               << "&end\n";
+    outputFile << "&column\n"
+               << indent << "name=ref_px,\n"
+               << indent << "type=double,\n"
+               << indent << "units=1,\n"
+               << indent << "description=\"21 x momentum of reference particle in lab cs\"\n"
+               << "&end\n";
+    outputFile << "&column\n"
+               << indent << "name=ref_py,\n"
+               << indent << "type=double,\n"
+               << indent << "units=1,\n"
+               << indent << "description=\"22 y momentum of reference particle in lab cs\"\n"
+               << "&end\n";
+    outputFile << "&column\n"
+               << indent << "name=ref_pz,\n"
+               << indent << "type=double,\n"
+               << indent << "units=1,\n"
+               << indent << "description=\"23 z momentum of reference particle in lab cs\"\n"
+               << "&end\n";
+    outputFile << "&column\n"
+               << indent << "name=max_x,\n"
+               << indent << "type=double,\n"
+               << indent << "units=m,\n"
+               << indent << "description=\"24 Max Beamsize in x\"\n"
+               << "&end\n";
+    outputFile << "&column\n"
+               << indent << "name=max_y,\n"
+               << indent << "type=double,\n"
+               << indent << "units=m,\n"
+               << indent << "description=\"25 Max Beamsize in y\"\n"
+               << "&end\n";
+    outputFile << "&column\n"
+               << indent << "name=max_s,\n"
+               << indent << "type=double,\n"
+               << indent << "units=m,\n"
+               << indent << "description=\"26 Max Beamsize in s\"\n"
+               << "&end\n";
+    outputFile << "&column\n"
+               << indent << "name=xpx,\n"
+               << indent << "type=double,\n"
+               << indent << "units=1,\n"
+               << indent << "description=\"27 Correlation xpx\"\n"
+               << "&end\n";
+    outputFile << "&column\n"
+               << indent << "name=ypy,\n"
+               << indent << "type=double,\n"
+               << indent << "units=1,\n"
+               << indent << "description=\"28 Correlation ypyy\"\n"
+               << "&end\n";
+    outputFile << "&column\n"
+               << indent << "name=zpz,\n"
+               << indent << "type=double,\n"
+               << indent << "units=1,\n"
+               << indent << "description=\"29 Correlation zpz\"\n"
+               << "&end\n";
+    outputFile << "&column\n"
+               << indent << "name=Dx,\n"
+               << indent << "type=double,\n"
+               << indent << "units=m,\n"
+               << indent << "description=\"30 Dispersion in x\"\n"
+               << "&end\n";
+    outputFile << "&column\n"
+               << indent << "name=DDx,\n"
+               << indent << "type=double,\n"
+               << indent << "units=1,\n"
+               << indent << "description=\"31 Derivative of dispersion in x\"\n"
+               << "&end\n";
+    outputFile << "&column\n"
+               << indent << "name=Dy,\n"
+               << indent << "type=double,\n"
+               << indent << "units=m,\n"
+               << indent << "description=\"32 Dispersion in y\"\n"
+               << "&end\n";
+    outputFile << "&column\n"
+               << indent << "name=DDy,\n"
+               << indent << "type=double,\n"
+               << indent << "units=1,\n"
+               << indent << "description=\"33 Derivative of dispersion in y\"\n"
+               << "&end\n";
+    outputFile << "&column\n"
+               << indent << "name=Bx_ref,\n"
+               << indent << "type=double,\n"
+               << indent << "units=T,\n"
+               << indent << "description=\"34 Bx-Field component of ref particle\"\n"
+               << "&end\n";
+    outputFile << "&column\n"
+               << indent << "name=By_ref,\n"
+               << indent << "type=double,\n"
+               << indent << "units=T,\n"
+               << indent << "description=\"35 By-Field component of ref particle\"\n"
+               << "&end\n";
+    outputFile << "&column\n"
+               << indent << "name=Bz_ref,\n"
+               << indent << "type=double,\n"
+               << indent << "units=T,\n"
+               << indent << "description=\"36 Bz-Field component of ref particle\"\n"
+               << "&end\n";
+    outputFile << "&column\n"
+               << indent << "name=Ex_ref,\n"
+               << indent << "type=double,\n"
+               << indent << "units=MV/m,\n"
+               << indent << "description=\"37 Ex-Field component of ref particle\"\n"
+               << "&end\n";
+    outputFile << "&column\n"
+               << indent << "name=Ey_ref,\n"
+               << indent << "type=double,\n"
+               << indent << "units=MV/m,\n"
+               << indent << "description=\"38 Ey-Field component of ref particle\"\n"
+               << "&end\n";
+    outputFile << "&column\n"
+               << indent << "name=Ez_ref,\n"
+               << indent << "type=double,\n"
+               << indent << "units=MV/m,\n"
+               << indent << "description=\"39 Ez-Field component of ref particle\"\n"
+               << "&end\n";
+    outputFile << "&column\n"
+               << indent << "name=dE,\n"
+               << indent << "type=double,\n"
+               << indent << "units=MeV,\n"
+               << indent << "description=\"40 energy spread of the beam\"\n"
+               << "&end\n";
+    outputFile << "&column\n"
+               << indent << "name=dt,\n"
+               << indent << "type=double,\n"
+               << indent << "units=ns,\n"
+               << indent << "description=\"41 time step size\"\n"
+               << "&end\n";
+    outputFile << "&column\n"
+               << indent << "name=partsOutside,\n"
+               << indent << "type=double,\n"
+               << indent << "units=1,\n"
+               << indent << "description=\"42 outside n*sigma of the beam\"\n"
+               << "&end\n";
+
+    unsigned int columnStart = 43;
     if(Ippl::getNodes() == 1) {
-        outputFile << "&column name=R0_x, type=double, units=m , ";
-        outputFile << "description=\"50 R0 Particle Position in x  \" &end" << endl;
-        outputFile << "&column name=R0_y, type=double, units=m , ";
-        outputFile << "description=\"51 R0 Particle Position in y  \" &end" << endl;
-        outputFile << "&column name=R0_s, type=double, units=m , ";
-        outputFile << "description=\"52 R0 Particle Position in s  \" &end" << endl;
-        outputFile << "&column name=P0_x, type=double, units=1 , ";
-        outputFile << "description=\"53 P0 Particle Position in px  \" &end" << endl;
-        outputFile << "&column name=P0_y, type=double, units=1 , ";
-        outputFile << "description=\"54 P0 Particle Position in py  \" &end" << endl;
-        outputFile << "&column name=P0_s, type=double, units=1 , ";
-        outputFile << "description=\"55 P0 Particle Position in ps  \" &end" << endl;
-
-        outputFile << "&column name=R1_x, type=double, units=m , ";
-        outputFile << "description=\"56 R1 Particle Position in x  \" &end" << endl;
-        outputFile << "&column name=R1_y, type=double, units=m , ";
-        outputFile << "description=\"57 R1 Particle Position in y  \" &end" << endl;
-        outputFile << "&column name=R1_s, type=double, units=m , ";
-        outputFile << "description=\"58 R1 Particle Position in s  \" &end" << endl;
-        outputFile << "&column name=P1_x, type=double, units=1 , ";
-        outputFile << "description=\"59 P1 Particle Position in px  \" &end" << endl;
-        outputFile << "&column name=P1_y, type=double, units=1 , ";
-        outputFile << "description=\"60 P1 Particle Position in py  \" &end" << endl;
-        outputFile << "&column name=P1_s, type=double, units=1 , ";
-        outputFile << "description=\"61 P1 Particle Position in ps  \" &end" << endl;
-
-        outputFile << "&column name=R2_x, type=double, units=m , ";
-        outputFile << "description=\"62 R2 Particle Position in x  \" &end" << endl;
-        outputFile << "&column name=R2_y, type=double, units=m , ";
-        outputFile << "description=\"63 R2 Particle Position in y  \" &end" << endl;
-        outputFile << "&column name=R2_s, type=double, units=m , ";
-        outputFile << "description=\"64 R2 Particle Position in s  \" &end" << endl;
-        outputFile << "&column name=P2_x, type=double, units=1 , ";
-        outputFile << "description=\"65 P2 Particle Position in px  \" &end" << endl;
-        outputFile << "&column name=P2_y, type=double, units=1 , ";
-        outputFile << "description=\"66 P2 Particle Position in py  \" &end" << endl;
-        outputFile << "&column name=P2_s, type=double, units=1 , ";
-        outputFile << "description=\"67 P2 Particle Position in ps  \" &end" << endl;
-
-        outputFile << "&column name=R3_x, type=double, units=m , ";
-        outputFile << "description=\"68 R3 Particle Position in x  \" &end" << endl;
-        outputFile << "&column name=R3_y, type=double, units=m , ";
-        outputFile << "description=\"69 R3 Particle Position in y  \" &end" << endl;
-        outputFile << "&column name=R3_s, type=double, units=m , ";
-        outputFile << "description=\"70 R3 Particle Position in s  \" &end" << endl;
-        outputFile << "&column name=P3_x, type=double, units=1 , ";
-        outputFile << "description=\"71 P3 Particle Position in px  \" &end" << endl;
-        outputFile << "&column name=P3_y, type=double, units=1 , ";
-        outputFile << "description=\"72 P3 Particle Position in py  \" &end" << endl;
-        outputFile << "&column name=P3_s, type=double, units=1 , ";
-        outputFile << "description=\"73 P3 Particle Position in ps  \" &end" << endl;
-
-        columnStart = 73;
+        outputFile << "&column\n"
+                   << indent << "name=R0_x,\n"
+                   << indent << "type=double,\n"
+                   << indent << "units=m,\n"
+                   << indent << "description=\"43 R0 Particle position in x\""
+                   << "&end\n";
+        outputFile << "&column\n"
+                   << indent << "name=R0_y,\n"
+                   << indent << "type=double,\n"
+                   << indent << "units=m,\n"
+                   << indent << "description=\"44 R0 Particle position in y\"\n"
+                   << "&end\n";
+        outputFile << "&column\n"
+                   << indent << "name=R0_s,\n"
+                   << indent << "type=double,\n"
+                   << indent << "units=m,\n"
+                   << indent << "description=\"45 R0 Particle position in s\"\n"
+                   << "&end\n";
+        outputFile << "&column\n"
+                   << indent << "name=P0_x,\n"
+                   << indent << "type=double,\n"
+                   << indent << "units=1,\n"
+                   << indent << "description=\"46 R0 Particle momentum in x\"\n"
+                   << "&end\n";
+        outputFile << "&column\n"
+                   << indent << "name=P0_y,\n"
+                   << indent << "type=double,\n"
+                   << indent << "units=1,\n"
+                   << indent << "description=\"47 R0 Particle momentum in y\"\n"
+                   << "&end\n";
+        outputFile << "&column\n"
+                   << indent << "name=P0_s,\n"
+                   << indent << "type=double,\n"
+                   << indent << "units=1,\n"
+                   << indent << "description=\"48 R0 Particle momentum in s\"\n"
+                   << "&end\n";
+        columnStart = 49;
     }
 
     for (size_t i = 0; i < losses.size(); ++ i) {
-        outputFile << "&column name=" << losses[i].first << ", type=long, units=1, ";
-        outputFile << "description=\"" << columnStart++ << " " << losses[i].second << "\" &end" << endl;
+        outputFile << "&column\n"
+                   << indent << "name=" << losses[i].first << ",\n"
+                   << indent << "type=long,\n"
+                   << indent << "units=1,\n"
+                   << indent << "description=\"" << columnStart ++ << "Number of lost particles in element\"\n"
+                   << "&end\n";
     }
-    outputFile << "&data mode=ascii, no_row_counts=1 &end" << endl;
+    outputFile << "&data\n"
+               << indent << "mode=ascii,\n"
+               << indent << "no_row_counts=1\n"
+               << "&end\n";
 
     outputFile << Ippl::getNodes() << endl;
-    outputFile << PACKAGE_NAME << " " << PACKAGE_VERSION << " git rev. " << GIT_VERSION << endl;
+    outputFile << PACKAGE_NAME << " " << PACKAGE_VERSION_STR << " git rev. " << Util::getGitRevision() << endl;
 }
 
 
@@ -1135,80 +1189,7 @@ void DataSink::rewindLines(const std::string &fileName, size_t numberOfLines) co
     fs.close();
 }
 
-/** \brief
- *  rewind the SDDS file such that the spos of the last step is less or equal to maxSPos
- */
-unsigned int DataSink::rewindLinesSDDS(const std::string &fileName, double maxSPos) const {
-    std::string line;
-    std::queue<std::string> allLines;
-    std::fstream fs;
-    unsigned int numParameters = 0;
-    unsigned int numColumns = 0;
-    unsigned int sposColumnNr = 0;
-    double spos, lastSPos = -1.0;
-
-    boost::regex parameters("^&parameter name=");
-    boost::regex column("^&column name=([a-zA-Z0-9\\$_]+),");
-    boost::regex data("^&data mode=ascii");
-    boost::smatch match;
-
-    std::istringstream linestream;
-    fs.open (fileName.c_str(), std::fstream::in);
-
-    if (!fs.is_open()) return 0;
-
-    while (getline(fs, line)) {
-        allLines.push(line);
-    }
-    fs.close();
-
-
-    fs.open (fileName.c_str(), std::fstream::out);
-
-    if (!fs.is_open()) return 0;
-
-    do {
-        line = allLines.front();
-        allLines.pop();
-        fs << line << "\n";
-        if (boost::regex_search(line, match, parameters)) {
-            ++numParameters;
-        } else if (boost::regex_search(line, match, column)) {
-            ++numColumns;
-            if (match[1] == "s") {
-                sposColumnNr = numColumns;
-            }
-        }
-    } while (!boost::regex_search(line, match, data));
-
-    for (unsigned int i = 0; i < numParameters; ++ i) {
-        fs << allLines.front() << "\n";
-        allLines.pop();
-    }
-
-    while (allLines.size() > 0) {
-        line = allLines.front();
-        linestream.str(line);
-
-        for (unsigned int i = 0; i < sposColumnNr; ++ i) {
-            linestream >> spos;
-        }
-
-        if ((spos - maxSPos) > 1e-20 * Physics::c || (spos - lastSPos) < 1e-20 * Physics::c) break;
-
-        allLines.pop();
-
-        fs << line << "\n";
-
-        lastSPos = spos;
-    }
-
-    fs.close();
-
-    return allLines.size();
-}
-
 /***************************************************************************
  * $RCSfile: DataSink.cpp,v $   $Author: adelmann $
  * $Revision: 1.3 $   $Date: 2004/06/02 19:38:54 $
- ***************************************************************************/
+ ***************************************************************************/
\ No newline at end of file
diff --git a/src/Structure/DataSink.h b/src/Structure/DataSink.h
index e5a371fc7c49bd48b40837d41cc40cc2d83c2db3..9a14f93e08aac3aeae409315da3f12f7a5b93ed5 100644
--- a/src/Structure/DataSink.h
+++ b/src/Structure/DataSink.h
@@ -29,6 +29,7 @@
 #include <fstream>
 
 #include "Algorithms/PBunchDefs.h"
+#include "Utilities/Util.h"
 #include "H5hut.h"
 
 class PartBunch;
@@ -57,7 +58,6 @@ public:
 
     void reset();
 
-    void rewindLinesSDDS(size_t numberOfLines) const;
     void rewindLinesLBal(size_t numberOfLines) const;
     unsigned int rewindSDDStoSPos(double maxSpos) const;
 
@@ -87,21 +87,18 @@ public:
      *  - FDext[3] = E at reference particle location (in x, y and z).
      *  - FDext[4] = B at tail particle location (in x, y, and z).
      *  - FDext[5] = E at tail particle location (in x, y, and z).
-     *  \param sposHead Longitudinal position of the head particle.
-     *  \param sposRef Longitudinal position of the reference particle.
-     *  \param sposTail Longitudinal position of the tail particles.
      */
-    void doWriteStatData(PartBunch &beam, Vector_t FDext[], double sposHead, double sposRef, double sposTail, double E, const std::vector<std::pair<std::string, unsigned int> > &losses);
+    void doWriteStatData(PartBunch &beam, Vector_t FDext[], double E, const std::vector<std::pair<std::string, unsigned int> > &losses);
 
     /** \brief for OPAL-t
 
      */
-    void writeStatData(PartBunch &beam, Vector_t FDext[], double sposHead, double sposRef, double sposTail, const std::vector<std::pair<std::string, unsigned int> > &losses);
+    void writeStatData(PartBunch &beam, Vector_t FDext[], const std::vector<std::pair<std::string, unsigned int> > &losses = std::vector<std::pair<std::string, unsigned int> >());
 
-    /** \brief for OPAL-cycl
+    // /** \brief for OPAL-cycl
 
-     */
-    void writeStatData(PartBunch &beam, Vector_t FDext[], double sposHead, double sposRef, double sposTail, double E);
+    //  */
+    void writeStatData(PartBunch &beam, Vector_t FDext[], double E);
 
 
     /** \brief Write SDDS header.
@@ -126,11 +123,8 @@ public:
      *  - FDext[3] = E at reference particle location (in x, y and z).
      *  - FDext[4] = B at tail particle location (in x, y, and z).
      *  - FDext[5] = E at tail particle location (in x, y, and z).
-     *  \param sposHead Longitudinal position of the head particle.
-     *  \param sposRef Longitudinal position of the reference particle.
-     *  \param sposTail Longitudinal position of the tail particles.
      */
-    void writePhaseSpace(PartBunch &beam, Vector_t FDext[], double sposHead, double sposRef, double sposTail);
+    void writePhaseSpace(PartBunch &beam, Vector_t FDext[]);
 
     /** \brief Dumps phase space to H5 file in OPAL cyclotron calculation.
      *
@@ -210,7 +204,6 @@ private:
     static std::string convertToString(int number);
 
     void rewindLines(const std::string &fileName, size_t numberOfLines) const;
-    unsigned int rewindLinesSDDS(const std::string &fileName, double maxSPos) const;
 
     /** \brief First write to the statistics output file.
      *
@@ -242,7 +235,7 @@ private:
 #else
     h5_file_t *H5fileS_m;
 #endif
-    
+
     /// Current record, or time step, of H5 file.
     int H5call_m;
 
@@ -266,16 +259,6 @@ void DataSink::reset() {
     H5call_m = 0;
 }
 
-/** \brief
- *  delete the last 'numberOfLines' lines of the statistics file
- */
-inline
-void DataSink::rewindLinesSDDS(size_t numberOfLines) const {
-    if (Ippl::myNode() == 0) {
-        rewindLines(statFileName_m, numberOfLines);
-    }
-}
-
 /** \brief
  *   delete the last 'numberOfLines' lines of the load balance file
  */
@@ -292,7 +275,7 @@ void DataSink::rewindLinesLBal(size_t numberOfLines) const {
 inline
 unsigned int DataSink::rewindSDDStoSPos(double maxSPos) const {
     if (Ippl::myNode() == 0) {
-        return rewindLinesSDDS(statFileName_m, maxSPos);
+        return Util::rewindLinesSDDS(statFileName_m, maxSPos);
     }
 
     return 0;
@@ -315,4 +298,4 @@ std::string DataSink::convertToString(int number) {
 /***************************************************************************
  * $RCSfile: DataSink.h,v $   $Author: adelmann $
  * $Revision: 1.1.1.1 $   $Date: 2003/01/23 13:29:44 $
- ***************************************************************************/
+ ***************************************************************************/
\ No newline at end of file
diff --git a/src/Structure/FieldSolver.cpp b/src/Structure/FieldSolver.cpp
index 1f21d50844b983f6234693d172fa4fd2eac99d0a..67c9f6bd1150861b2fbdfe36fd5f0a9a189bb102 100644
--- a/src/Structure/FieldSolver.cpp
+++ b/src/Structure/FieldSolver.cpp
@@ -30,6 +30,7 @@
 #include "Expressions/SRefExpr.h"
 #include "Physics/Physics.h"
 #include "Utilities/OpalException.h"
+#include "Utilities/Util.h"
 #include "BoundaryGeometry.h"
 #include "AbstractObjects/Element.h"
 #include "Algorithms/PartBunch.h"
@@ -119,18 +120,19 @@ FieldSolver::FieldSolver():
     itsAttr[TOL] = Attributes::makeReal("TOL", "Tolerance for iterative solver", 1e-8);
     itsAttr[MAXITERS] = Attributes::makeReal("MAXITERS", "Maximum number of iterations of iterative solver", 100);
     itsAttr[PRECMODE]  = Attributes::makeString("PRECMODE", "Preconditioner Mode [STD | HIERARCHY | REUSE]", "HIERARCHY");
-    
+
     // AMR
 #ifdef HAVE_AMR_SOLVER
     itsAttr[AMRMAXLEVEL] = Attributes::makeReal("AMRMAXLEVEL", "Maximum number of levels in AMR", 0);
     itsAttr[AMRREFX] = Attributes::makeReal("AMRREFX", "Refinement ration in x-direction in AMR", 2);
-    itsAttr[AMRREFY] = Attributes::makeReal("AMRREFY", "Refinement ration in y-direction in AMR", 2); 
+    itsAttr[AMRREFY] = Attributes::makeReal("AMRREFY", "Refinement ration in y-direction in AMR", 2);
     itsAttr[AMRREFT] = Attributes::makeReal("AMRREFT", "Refinement ration in z-direction in AMR", 2);
     itsAttr[AMRSUBCYCLE] = Attributes::makeBool("AMRSUBCYCLE",
                                                 "Subcycling in time for refined levels in AMR", false);
     itsAttr[AMRMAXGRID] = Attributes::makeReal("AMRMAXGRID", "Maximum grid size in AMR", 16);
+
 #endif
-    
+
     mesh_m = 0;
     FL_m = 0;
     PL_m = 0;
@@ -226,7 +228,7 @@ void FieldSolver::initCartesianFields() {
     if(Attributes::getBool(itsAttr[PARFFTT]))
         decomp[2] = PARALLEL;
 
-    if(Attributes::getString(itsAttr[FSTYPE]) == "FFTPERIODIC") {
+    if(Util::toUpper(Attributes::getString(itsAttr[FSTYPE])) == "FFTPERIODIC") {
         decomp[0] = decomp[1] = SERIAL;
         decomp[2] = PARALLEL;
     }
@@ -240,12 +242,12 @@ void FieldSolver::initCartesianFields() {
 }
 
 bool FieldSolver::hasPeriodicZ() {
-  return Attributes::getString(itsAttr[BCFFTT])==std::string("PERIODIC");
+    return Util::toUpper(Attributes::getString(itsAttr[BCFFTT])) == std::string("PERIODIC");
 }
 
 #ifdef HAVE_AMR_SOLVER
 bool FieldSolver::isAMRSolver() {
-  return Attributes::getString(itsAttr[FSTYPE])==std::string("AMR");
+    return Util::toUpper(Attributes::getString(itsAttr[FSTYPE])) == std::string("AMR");
 }
 
 int FieldSolver::amrMaxLevel() {
@@ -278,8 +280,8 @@ void FieldSolver::initSolver(PartBunch &b) {
     std::string bcx = Attributes::getString(itsAttr[BCFFTX]);
     std::string bcy = Attributes::getString(itsAttr[BCFFTY]);
     std::string bcz = Attributes::getString(itsAttr[BCFFTT]);
-    
-    if(Attributes::getString(itsAttr[FSTYPE]) == "FFT") { 
+
+    if(Attributes::getString(itsAttr[FSTYPE]) == "FFT") {
         bool sinTrafo = ((bcx == std::string("DIRICHLET")) && (bcy == std::string("DIRICHLET")) && (bcz == std::string("DIRICHLET")));
         if(sinTrafo) {
             std::cout << "FFTBOX ACTIVE" << std::endl;
@@ -295,7 +297,7 @@ void FieldSolver::initSolver(PartBunch &b) {
                         geometries.push_back(geom);
                     tmp.clear();
                 } else
-                tmp += geoms[i];
+                    tmp += geoms[i];
             }
             BoundaryGeometry *ttmp = geometries[0];
             solver_m = new FFTBoxPoissonSolver(mesh_m, FL_m, Attributes::getString(itsAttr[GREENSF]), ttmp->getA());
@@ -306,14 +308,18 @@ void FieldSolver::initSolver(PartBunch &b) {
             itsBunch_m->set_meshEnlargement(Attributes::getReal(itsAttr[BBOXINCR]) / 100.0);
             fsType_m = "FFT";
         }
-  } else if (Attributes::getString(itsAttr[FSTYPE]) == "P3M") {
-      solver_m = new P3MPoissonSolver(mesh_m, FL_m, Attributes::getReal(itsAttr[RC]), Attributes::getReal(itsAttr[ALPHA]), Attributes::getReal(itsAttr[EPSILON]));
-      
-      PL_m->setAllCacheDimensions(Attributes::getReal(itsAttr[RC]));
-      PL_m->enableCaching();
-      
-      fsType_m = "P3M";
-    } else if(Attributes::getString(itsAttr[FSTYPE]) == "SAAMG") {
+    } else if (Util::toUpper(Attributes::getString(itsAttr[FSTYPE])) == "P3M") {
+        solver_m = new P3MPoissonSolver(mesh_m,
+                                        FL_m,
+                                        Attributes::getReal(itsAttr[RC]),
+                                        Attributes::getReal(itsAttr[ALPHA]),
+                                        Attributes::getReal(itsAttr[EPSILON]));
+
+        PL_m->setAllCacheDimensions(Attributes::getReal(itsAttr[RC]));
+        PL_m->enableCaching();
+
+        fsType_m = "P3M";
+    } else if(Util::toUpper(Attributes::getString(itsAttr[FSTYPE])) == "SAAMG") {
 #ifdef HAVE_SAAMG_SOLVER
         //we go over all geometries and add the Geometry Elements to the geometry list
         std::string geoms = Attributes::getString(itsAttr[GEOMETRY]);
@@ -340,7 +346,7 @@ void FieldSolver::initSolver(PartBunch &b) {
 #else
         INFOMSG("SAAMG Solver not enabled! Please build OPAL with -DENABLE_SAAMG_SOLVER=1" << endl);
         INFOMSG("switching to FFT solver..." << endl);
-        solver_m = new FFTPoissonSolver(mesh_m, FL_m, Attributes::getString(itsAttr[GREENSF]),bcz);
+        solver_m = new FFTPoissonSolver(mesh_m, FL_m, Util::toUpper(Attributes::getString(itsAttr[GREENSF])),bcz);
         fsType_m = "FFT";
 #endif
     }
@@ -348,72 +354,73 @@ void FieldSolver::initSolver(PartBunch &b) {
     else if (Attributes::getString(itsAttr[FSTYPE]) == "AMR") {
         Inform m("FieldSolver::initSolver-amr ");
         fsType_m = "AMR";
-	/* 
+
+	/*
         // Add the parsed AMR attributes to BoxLib (please check BoxLib/Src/C_AMRLib/Amr.cpp)
         ParmParse pp("amr");
-    
+
         pp.add("max_level", Attributes::getReal(itsAttr[AMRMAXLEVEL]));
-        
+
         pp.add("ref_ratio", (int)Attributes::getReal(itsAttr[AMRREFX])); //FIXME
-    
+
         pp.add("max_grid_size", Attributes::getReal(itsAttr[AMRMAXGRID]));
-    
+
         FieldLayout<3>::iterator_iv locDomBegin = FL_m->begin_iv();
         FieldLayout<3>::iterator_iv locDomEnd = FL_m->end_iv();
         FieldLayout<3>::iterator_dv globDomBegin = FL_m->begin_rdv();
         FieldLayout<3>::iterator_dv globDomEnd = FL_m->end_rdv();
-            
+
         BoxArray lev0_grids(Ippl::getNodes());
-    
+
         Array<int> procMap;
-        procMap.resize(lev0_grids.size()+1); // +1 is a historical thing, do not ask	
-        
+        procMap.resize(lev0_grids.size()+1); // +1 is a historical thing, do not ask
+
         // first iterate over the local owned domain(s)
         for(FieldLayout<3>::const_iterator_iv v_i = locDomBegin ; v_i != locDomEnd; ++v_i) {
             std::ostringstream stream;
-            stream << *((*v_i).second);	 
-            
+            stream << *((*v_i).second);
+
             std::pair<Box,unsigned int> res = getBlGrids(stream.str());
             lev0_grids.set(res.second,res.first);
             procMap[res.second] = Ippl::myNode();
         }
-        
+
         // then iterate over the non-local domain(s)
         for(FieldLayout<3>::iterator_dv v_i = globDomBegin ; v_i != globDomEnd; ++v_i) {
             std::ostringstream stream;
             stream << *((*v_i).second);
-            
+
             std::pair<Box,unsigned int> res = getBlGrids(stream.str());
             lev0_grids.set(res.second,res.first);
             procMap[res.second] = res.second;
         }
         procMap[lev0_grids.size()] = Ippl::myNode();
-        
+
         // This init call will cache the distribution map as determined by procMap
         // so that all data will end up on the right processor
         RealBox rb;
         Array<Real> prob_lo(3);
         Array<Real> prob_hi(3);
-        
+
         prob_lo[0] = -0.02; //-0.08);
         prob_lo[1] = -0.02; //-0.08);
         prob_lo[2] =  0.0; //-0.12);
         prob_hi[0] =  0.02; //0.08);
         prob_hi[1] =  0.02; //0.08);
         prob_hi[2] =  0.04; //0.16);
-        
+
         rb.setLo(prob_lo);
         rb.setHi(prob_hi);
-        
+
         int coord_sys = 0;
-            
+
         NDIndex<3> ipplDom = FL_m->getDomain();
-        
+
         Array<int> ncell(3);
         ncell[0] = ipplDom[0].length();
         ncell[1] = ipplDom[1].length();
         ncell[2] = ipplDom[2].length();
-        
+
         std::vector<int   > nr(3);
         std::vector<double> hr(3);
         std::vector<double> prob_lo_in(3);
@@ -422,18 +429,18 @@ void FieldSolver::initSolver(PartBunch &b) {
             hr[i] = (prob_hi[i] - prob_lo[i]) / ncell[i];
             prob_lo_in[i] = prob_lo[i];
         }
-        
+
         int maxLevel = -1;
         amrptr_m = new Amr(&rb,maxLevel,ncell,coord_sys);
-        
+
         if(amrptr_m)
             m << fsType_m << " solver: amrptr_m ready " << endl;
-        
+
         Real strt_time = 0.0;
         Real stop_time = 1.0;
-        
+
         amrptr_m->InitializeInit(strt_time, stop_time, &lev0_grids, &procMap);
-        
+
         if(amrptr_m)
             m << fsType_m << " solver: amrptr_m Init done " << endl;
 	*/
@@ -442,7 +449,7 @@ void FieldSolver::initSolver(PartBunch &b) {
     else {
         solver_m = 0;
         INFOMSG("no solver attached" << endl);
-    }    
+    }
 }
 
 bool FieldSolver::hasValidSolver() {
@@ -450,11 +457,11 @@ bool FieldSolver::hasValidSolver() {
 }
 
 Inform &FieldSolver::printInfo(Inform &os) const {
-    std::string fsType = Attributes::getString(itsAttr[FSTYPE]);
-    
+    std::string fsType = Util::toUpper(Attributes::getString(itsAttr[FSTYPE]));
+
     os << "* ************* F I E L D S O L V E R ********************************************** " << endl;
     os << "* FIELDSOLVER  " << getOpalName() << '\n'
-       << "* TYPE         " << Attributes::getString(itsAttr[FSTYPE]) << '\n'
+       << "* TYPE         " << fsType << '\n'
        << "* N-PROCESSORS " << Ippl::getNodes() << '\n'
        << "* MX           " << Attributes::getReal(itsAttr[MX])   << '\n'
        << "* MY           " << Attributes::getReal(itsAttr[MY])   << '\n'
@@ -465,14 +472,14 @@ Inform &FieldSolver::printInfo(Inform &os) const {
         os << "* RC           " << Attributes::getReal(itsAttr[RC]) << '\n'
            << "* ALPHA        " << Attributes::getReal(itsAttr[ALPHA]) << '\n'
            << "* EPSILON      " << Attributes::getReal(itsAttr[EPSILON]) << endl;
-    
+
 
     if(fsType == "FFT") {
-        os << "* GRRENSF      " << Attributes::getString(itsAttr[GREENSF]) << endl;
+        os << "* GRRENSF      " << Util::toUpper(Attributes::getString(itsAttr[GREENSF])) << endl;
     } else if (fsType == "SAAMG") {
         os << "* GEOMETRY     " << Attributes::getString(itsAttr[GEOMETRY]) << '\n'
-           << "* ITSOLVER     " << Attributes::getString(itsAttr[ITSOLVER])   << '\n'
-           << "* INTERPL      " << Attributes::getString(itsAttr[INTERPL])  << '\n'
+           << "* ITSOLVER     " << Util::toUpper(Attributes::getString(itsAttr[ITSOLVER]))   << '\n'
+           << "* INTERPL      " << Util::toUpper(Attributes::getString(itsAttr[INTERPL]))  << '\n'
            << "* TOL          " << Attributes::getReal(itsAttr[TOL])        << '\n'
            << "* MAXITERS     " << Attributes::getReal(itsAttr[MAXITERS]) << '\n'
            << "* PRECMODE     " << Attributes::getString(itsAttr[PRECMODE])   << endl;
@@ -509,4 +516,4 @@ Inform &FieldSolver::printInfo(Inform &os) const {
         os << *solver_m << endl;
     os << "* ********************************************************************************** " << endl;
     return os;
-}
+}
\ No newline at end of file
diff --git a/src/Structure/FieldSolver.h b/src/Structure/FieldSolver.h
index d241926b2d8ff3d3ec44d3ae25265114f0c623d5..6e7053271f510fa16462b2be2a45c29140865b43 100644
--- a/src/Structure/FieldSolver.h
+++ b/src/Structure/FieldSolver.h
@@ -89,17 +89,17 @@ public:
 
 #ifdef HAVE_AMR_SOLVER
     bool isAMRSolver();
-    
+
     int amrMaxLevel();
-    
+
     int amrRefRatioX();
-    
+
     int amrRefRatioY();
-    
+
     int amrRefRatioT();
-    
+
     bool amrSubCycling();
-    
+
     int amrMaxGridSize();
 #endif
 
@@ -137,4 +137,4 @@ inline Inform &operator<<(Inform &os, const FieldSolver &fs) {
     return fs.printInfo(os);
 }
 
-#endif // OPAL_FieldSolver_HH
+#endif // OPAL_FieldSolver_HH
\ No newline at end of file
diff --git a/src/Structure/H5PartWrapper.cpp b/src/Structure/H5PartWrapper.cpp
index 1980a94ddd5d733f900e084797f5192252e0c691..f2564f6d40266b009e28075b528ef6e188d14913 100644
--- a/src/Structure/H5PartWrapper.cpp
+++ b/src/Structure/H5PartWrapper.cpp
@@ -4,7 +4,7 @@
 
 #include "Structure/H5PartWrapper.h"
 
-#include "config.h"
+#include "OPALconfig.h"
 #include "Algorithms/PartBunch.h"
 #include "AbstractObjects/OpalData.h"
 #include "Utilities/Options.h"
@@ -39,6 +39,7 @@ H5PartWrapper::H5PartWrapper(const std::string &fileName, int restartStep, std::
     namespace fs = boost::filesystem;
 
     if (sourceFile == "") sourceFile = fileName_m;
+
     copyFile(sourceFile, restartStep, flags);
 
     open(H5_O_RDWR);
@@ -76,14 +77,19 @@ void H5PartWrapper::open(h5_int32_t flags) {
     assert (file_m != (void*)H5_ERR);
 #endif
 
-    
+
 }
 
 void H5PartWrapper::storeCavityInformation() {
-    if (startedFromExistingFile_m) return;
-
     /// Write number of Cavities with autophase information
     h5_int64_t nAutopPhaseCavities = OpalData::getInstance()->getNumberOfMaxPhases();
+    h5_int64_t nFormerlySavedAutoPhaseCavities = 0;
+
+    if (H5ReadFileAttribInt64(file_m, "nAutoPhaseCavities", &nFormerlySavedAutoPhaseCavities) == -1) {
+        nFormerlySavedAutoPhaseCavities = 0;
+    }
+
+    if (nFormerlySavedAutoPhaseCavities == nAutopPhaseCavities) return;
 
     WRITEFILEATTRIB(Int64, file_m, "nAutoPhaseCavities", &nAutopPhaseCavities, 1);
 
@@ -91,6 +97,8 @@ void H5PartWrapper::storeCavityInformation() {
     std::vector<MaxPhasesT>::iterator it = OpalData::getInstance()->getFirstMaxPhases();
     std::vector<MaxPhasesT>::iterator end = OpalData::getInstance()->getLastMaxPhases();
     for(; it < end; ++ it, ++ elementNumber) {
+        if (elementNumber <= nFormerlySavedAutoPhaseCavities) continue;
+
         std::string nameAttributeName = "Cav-" + std::to_string(elementNumber) + "-name";
         std::string valueAttributeName  = "Cav-" + std::to_string(elementNumber) + "-value";
 
@@ -550,4 +558,4 @@ size_t H5PartWrapper::getNumParticles() const {
 // mode:c
 // c-basic-offset: 4
 // indent-tabs-mode:nil
-// End:
+// End:
\ No newline at end of file
diff --git a/src/Structure/H5PartWrapperForPC.cpp b/src/Structure/H5PartWrapperForPC.cpp
index b29735f1b4addebc561795844740ee8c26029981..80a7cebc1dcdb0b274b3ee1182f7ed850c93f506 100644
--- a/src/Structure/H5PartWrapperForPC.cpp
+++ b/src/Structure/H5PartWrapperForPC.cpp
@@ -4,12 +4,11 @@
 
 #include "Structure/H5PartWrapperForPC.h"
 
-#include "config.h"
-#include "revision.h"
+#include "OPALconfig.h"
 #include "Algorithms/PartBunch.h"
 #include "AbstractObjects/OpalData.h"
 #include "Utilities/Options.h"
-#include "Utilities/Options.h"
+#include "Utilities/Util.h"
 #include "Physics/Physics.h"
 
 #include <boost/filesystem.hpp>
@@ -205,7 +204,7 @@ void H5PartWrapperForPC::readStepData(PartBunch& bunch, h5_ssize_t firstParticle
 
 void H5PartWrapperForPC::writeHeader() {
     std::stringstream OPAL_version;
-    OPAL_version << PACKAGE_NAME << " " << PACKAGE_VERSION << " git rev. " << GIT_VERSION;
+    OPAL_version << PACKAGE_NAME << " " << PACKAGE_VERSION_STR << " git rev. " << Util::getGitRevision();
     WRITESTRINGFILEATTRIB(file_m, "OPAL_version", OPAL_version.str().c_str());
 
     WRITESTRINGFILEATTRIB(file_m, "tUnit", "s");
@@ -283,7 +282,7 @@ void H5PartWrapperForPC::writeStepHeader(PartBunch& bunch, const std::map<std::s
     double   t          = bunch.getT();
     double   pathLength = bunch.getLPath();
     Vector_t rmin       = bunch.get_origin();
-    Vector_t rmax       = bunch.get_maxExtend();
+    Vector_t rmax       = bunch.get_maxExtent();
     Vector_t centroid   = bunch.get_centroid();
 
     Vector_t meanR = bunch.get_rmean();
@@ -293,10 +292,10 @@ void H5PartWrapperForPC::writeStepHeader(PartBunch& bunch, const std::map<std::s
     Vector_t vareps = bunch.get_norm_emit();
     Vector_t geomvareps = bunch.get_emit();
 
-    Vector_t RefPartR = bunch.RefPart_R;
-    Vector_t RefPartP = bunch.RefPart_P;
+    Vector_t RefPartR = bunch.RefPartR_m;
+    Vector_t RefPartP = bunch.RefPartP_m;
 
-    double meanEnergy = bunch.get_meanEnergy();
+    double meanEnergy = bunch.get_meanKineticEnergy();
     double energySpread = bunch.getdE();
     double I_0 = 4.0 * Physics::pi * Physics::epsilon_0 * Physics::c * bunch.getM() / bunch.getQ();
     double sigma = ((xsigma[0] * xsigma[0]) + (xsigma[1] * xsigma[1])) /
@@ -499,7 +498,7 @@ void H5PartWrapperForPC::writeStepData(PartBunch& bunch) {
         for(size_t i = 0; i < numLocalParticles; ++ i)
             f64buffer[i] =  bunch.Bf[i](0);
         WRITEDATA(Float64, file_m, "Bx", f64buffer);
-	
+
         for(size_t i = 0; i < numLocalParticles; ++ i)
             f64buffer[i] =  bunch.Bf[i](1);
         WRITEDATA(Float64, file_m, "By", f64buffer);
@@ -546,4 +545,4 @@ void H5PartWrapperForPC::writeStepData(PartBunch& bunch) {
                                                (h5_float64_t)bunch.get_hr()(1),
                                                (h5_float64_t)bunch.get_hr()(2)));
     }
-}
+}
\ No newline at end of file
diff --git a/src/Structure/H5PartWrapperForPS.cpp b/src/Structure/H5PartWrapperForPS.cpp
index 67e031f5324ff4e913b0343b546b29f6c0ceabfe..7a3664b9dbf240d74227a087e22ca62e54d31b97 100644
--- a/src/Structure/H5PartWrapperForPS.cpp
+++ b/src/Structure/H5PartWrapperForPS.cpp
@@ -4,13 +4,12 @@
 
 #include "Structure/H5PartWrapperForPS.h"
 
-#include "config.h"
-#include "revision.h"
+#include "OPALconfig.h"
 #include "Algorithms/PartBunch.h"
 #include "Algorithms/bet/EnvelopeBunch.h"
 #include "AbstractObjects/OpalData.h"
 #include "Utilities/Options.h"
-#include "Utilities/Options.h"
+#include "Utilities/Util.h"
 #include "Physics/Physics.h"
 
 #include <boost/filesystem.hpp>
@@ -176,7 +175,7 @@ void H5PartWrapperForPS::writeHeader() {
     h5_float64_t dphi = OpalData::getInstance()->getGlobalPhaseShift();
     std::stringstream OPAL_version;
 
-    OPAL_version << PACKAGE_NAME << " " << PACKAGE_VERSION << " git rev. " << GIT_VERSION;
+    OPAL_version << PACKAGE_NAME << " " << PACKAGE_VERSION_STR << " git rev. " << Util::getGitRevision();
     WRITESTRINGFILEATTRIB(file_m, "OPAL_version", OPAL_version.str().c_str());
 
     WRITESTRINGFILEATTRIB(file_m, "xUnit", "m");
@@ -241,13 +240,13 @@ void H5PartWrapperForPS::writeStepHeader(PartBunch& bunch,
     double   actPos   = ebunch->get_sPos();
     double   t        = ebunch->getT();
     Vector_t rmin     = ebunch->get_origin();
-    Vector_t rmax     = ebunch->get_maxExtend();
+    Vector_t rmax     = ebunch->get_maxExtent();
 
     Vector_t xsigma = ebunch->get_rrms();
     Vector_t psigma = ebunch->get_prms();
     Vector_t vareps = ebunch->get_norm_emit();
 
-    double meanEnergy = ebunch->get_meanEnergy();
+    double meanEnergy = ebunch->get_meanKineticEnergy();
 
     double mass = 1.0e-9 * ebunch->getM();
     double charge = ebunch->getCharge();
@@ -425,7 +424,7 @@ void H5PartWrapperForPS::stashPhaseSpaceEnvelope(EnvelopeBunch &bunch,
     stash_minP.push_back(ebunch->minP());
 
     //in MeV
-    stash_meanEnergy.push_back(ebunch->get_meanEnergy() * 1e-6);
+    stash_meanEnergy.push_back(ebunch->get_meanKineticEnergy() * 1e-6);
 
     stash_sposHead.push_back(sposHead);
     stash_sposRef.push_back(sposRef);
@@ -531,4 +530,4 @@ void H5PartWrapperForPS::dumpStashedPhaseSpaceEnvelope() {
         WRITEDATA(Float64, file_m, "pz", f64buffer);
         //rc = H5Fflush, file_m->file, rc = H5F_SCOPE_GLOBAL);
     }
-}
+}
\ No newline at end of file
diff --git a/src/Structure/H5PartWrapperForPT.cpp b/src/Structure/H5PartWrapperForPT.cpp
index ef486adc4ceae6856ea5dc92bec360427fcb9113..2520cb17e8fdc645de133838a97c5b733e1455b9 100644
--- a/src/Structure/H5PartWrapperForPT.cpp
+++ b/src/Structure/H5PartWrapperForPT.cpp
@@ -4,12 +4,11 @@
 
 #include "Structure/H5PartWrapperForPT.h"
 
-#include "config.h"
-#include "revision.h"
+#include "OPALconfig.h"
 #include "Algorithms/PartBunch.h"
 #include "AbstractObjects/OpalData.h"
 #include "Utilities/Options.h"
-#include "Utilities/Options.h"
+#include "Utilities/Util.h"
 #include "Physics/Physics.h"
 
 #include <boost/filesystem.hpp>
@@ -100,22 +99,33 @@ void H5PartWrapperForPT::readStepHeader(PartBunch& bunch) {
     READSTEPATTRIB(Float64, file_m, "TIME", &actualT);
     bunch.setT(actualT);
 
+    double spos;
+    READSTEPATTRIB(Float64, file_m, "SPOS", &spos);
+    bunch.set_sPos(spos);
+
     h5_int64_t ltstep;
     READSTEPATTRIB(Int64, file_m, "LocalTrackStep", &ltstep);
-    bunch.setLocalTrackStep((long long)ltstep);
+    bunch.setLocalTrackStep((long long)(ltstep + 1));
 
     h5_int64_t gtstep;
     READSTEPATTRIB(Int64, file_m, "GlobalTrackStep", &gtstep);
-    bunch.setGlobalTrackStep((long long)gtstep);
+    bunch.setGlobalTrackStep((long long)(gtstep + 1));
 
     Vector_t RefPartR;
     READSTEPATTRIB(Float64, file_m, "RefPartR", (h5_float64_t *)&RefPartR);
-    bunch.RefPart_R = RefPartR;
+    bunch.RefPartR_m = RefPartR;
 
     Vector_t RefPartP;
     READSTEPATTRIB(Float64, file_m, "RefPartP", (h5_float64_t *)&RefPartP);
-    bunch.RefPart_P = RefPartP;
-
+    bunch.RefPartP_m = RefPartP;
+
+    Vector_t TaitBryant;
+    READSTEPATTRIB(Float64, file_m, "TaitBryantAngles", (h5_float64_t *)&TaitBryant);
+    Quaternion rotTheta(cos(0.5 * TaitBryant[0]), 0, sin(0.5 * TaitBryant[0]), 0);
+    Quaternion rotPhi(cos(0.5 * TaitBryant[1]), sin(0.5 * TaitBryant[1]), 0, 0);
+    Quaternion rotPsi(cos(0.5 * TaitBryant[2]), 0, 0, sin(0.5 * TaitBryant[2]));
+    Quaternion rotation = rotTheta * (rotPhi * rotPsi);
+    bunch.toLabTrafo_m = CoordinateSystemTrafo(-rotation.conjugate().rotate(RefPartR), rotation);
 }
 
 void H5PartWrapperForPT::readStepData(PartBunch& bunch, h5_ssize_t firstParticle, h5_ssize_t lastParticle) {
@@ -169,9 +179,9 @@ void H5PartWrapperForPT::readStepData(PartBunch& bunch, h5_ssize_t firstParticle
         bunch.Q[n] = f64buffer[n];
     }
 
-    READDATA(Int32, file_m, "lastsection", i32buffer);
+    READDATA(Int32, file_m, "id", i32buffer);
     for(long int n = 0; n < numParticles; ++ n) {
-        bunch.LastSection[n] = i32buffer[n];
+        bunch.ID[n] = i32buffer[n];
     }
 
     REPORTONERROR(H5PartSetView(file_m, -1, -1));
@@ -179,34 +189,21 @@ void H5PartWrapperForPT::readStepData(PartBunch& bunch, h5_ssize_t firstParticle
 
 void H5PartWrapperForPT::writeHeader() {
     std::stringstream OPAL_version;
-    OPAL_version << PACKAGE_NAME << " " << PACKAGE_VERSION << " git rev. " << GIT_VERSION;
+    OPAL_version << PACKAGE_NAME << " " << PACKAGE_VERSION_STR << " git rev. " << Util::getGitRevision();
     WRITESTRINGFILEATTRIB(file_m, "OPAL_version", OPAL_version.str().c_str());
 
-    WRITESTRINGFILEATTRIB(file_m, "tUnit", "s");
-    WRITESTRINGFILEATTRIB(file_m, "xUnit", "m");
-    WRITESTRINGFILEATTRIB(file_m, "yUnit", "m");
-    WRITESTRINGFILEATTRIB(file_m, "zUnit", "m");
-    WRITESTRINGFILEATTRIB(file_m, "pxUnit", "#beta#gamma");
-    WRITESTRINGFILEATTRIB(file_m, "pyUnit", "#beta#gamma");
-    WRITESTRINGFILEATTRIB(file_m, "pzUnit", "#beta#gamma");
-    WRITESTRINGFILEATTRIB(file_m, "qUnit", "Cb");
-
-    WRITESTRINGFILEATTRIB(file_m, "idUnit", "1");
-    WRITESTRINGFILEATTRIB(file_m, "ptype", "1");
-    WRITESTRINGFILEATTRIB(file_m, "lastsection", "1");
-
     WRITESTRINGFILEATTRIB(file_m, "SPOSUnit", "m");
     WRITESTRINGFILEATTRIB(file_m, "TIMEUnit", "s");
     WRITESTRINGFILEATTRIB(file_m, "#gammaUnit", "1");
     WRITESTRINGFILEATTRIB(file_m, "ENERGYUnit", "MeV");
     WRITESTRINGFILEATTRIB(file_m, "#varepsilonUnit", "m rad");
-    WRITESTRINGFILEATTRIB(file_m, "#varepsilonrUnit", "m rad");
     WRITESTRINGFILEATTRIB(file_m, "#varepsilon-geomUnit", "m rad");
 
     WRITESTRINGFILEATTRIB(file_m, "#sigmaUnit", "1");
     WRITESTRINGFILEATTRIB(file_m, "RMSXUnit", "m");
-    WRITESTRINGFILEATTRIB(file_m, "RMSRUnit", "m");
+    WRITESTRINGFILEATTRIB(file_m, "centroidUnit", "m");
     WRITESTRINGFILEATTRIB(file_m, "RMSPUnit", "#beta#gamma");
+    WRITESTRINGFILEATTRIB(file_m, "MEANPUnit", "#beta#gamma");
 
     WRITESTRINGFILEATTRIB(file_m, "maxdEUnit", "MeV");
     WRITESTRINGFILEATTRIB(file_m, "max#phiUnit", "deg");
@@ -217,15 +214,8 @@ void H5PartWrapperForPT::writeHeader() {
     WRITESTRINGFILEATTRIB(file_m, "MASSUnit", "GeV");
     WRITESTRINGFILEATTRIB(file_m, "CHARGEUnit", "C");
 
-    WRITESTRINGFILEATTRIB(file_m, "spos-headUnit", "m");
-    WRITESTRINGFILEATTRIB(file_m, "E-headUnit", "MV/m");
-    WRITESTRINGFILEATTRIB(file_m, "B-headUnit", "T");
-    WRITESTRINGFILEATTRIB(file_m, "spos-refUnit", "m");
     WRITESTRINGFILEATTRIB(file_m, "E-refUnit", "MV/m");
     WRITESTRINGFILEATTRIB(file_m, "B-refUnit", "T");
-    WRITESTRINGFILEATTRIB(file_m, "spos-tailUnit", "m");
-    WRITESTRINGFILEATTRIB(file_m, "E-tailUnit", "MV/m");
-    WRITESTRINGFILEATTRIB(file_m, "B-tailUnit", "T");
 
     WRITESTRINGFILEATTRIB(file_m, "StepUnit", "1");
     WRITESTRINGFILEATTRIB(file_m, "LocalTrackStepUnit", "1");
@@ -260,7 +250,7 @@ void H5PartWrapperForPT::writeStepHeader(PartBunch& bunch, const std::map<std::s
     double   actPos   = bunch.get_sPos();
     double   t        = bunch.getT();
     Vector_t rmin     = bunch.get_origin();
-    Vector_t rmax     = bunch.get_maxExtend();
+    Vector_t rmax     = bunch.get_maxExtent();
     Vector_t centroid = bunch.get_centroid();
 
     Vector_t maxP(0.0);
@@ -270,11 +260,12 @@ void H5PartWrapperForPT::writeStepHeader(PartBunch& bunch, const std::map<std::s
     Vector_t psigma = bunch.get_prms();
     Vector_t vareps = bunch.get_norm_emit();
     Vector_t geomvareps = bunch.get_emit();
-    Vector_t RefPartR = bunch.RefPart_R;
-    Vector_t RefPartP = bunch.RefPart_P;
+    Vector_t RefPartR = bunch.RefPartR_m;
+    Vector_t RefPartP = bunch.RefPartP_m;
+    Vector_t TaitBryant = Util::getTaitBryantAngles(bunch.toLabTrafo_m.getRotation());
     Vector_t pmean = bunch.get_pmean();
 
-    double meanEnergy = bunch.get_meanEnergy();
+    double meanEnergy = bunch.get_meanKineticEnergy();
     double energySpread = bunch.getdE();
     double I_0 = 4.0 * Physics::pi * Physics::epsilon_0 * Physics::c * bunch.getM() / bunch.getQ();
     double sigma = ((xsigma[0] * xsigma[0]) + (xsigma[1] * xsigma[1])) /
@@ -305,6 +296,7 @@ void H5PartWrapperForPT::writeStepHeader(PartBunch& bunch, const std::map<std::s
     WRITESTEPATTRIB(Float64, file_m, "RefPartP", (h5_float64_t *)&RefPartP, 3);
     WRITESTEPATTRIB(Float64, file_m, "MEANP", (h5_float64_t *)&pmean, 3);
     WRITESTEPATTRIB(Float64, file_m, "RMSP", (h5_float64_t *)&psigma, 3);
+    WRITESTEPATTRIB(Float64, file_m, "TaitBryantAngles", (h5_float64_t *)&TaitBryant, 3);
 
     WRITESTEPATTRIB(Float64, file_m, "#varepsilon", (h5_float64_t *)&vareps, 3);
     WRITESTEPATTRIB(Float64, file_m, "#varepsilon-geom", (h5_float64_t *)&geomvareps, 3);
@@ -336,38 +328,15 @@ void H5PartWrapperForPT::writeStepHeader(PartBunch& bunch, const std::map<std::s
     WRITESTEPATTRIB(Int64, file_m, "SteptoLastInj", &SteptoLastInj, 1);
 
     try {
-        double sposHead = additionalStepAttributes.at("sposHead");
-        double sposRef = additionalStepAttributes.at("sposRef");
-        double sposTail = additionalStepAttributes.at("sposTail");
         Vector_t referenceB(additionalStepAttributes.at("B-ref_x"),
                             additionalStepAttributes.at("B-ref_z"),
                             additionalStepAttributes.at("B-ref_y"));
         Vector_t referenceE(additionalStepAttributes.at("E-ref_x"),
                             additionalStepAttributes.at("E-ref_z"),
                             additionalStepAttributes.at("E-ref_y"));
-        Vector_t headB(additionalStepAttributes.at("B-head_x"),
-                       additionalStepAttributes.at("B-head_z"),
-                       additionalStepAttributes.at("B-head_y"));
-        Vector_t headE(additionalStepAttributes.at("E-head_x"),
-                       additionalStepAttributes.at("E-head_z"),
-                       additionalStepAttributes.at("E-head_y"));
-        Vector_t tailB(additionalStepAttributes.at("B-tail_x"),
-                      additionalStepAttributes.at("B-tail_z"),
-                      additionalStepAttributes.at("B-tail_y"));
-        Vector_t tailE(additionalStepAttributes.at("E-tail_x"),
-                       additionalStepAttributes.at("E-tail_z"),
-                       additionalStepAttributes.at("E-tail_y"));
-
-        WRITESTEPATTRIB(Float64, file_m, "spos-head", &sposHead, 1);
-        WRITESTEPATTRIB(Float64, file_m, "spos-ref", &sposRef, 1);
-        WRITESTEPATTRIB(Float64, file_m, "spos-tail", &sposTail, 1);
 
         WRITESTEPATTRIB(Float64, file_m, "B-ref", (h5_float64_t *)&referenceB, 3);
         WRITESTEPATTRIB(Float64, file_m, "E-ref", (h5_float64_t *)&referenceE, 3);
-        WRITESTEPATTRIB(Float64, file_m, "B-head", (h5_float64_t *)&headB, 3);
-        WRITESTEPATTRIB(Float64, file_m, "E-head", (h5_float64_t *)&headE, 3);
-        WRITESTEPATTRIB(Float64, file_m, "B-tail", (h5_float64_t *)&tailB, 3);
-        WRITESTEPATTRIB(Float64, file_m, "E-tail", (h5_float64_t *)&tailE, 3);
     } catch (std::out_of_range & m) {
         ERRORMSG(m.what() << endl);
 
@@ -424,10 +393,6 @@ void H5PartWrapperForPT::writeStepData(PartBunch& bunch) {
         i32buffer[i] = (h5_int32_t) bunch.PType[i];
     WRITEDATA(Int32, file_m, "ptype", i32buffer);
 
-    for(size_t i = 0; i < numLocalParticles; ++ i)
-        i32buffer[i] =  bunch.LastSection[i];
-    WRITEDATA(Int32, file_m, "lastsection", i32buffer);
-
     if(Options::ebDump) {
         for(size_t i = 0; i < numLocalParticles; ++ i)
             f64buffer[i] =  bunch.Ef[i](0);
@@ -497,4 +462,4 @@ void H5PartWrapperForPT::writeStepData(PartBunch& bunch) {
         reportOnError(herr, __FILE__, __LINE__);
 
     }
-}
+}
\ No newline at end of file
diff --git a/src/Structure/OpalWake.cpp b/src/Structure/OpalWake.cpp
index d94136409b3f251c806d6ba3dee1faef8efffb88..c7aff6863d1d6bf6ed64738a03fb1e7e26c523c3 100644
--- a/src/Structure/OpalWake.cpp
+++ b/src/Structure/OpalWake.cpp
@@ -24,6 +24,7 @@
 #include "Utilities/OpalException.h"
 #include "AbsBeamline/ElementBase.h"
 #include "Utilities/OpalFilter.h"
+#include "Utilities/Util.h"
 
 extern Inform *gmsg;
 
@@ -58,37 +59,37 @@ OpalWake::OpalWake():
                "on an element."),
     wf_m(0) {
     itsAttr[TYPE] = Attributes::makeString
-                    ("TYPE", "Specifies the wake function: 1D-CSR, 1D-CSR-IGF, LONG-SHORT-RANGE, TRANSV-SHORT-RANGE, LONG-TRANSV-SHORT-RANGE");
+        ("TYPE", "Specifies the wake function: 1D-CSR, 1D-CSR-IGF, LONG-SHORT-RANGE, TRANSV-SHORT-RANGE, LONG-TRANSV-SHORT-RANGE");
 
     itsAttr[NBIN] = Attributes::makeReal
-                    ("NBIN", "Number of bins for the line density calculation");
+        ("NBIN", "Number of bins for the line density calculation");
 
     itsAttr[CONST_LENGTH] = Attributes::makeBool
-                            ("CONST_LENGTH", "True if the length of the Bunch is considered as constant");
+        ("CONST_LENGTH", "True if the length of the Bunch is considered as constant");
 
     itsAttr[CONDUCT] = Attributes::makeString
-                       ("CONDUCT", "Conductivity: DC, AC");
+        ("CONDUCT", "Conductivity: DC, AC");
 
     itsAttr[Z0] = Attributes::makeReal
-                  ("Z0", "Impedance of the beam pipe ");
+        ("Z0", "Impedance of the beam pipe ");
 
     itsAttr[FORM] = Attributes::makeString
-                    ("FORM", "The form of the  beam pipe: ROUND");
+        ("FORM", "The form of the  beam pipe: ROUND");
 
     itsAttr[RADIUS] = Attributes::makeReal
-                      ("RADIUS", "The radius of the beam pipe [m]");
+        ("RADIUS", "The radius of the beam pipe [m]");
 
     itsAttr[SIGMA] = Attributes::makeReal
-                     ("SIGMA", "Material constant dependant on the  beam pipe material");
+        ("SIGMA", "Material constant dependant on the  beam pipe material");
 
     itsAttr[TAU] = Attributes::makeReal
-                   ("TAU", "Material constant dependant on the  beam pipe material");
+        ("TAU", "Material constant dependant on the  beam pipe material");
 
     itsAttr[FILTERS] = Attributes::makeStringArray
-                       ("FILTERS", "List of filters to apply on line density");
+        ("FILTERS", "List of filters to apply on line density");
 
     itsAttr[FNAME] = Attributes::makeStringArray
-                     ("FNAME", "Filename of the wakefield file");
+        ("FNAME", "Filename of the wakefield file");
 
     OpalWake *defWake = clone("UNNAMED_WAKE");
     defWake->builtin = true;
@@ -109,7 +110,7 @@ OpalWake::OpalWake(const std::string &name, OpalWake *parent):
 
 
 OpalWake::~OpalWake() {
-    if(wf_m)
+    if (wf_m)
         delete wf_m;
 }
 
@@ -133,7 +134,7 @@ void OpalWake::execute() {
 OpalWake *OpalWake::find(const std::string &name) {
     OpalWake *wake = dynamic_cast<OpalWake *>(OpalData::getInstance()->find(name));
 
-    if(wake == 0) {
+    if (wake == 0) {
         throw OpalException("OpalWake::find()", "Wake \"" + name + "\" not found.");
     }
     return wake;
@@ -147,7 +148,7 @@ int OpalWake::getNumberOfBins() {
 
 void OpalWake::update() {
     // Set default name.
-    if(getOpalName().empty()) setOpalName("UNNAMED_WAKE");
+    if (getOpalName().empty()) setOpalName("UNNAMED_WAKE");
 }
 
 
@@ -165,37 +166,59 @@ void OpalWake::initWakefunction(ElementBase &element) {
     for(std::vector<std::string>::const_iterator fit = filters_str.begin(); fit != filters_str.end(); ++ fit) {
         OpalFilter *f = OpalFilter::find(*fit);
 
-        if(f) {
+        if (f) {
             f->initOpalFilter();
             filters.push_back(f->filter_m);
         }
     }
-    if(Attributes::getString(itsAttr[TYPE]) == "1D-CSR") {
-        wf_m = new CSRWakeFunction(getOpalName(), itsElement_m, filters, (int)(Attributes::getReal(itsAttr[NBIN])));
-    } else if(Attributes::getString(itsAttr[TYPE]) == "1D-CSR-IGF") {
-        wf_m = new CSRIGFWakeFunction(getOpalName(), itsElement_m, filters, (int)(Attributes::getReal(itsAttr[NBIN])));
-    } else if(Attributes::getString(itsAttr[TYPE]) == "LONG-SHORT-RANGE") {
-        int acMode = 1;
-        if(Attributes::getString(itsAttr[CONDUCT]).compare("DC") == 0) {
-            acMode = 2;
-        }
-        wf_m = new GreenWakeFunction(getOpalName(), itsElement_m, filters, (int)(Attributes::getReal(itsAttr[NBIN])),
-                                     (Attributes::getReal(itsAttr[Z0])), (Attributes::getReal(itsAttr[RADIUS])),
-                                     (Attributes::getReal(itsAttr[SIGMA])), acMode,
-                                     (Attributes::getReal(itsAttr[TAU])), 1, (Attributes::getBool(itsAttr[CONST_LENGTH])),
+
+    if (Util::toUpper(Attributes::getString(itsAttr[TYPE])) == "1D-CSR") {
+
+        wf_m = new CSRWakeFunction(getOpalName(),
+                                   itsElement_m,
+                                   filters,
+                                   (int)(Attributes::getReal(itsAttr[NBIN])));
+
+    } else if (Util::toUpper(Attributes::getString(itsAttr[TYPE])) == "1D-CSR-IGF") {
+
+        wf_m = new CSRIGFWakeFunction(getOpalName(),
+                                      itsElement_m,
+                                      filters,
+                                      (int)(Attributes::getReal(itsAttr[NBIN])));
+
+    } else if (Util::toUpper(Attributes::getString(itsAttr[TYPE])) == "LONG-SHORT-RANGE") {
+        int acMode = Util::toUpper(Attributes::getString(itsAttr[CONDUCT])) == "DC"? 2: 1;
+
+        wf_m = new GreenWakeFunction(getOpalName(),
+                                     itsElement_m,
+                                     filters,
+                                     (int)(Attributes::getReal(itsAttr[NBIN])),
+                                     Attributes::getReal(itsAttr[Z0]),
+                                     Attributes::getReal(itsAttr[RADIUS]),
+                                     Attributes::getReal(itsAttr[SIGMA]),
+                                     acMode,
+                                     Attributes::getReal(itsAttr[TAU]),
+                                     1,
+                                     Attributes::getBool(itsAttr[CONST_LENGTH]),
                                      Attributes::getString(itsAttr[FNAME]));
-    } else if(Attributes::getString(itsAttr[TYPE]) == "TRANSV-SHORT-RANGE") {
-        int acMode = 1;
-        if(Attributes::getString(itsAttr[CONDUCT]).compare("DC") == 0) {
-            acMode = 2;
-        }
 
-        wf_m = new GreenWakeFunction(getOpalName(), itsElement_m, filters, (int)(Attributes::getReal(itsAttr[NBIN])),
-                                     (Attributes::getReal(itsAttr[Z0])), (Attributes::getReal(itsAttr[RADIUS])),
-                                     (Attributes::getReal(itsAttr[SIGMA])), acMode,
-                                     (Attributes::getReal(itsAttr[TAU])), 0, (Attributes::getBool(itsAttr[CONST_LENGTH])),
+    } else if (Util::toUpper(Attributes::getString(itsAttr[TYPE])) == "TRANSV-SHORT-RANGE") {
+        int acMode = Util::toUpper(Attributes::getString(itsAttr[CONDUCT])) == "DC"? 2: 1;
+
+        wf_m = new GreenWakeFunction(getOpalName(),
+                                     itsElement_m,
+                                     filters,
+                                     (int)(Attributes::getReal(itsAttr[NBIN])),
+                                     Attributes::getReal(itsAttr[Z0]),
+                                     Attributes::getReal(itsAttr[RADIUS]),
+                                     Attributes::getReal(itsAttr[SIGMA]),
+                                     acMode,
+                                     Attributes::getReal(itsAttr[TAU]),
+                                     0,
+                                     Attributes::getBool(itsAttr[CONST_LENGTH]),
                                      Attributes::getString(itsAttr[FNAME]));
-    } else if(Attributes::getString(itsAttr[TYPE]) == "LONG-TRANSV-SHORT-RANGE") {
+
+    } else if (Attributes::getString(itsAttr[TYPE]) == "LONG-TRANSV-SHORT-RANGE") {
         //FIXME: NOT IMPLEMENTED YET!!!
     } else {
         wf_m = 0;
diff --git a/src/Structure/PriEmissionPhysics.cpp b/src/Structure/PriEmissionPhysics.cpp
index a505115d777145cd3da6c22ede8f20c5a31064d7..b4d91b79db0868500c75a349c6b6ac3f5b9f6912 100644
--- a/src/Structure/PriEmissionPhysics.cpp
+++ b/src/Structure/PriEmissionPhysics.cpp
@@ -82,11 +82,9 @@ void PriEmissionPhysics::Fieldemission(PartBunch *itsBunch, const double &fa, co
                 itsBunch->PType[count[pc]] = ParticleType::FIELDEMISSION;
                 itsBunch->TriID[count[pc]] = 0;
                 itsBunch->Q[count[pc]] = chargeScalFactor * itsBunch->getChargePerParticle();
-                itsBunch->LastSection[count[pc]] = 0;
                 itsBunch->Ef[count[pc]] = Vector_t(0.0);
                 itsBunch->Bf[count[pc]] = Vector_t(0.0);
                 itsBunch->dt[count[pc]] = itsBunch->getdT();
-                itsBunch->LastSection[count[pc]] = 0;
 
                 count[pc]++;
 
@@ -128,11 +126,9 @@ void PriEmissionPhysics::Fieldemission(PartBunch *itsBunch, const double &fa, co
                 itsBunch->PType[count[pc]] = ParticleType::FIELDEMISSION;
                 itsBunch->TriID[count[pc]] = 0;
                 itsBunch->Q[count[pc]] = chargeScalFactor * itsBunch->getChargePerParticle();
-                itsBunch->LastSection[count[pc]] = 0;
                 itsBunch->Ef[count[pc]] = Vector_t(0.0);
                 itsBunch->Bf[count[pc]] = Vector_t(0.0);
                 itsBunch->dt[count[pc]] = itsBunch->getdT();
-                itsBunch->LastSection[count[pc]] = 0;
                 count[pc]++;
 
             }
diff --git a/src/Structure/SecondaryEmissionPhysics.cpp b/src/Structure/SecondaryEmissionPhysics.cpp
index e2a8504b6f39f49bbb73bd28c7a96b8193eed1c9..df4220559130d5415cc6715282d987d8633cd8d5 100644
--- a/src/Structure/SecondaryEmissionPhysics.cpp
+++ b/src/Structure/SecondaryEmissionPhysics.cpp
@@ -5,6 +5,7 @@
 #include <sys/stat.h>
 #include "Algorithms/PartBunch.h"
 #include "Utilities/Options.h"
+#include "Utility/IpplTimings.h"
 
 using namespace myeps;
 using namespace Physics;
@@ -323,7 +324,6 @@ void SecondaryEmissionPhysics::nSec(const double &incEnergy,
 	itsBunch->TriID[lowMark] = 0;
 	//itsBunch->Q[lowMark] = incQ_l*seNum;// charge of simulation particle will be sum of secondaies
 	itsBunch->Q[lowMark] = incQ_l*seyNum;// charge of simulation particle will be multiplied by SEY.
-	itsBunch->LastSection[lowMark] = 0;
 	itsBunch->Ef[lowMark] = Vector_t(0.0);
 	itsBunch->Bf[lowMark] = Vector_t(0.0);
 	itsBunch->dt[lowMark] = itsBunch->getdT();
@@ -363,7 +363,6 @@ void SecondaryEmissionPhysics::nSec(const double &incEnergy,
 	    itsBunch->PType[lowMark+i] = ParticleType::NEWSECONDARY;
 	    itsBunch->TriID[lowMark+i] = 0;
 	    itsBunch->Q[lowMark+i] = incQ_l;
-	    itsBunch->LastSection[lowMark+i] = 0;
 	    itsBunch->Ef[lowMark+i] = Vector_t(0.0);
 	    itsBunch->Bf[lowMark+i] = Vector_t(0.0);
 	    itsBunch->dt[lowMark+i] = itsBunch->getdT();
@@ -580,7 +579,6 @@ void SecondaryEmissionPhysics::nSec(const double &incEnergy,  const double &cosT
 	itsBunch->PType[lowMark] = ParticleType::NEWSECONDARY;
 	itsBunch->TriID[lowMark] = 0;
 	itsBunch->Q[lowMark] = incQ_l*seyNum;
-	itsBunch->LastSection[lowMark] = 0;// fixme: what about last section !=0 ?
 	itsBunch->Ef[lowMark] = Vector_t(0.0);
 	itsBunch->Bf[lowMark] = Vector_t(0.0);
 	itsBunch->dt[lowMark] = itsBunch->getdT();
@@ -616,7 +614,6 @@ void SecondaryEmissionPhysics::nSec(const double &incEnergy,  const double &cosT
 	    itsBunch->PType[lowMark+i] = ParticleType::NEWSECONDARY;
 	    itsBunch->TriID[lowMark+i] = 0;
 	    itsBunch->Q[lowMark+i] = incQ_l;
-	    itsBunch->LastSection[lowMark+i] = 0;
 	    itsBunch->Ef[lowMark+i] = Vector_t(0.0);
 	    itsBunch->Bf[lowMark+i] = Vector_t(0.0);
 	    itsBunch->dt[lowMark+i] = itsBunch->getdT();
diff --git a/src/Structure/SurfacePhysics.cpp b/src/Structure/SurfacePhysics.cpp
index ecb5c1d4a023ccac451e37b1094183e8a75c3493..9a4ac3d774c14426da09844fa9c9c43cd4736ae3 100644
--- a/src/Structure/SurfacePhysics.cpp
+++ b/src/Structure/SurfacePhysics.cpp
@@ -21,6 +21,7 @@
 #include "Physics/Physics.h"
 #include "Utilities/OpalException.h"
 #include "AbsBeamline/ElementBase.h"
+#include "Utilities/Util.h"
 
 extern Inform *gmsg;
 
@@ -128,14 +129,18 @@ void SurfacePhysics::initSurfacePhysicsHandler(ElementBase &element) {
     *gmsg << "* ********************************************************************************** " << endl;
 
     itsElement_m = &element;
-    material_m = Attributes::getString(itsAttr[MATERIAL]);
+    material_m = Util::toUpper(Attributes::getString(itsAttr[MATERIAL]));
+
+    const std::string type = Util::toUpper(Attributes::getString(itsAttr[TYPE]));
+    if(type == "CCOLLIMATOR" ||
+       type == "COLLIMATOR" ||
+       type == "DEGRADER") {
 
-    if(Attributes::getString(itsAttr[TYPE]) == "CCOLLIMATOR" || Attributes::getString(itsAttr[TYPE]) == "COLLIMATOR" || Attributes::getString(itsAttr[TYPE]) == "DEGRADER") {
         handler_m = new CollimatorPhysics(getOpalName(), itsElement_m, material_m);
         *gmsg << *this << endl;
     } else {
         handler_m = 0;
-        INFOMSG("no surface physics handler attached, TYPE == " << Attributes::getString(itsAttr[TYPE]) << endl);
+        INFOMSG(getOpalName() + ": no surface physics handler attached, TYPE == " << Attributes::getString(itsAttr[TYPE]) << endl);
     }
 
 }
@@ -152,4 +157,4 @@ void SurfacePhysics::print(std::ostream &os) const {
        << "* SIGMA          " << Attributes::getReal(itsAttr[SIGMA]) << '\n'
        << "* TAU            " << Attributes::getReal(itsAttr[TAU]) << '\n';
     os << "* ********************************************************************************** " << std::endl;
-}
\ No newline at end of file
+}
diff --git a/src/Tables/CMakeLists.txt b/src/Tables/CMakeLists.txt
index ca17ee413d1b53268a2eeb570ef30a263303c909..52d71752317071d31203ef171be725e0dbd2ba47 100644
--- a/src/Tables/CMakeLists.txt
+++ b/src/Tables/CMakeLists.txt
@@ -23,4 +23,28 @@ include_directories (
   ${CMAKE_CURRENT_SOURCE_DIR}
 )
 
-add_sources(${_SRCS})
+add_opal_sources(${_SRCS})
+
+set (HDRS
+    AttList.h
+    AttWriter.h
+    CorrectionBase.h
+    Eigen.h
+    Envelope.h
+    Flatten.h
+    Insertion.h
+    List.h
+    MatrixCmd.h
+    Micado.h
+    Period.h
+    RangeSelector.h
+    Selector.h
+    Survey.h
+    TableTester.h
+    ThreadAll.h
+    ThreadBpm.h
+    Twiss3.h
+    Twiss.h
+)
+
+install (FILES ${HDRS} DESTINATION "${CMAKE_INSTALL_PREFIX}/include/Tables")
\ No newline at end of file
diff --git a/src/Track/CMakeLists.txt b/src/Track/CMakeLists.txt
index 8c218619776d69b8429b19fb5fc40c07e3222c06..fcd38a61eb0e5b74a5e06bcadad37cd3aa8c9281 100644
--- a/src/Track/CMakeLists.txt
+++ b/src/Track/CMakeLists.txt
@@ -12,4 +12,16 @@ include_directories (
   ${CMAKE_CURRENT_SOURCE_DIR}
 )
 
-add_sources(${_SRCS})
+add_opal_sources(${_SRCS})
+
+set (HDRS
+    TrackCmd.h
+    TrackEnd.h
+    Track.h
+    TrackParser.h
+    TrackRun.h
+    TrackSave.h
+    TrackStart.h
+)
+
+install (FILES ${HDRS} DESTINATION "${CMAKE_INSTALL_PREFIX}/include/Track")
\ No newline at end of file
diff --git a/src/Track/Track.cpp b/src/Track/Track.cpp
index 3bd2898c9703e4a7108d122e6855d6261248187a..4cd4fe7df6a355ae3fd86eb9fe28eec1542ce227 100644
--- a/src/Track/Track.cpp
+++ b/src/Track/Track.cpp
@@ -25,7 +25,7 @@
 // ------------------------------------------------------------------------
 
 Track *Track::block = 0;
-
+std::stack<Track*> Track::stashedTrack;
 
 /**
 
@@ -38,8 +38,8 @@ otherwise a new bunch is allocated in the dictionary.
 
 Track::Track(BeamSequence *u, const PartData &ref, const std::vector<double> & dt,
              const std::vector<unsigned long long> & maxtsteps, int stepsperturn,
-             const std::vector<double> & zStop, int timeintegrator, int nslices,
-             double t0, double dtScInit, double deltaTau):
+             double zStart, const std::vector<double> & zStop, int timeintegrator,
+             int nslices, double t0, double dtScInit, double deltaTau):
     reference(ref),
     use(u),
     parser(),
@@ -49,6 +49,7 @@ Track::Track(BeamSequence *u, const PartData &ref, const std::vector<double> & d
     t0_m(t0),
     localTimeSteps(maxtsteps),
     stepsPerTurn(stepsperturn),
+    zstart(zStart),
     zstop(zStop),
     timeIntegrator(timeintegrator) {
     if(nslices > 0) {
@@ -71,4 +72,19 @@ Track::Track(BeamSequence *u, const PartData &ref, const std::vector<double> & d
 
 
 Track::~Track()
-{}
\ No newline at end of file
+{}
+
+void Track::stash() {
+    PAssert(stashedTrack.size() == 0);
+
+    stashedTrack.push(block);
+    block = 0;
+}
+
+Track* Track::pop() {
+    delete block;
+    block = stashedTrack.top();
+    stashedTrack.pop();
+
+    return block;
+}
\ No newline at end of file
diff --git a/src/Track/Track.h b/src/Track/Track.h
index 424ab05a796945d846993a99f5a2913a911d190c..0f23d3091a8937b1fd5a59af97b340e0bb5aec88 100644
--- a/src/Track/Track.h
+++ b/src/Track/Track.h
@@ -20,6 +20,7 @@
 
 #include "Algorithms/PartData.h"
 #include "Track/TrackParser.h"
+#include <stack>
 
 class BeamSequence;
 class TrackParser;
@@ -37,8 +38,8 @@ public:
 
     Track(BeamSequence *, const PartData &, const std::vector<double> & dt,
           const std::vector<unsigned long long> & maxtsteps, int stepsperturn,
-          const std::vector<double> & zStop, int timeintegrator, int nslices,
-          double t0, double dtScInit, double deltaTau);
+          double zStart, const std::vector<double> & zStop, int timeintegrator,
+          int nslices, double t0, double dtScInit, double deltaTau);
     ~Track();
 
     /// The particle bunch to be tracked.
@@ -58,6 +59,9 @@ public:
     /// The block of track data.
     static Track *block;
 
+    static void stash();
+    static Track* pop();
+
     /// The initial timestep
     std::vector<double> dT;
 
@@ -74,6 +78,9 @@ public:
     /// The timsteps per revolution period. ONLY available for OPAL-cycl.
     int stepsPerTurn;
 
+    /// The location at which the simulation starts
+    double zstart;
+
     /// The location at which the simulation stops
     std::vector<double> zstop;
 
@@ -90,6 +97,8 @@ private:
     Track();
     Track(const Track &);
     void operator=(const Track &);
+
+    static std::stack<Track*> stashedTrack;
 };
 
 #endif // OPAL_Track_HH
\ No newline at end of file
diff --git a/src/Track/TrackCmd.cpp b/src/Track/TrackCmd.cpp
index 6d6b7488eded94a874c9f14e359fb6f16c187f93..7804d41908096ead74473e4e4e4b07289ef24046 100644
--- a/src/Track/TrackCmd.cpp
+++ b/src/Track/TrackCmd.cpp
@@ -44,6 +44,7 @@ namespace {
                       // for continuing with same step size in follow-up tracks.
         T0,           // The elapsed time (sec) of the bunch
         MAXSTEPS,     // The maximum timesteps we integrate
+        ZSTART,       // Defines a z-location [m] where the reference particle starts
         ZSTOP,        // Defines a z-location [m], after which the simulation stops when the last particles passes
         STEPSPERTURN, // Return the timsteps per revolution period. ONLY available for OPAL-cycl.
         TIMEINTEGRATOR, // the name of time integrator
@@ -71,6 +72,8 @@ TrackCmd::TrackCmd():
                         ("MAXSTEPS", "THE MAXIMUM NUMBER OF INTEGRATION STEPS DT, should be larger ZSTOP/(beta*c average)");
     itsAttr[STEPSPERTURN] = Attributes::makeReal
                             ("STEPSPERTURN", "THE TIME STEPS PER REVOLUTION PERIOD, ONLY FOR OPAL-CYCL", 720);
+    itsAttr[ZSTART] = Attributes::makeReal
+                      ("ZSTART", "Defines a z-location [m] where the reference particle starts", 0.0);
     itsAttr[ZSTOP] = Attributes::makeRealArray
                      ("ZSTOP", "Defines a z-location [m], after which the simulation stops when the last particles passes");
     itsAttr[TIMEINTEGRATOR] = Attributes::makeString
@@ -112,6 +115,11 @@ double TrackCmd::getT0() const {
     return Attributes::getReal(itsAttr[T0]);
 }
 
+double TrackCmd::getZSTART() const {
+    double zstart = Attributes::getReal(itsAttr[ZSTART]);
+    return zstart;
+}
+
 std::vector<double> TrackCmd::getZSTOP() const {
     std::vector<double> zstop = Attributes::getRealArray(itsAttr[ZSTOP]);
     if (zstop.size() == 0) {
@@ -173,6 +181,7 @@ void TrackCmd::execute() {
     double t0 = getT0();
     std::vector<unsigned long long> maxsteps = getMAXSTEPS();
     int    stepsperturn = getSTEPSPERTURN();
+    double zstart = getZSTART();
     std::vector<double> zstop = getZSTOP();
     int timeintegrator = getTIMEINTEGRATOR();
     int nslices = beam->getNumberOfSlices();
@@ -191,7 +200,7 @@ void TrackCmd::execute() {
     }
 
    // Execute track block.
-    Track::block = new Track(use, beam->getReference(), dt, maxsteps, stepsperturn, zstop, timeintegrator, nslices, t0, getDTSCINIT(), getDTAU());
+    Track::block = new Track(use, beam->getReference(), dt, maxsteps, stepsperturn, zstart, zstop, timeintegrator, nslices, t0, getDTSCINIT(), getDTAU());
     Track::block->parser.run();
 
     // Clean up.
diff --git a/src/Track/TrackCmd.h b/src/Track/TrackCmd.h
index 3ec85b35b25323afcf1839d98ed960a2b7478da6..c7d8ef7823665c6341baa876f49424f919a3b3ac 100644
--- a/src/Track/TrackCmd.h
+++ b/src/Track/TrackCmd.h
@@ -57,6 +57,9 @@ public:
     /// In OPAL-cycl, timestep is calculated by STEPSPERTURN, rather than given in TRACK command.
     int getSTEPSPERTURN() const;
 
+    /// location at which the simulation starts
+    double getZSTART() const;
+
     /// location at which the simulation stops
     std::vector<double> getZSTOP() const;
 
diff --git a/src/Track/TrackRun.cpp b/src/Track/TrackRun.cpp
index cb81077ba3f6dd8c998c2d5bdcb103c86cb2e76d..6f5a17bb40eecb5e804e22c18ab531d1074238b1 100644
--- a/src/Track/TrackRun.cpp
+++ b/src/Track/TrackRun.cpp
@@ -29,7 +29,8 @@
 #include "Algorithms/ParallelTTracker.h"
 #include "Algorithms/ParallelSliceTracker.h"
 #include "Algorithms/ParallelCyclotronTracker.h"
-#include "Algorithms/AutophaseTracker.h"
+#include "Algorithms/StatisticalErrors.h"
+#include "Algorithms/NilTracker.h"
 
 #include "Attributes/Attributes.h"
 #include "Beamlines/TBeamline.h"
@@ -40,6 +41,7 @@
 #include "Track/Track.h"
 #include "Utilities/OpalException.h"
 #include "Utilities/Round.h"
+#include "Utilities/Util.h"
 #include "Structure/Beam.h"
 #include "Structure/FieldSolver.h"
 #include "Structure/DataSink.h"
@@ -50,11 +52,16 @@
 #include "Distribution/Distribution.h"
 #include "Structure/BoundaryGeometry.h"
 
+#include "OPALconfig.h"
+#include "changes.h"
+
 #ifdef HAVE_AMR_SOLVER
 #define DIM 3
 #include <ParallelDescriptor.H>
 #endif
 
+#include <boost/algorithm/string.hpp>
+
 #include <fstream>
 #include <iomanip>
 
@@ -78,6 +85,7 @@ namespace {
         BOUNDARYGEOMETRY, // The boundary geometry
         DISTRIBUTION, // The particle distribution
         MULTIPACTING, // MULTIPACTING flag
+        OBJECTIVES,   // for which columns of an sdds file statistical errors should be considered
         // THE INTEGRATION TIMESTEP IN SEC
         SIZE
     };
@@ -97,7 +105,7 @@ TrackRun::TrackRun():
     phaseSpaceSink_m(NULL) {
     itsAttr[METHOD] = Attributes::makeString
                       ("METHOD", "Name of tracking algorithm to use:\n"
-                       "\t\t\t\"THIN\" (default) or \"THICK,PARALLEL-T,CYCLOTRON-T,PARALLEL-SLICE,AUTOPHASE\".", "THIN");
+                       "\t\t\t\"THIN\" (default) or \"THICK,OPAL-T,OPAL-T3D,OPAL-CYCL,OPAL-E\".", "THIN");
     itsAttr[TURNS] = Attributes::makeReal
                      ("TURNS", "Number of turns to be tracked; Number of neighboring bunches to be tracked in cyclotron", 1.0);
 
@@ -120,6 +128,9 @@ TrackRun::TrackRun():
                              ("DISTRIBUTION", "List of particle distributions to be used ");
     itsAttr[MULTIPACTING] = Attributes::makeBool
                             ("MULTIPACTING", "Multipacting flag, default: false. Set true to initialize primary particles according to BoundaryGeometry", false);
+    itsAttr[OBJECTIVES] = Attributes::makeStringArray
+                          ("OBJECTIVES", "List of SDDS columns that should be considered when evaluating statistical errors");
+
     opal = OpalData::getInstance();
 }
 
@@ -149,9 +160,41 @@ TrackRun *TrackRun::clone(const std::string &name) {
 
 
 void TrackRun::execute() {
+    std::string packageVersionStr = PACKAGE_VERSION_STR;
+    packageVersionStr.replace(packageVersionStr.find_first_of('.'), 1, "");
+    unsigned int posDot = packageVersionStr.find_first_of('.');
+    if (posDot != std::string::npos)
+        packageVersionStr = packageVersionStr.substr(0, posDot);
+
+    const int currentVersion = std::atoi(packageVersionStr.c_str()) * 100;
+
+    if (Options::version < currentVersion) {
+        unsigned int fileVersion = Options::version / 100;
+        bool newerChanges = false;
+        for (auto it = Versions::changes.begin(); it != Versions::changes.end(); ++ it) {
+            if (it->first > fileVersion) {
+                newerChanges = true;
+                break;
+            }
+        }
+        if (newerChanges) {
+            ERRORMSG("\n******************** V E R S I O N   M I S M A T C H ***********************\n" << endl);
+            for (auto it = Versions::changes.begin(); it != Versions::changes.end(); ++ it) {
+                if (it->first > fileVersion) {
+                    ERRORMSG(it->second << endl);
+                }
+            }
+            ERRORMSG("\nMake sure you do understand these changes and adjust your input file \n"
+                     << "accordingly. Then add\n"
+                     << "OPTION, VERSION = " << currentVersion << ";\n"
+                     << "to your input file. " << endl);
+            ERRORMSG("\n****************************************************************************\n" << endl);
+            throw OpalException("TrackRun::execute", "Version mismatch");
+        }
+    }
 
     // Get algorithm to use.
-    std::string method = Attributes::getString(itsAttr[METHOD]);
+    std::string method = Util::toUpper(Attributes::getString(itsAttr[METHOD]));
     if(method == "THIN") {
         //std::cerr << "  method == \"THIN\"" << std::endl;
         itsTracker = new ThinTracker(*Track::block->use->fetchLine(),
@@ -162,19 +205,17 @@ void TrackRun::execute() {
         itsTracker = new ThickTracker(*Track::block->use->fetchLine(),
                                       *Track::block->bunch, Track::block->reference,
                                       false, false);
-    } else if(method == "PARALLEL-SLICE") {
-        setupSliceTracker();
-    } else if(method == "PARALLEL-T") {
+    // } else if(method == "PARALLEL-SLICE" || method == "OPAL-E") {
+    //     setupSliceTracker();
+    } else if(method == "PARALLEL-T" || method == "OPAL-T") {
         setupTTracker();
     } else if(method == "PARALLEL-Z") {
         *gmsg << "  method == \"PARALLEL-Z\"" << endl;
 
-    } else if(method == "CYCLOTRON-T") {
+    } else if(method == "CYCLOTRON-T" || method == "OPAL-CYCL") {
         setupCyclotronTracker();
-    } else if(method == "AUTOPHASE") {
-        executeAutophaseTracker();
-
-        return;
+    } else if(method.substr(0,18) == "STATISTICAL-ERRORS") {
+        setupStatisticalErrors(method);
     } else {
         throw OpalException("TrackRun::execute()",
                             "Method name \"" + method + "\" unknown.");
@@ -223,123 +264,123 @@ void TrackRun::execute() {
 }
 
 void TrackRun::setupSliceTracker() {
-    OpalData::getInstance()->setInOPALEnvMode();
-    bool isFollowupTrack = opal->hasSLBunchAllocated() && !Options::scan;
-    if(!opal->hasSLBunchAllocated()) {
-        *gmsg << "* ********************************************************************************** " << endl;
-        *gmsg << "* Selected Tracking Method == PARALLEL-SLICE, NEW TRACK" << endl;
-        *gmsg << "* ********************************************************************************** " << endl;
-    } else if(isFollowupTrack) {
-        *gmsg << "* ********************************************************************************** " << endl;
-        *gmsg << "* Selected Tracking Method == PARALLEL-SLICE, FOLLOWUP TRACK" << endl;
-        *gmsg << "* ********************************************************************************** " << endl;
-    } else if(opal->hasSLBunchAllocated() && Options::scan) {
-        *gmsg << "* ********************************************************************************** " << endl;
-        *gmsg << "* Selected Tracking Method == PARALLEL-SLICE, SCAN TRACK" << endl;
-        *gmsg << "* ********************************************************************************** " << endl;
-    }
-
-    Beam   *beam = Beam::find(Attributes::getString(itsAttr[BEAM]));
-
-    if(opal->inRestartRun()) {
-        phaseSpaceSink_m = new H5PartWrapperForPS(opal->getInputBasename() + std::string(".h5"),
-                                                  opal->getRestartStep(),
-                                                  OpalData::getInstance()->getRestartFileName(),
-                                                  H5_O_WRONLY);
-    } else if (isFollowupTrack) {
-        phaseSpaceSink_m = new H5PartWrapperForPS(opal->getInputBasename() + std::string(".h5"),
-                                                  -1,
-                                                  opal->getInputBasename() + std::string(".h5"),
-                                                  H5_O_WRONLY);
-    } else {
-        phaseSpaceSink_m = new H5PartWrapperForPS(opal->getInputBasename() + std::string(".h5"),
-                                                  H5_O_WRONLY);
-    }
-
-    std::vector<std::string> distr_str = Attributes::getStringArray(itsAttr[DISTRIBUTION]);
-    const size_t numberOfDistributions = distr_str.size();
-    if (numberOfDistributions == 0) {
-        dist = Distribution::find(defaultDistribution);
-    } else {
-        dist = Distribution::find(distr_str.at(0));
-        dist->setNumberOfDistributions(numberOfDistributions);
-
-        if(numberOfDistributions > 1) {
-            *gmsg << "Found more than one distribution: ";
-            for(size_t i = 1; i < numberOfDistributions; ++ i) {
-                Distribution *d = Distribution::find(distr_str.at(i));
-
-                d->setNumberOfDistributions(numberOfDistributions);
-                distrs_m.push_back(d);
-
-                *gmsg << " " << distr_str.at(i);
-            }
-            *gmsg << endl;
-        }
-    }
-
-    fs = FieldSolver::find(Attributes::getString(itsAttr[FIELDSOLVER]));
-    fs->initCartesianFields();
-
-    double charge = 0.0;
-
-    if(!opal->hasSLBunchAllocated()) {
-        if(!opal->inRestartRun()) {
-
-            dist->CreateOpalE(beam, distrs_m, Track::block->slbunch, 0.0, 0.0);
-            opal->setGlobalPhaseShift(0.5 * dist->GetTEmission());
-
-        } else {
-            /***
-                reload slice distribution
-            */
-
-            dist->DoRestartOpalE(*Track::block->slbunch, beam->getNumberOfParticles(), opal->getRestartStep(), phaseSpaceSink_m);
-        }
-    } else {
-        charge = 1.0;
-    }
-
-    Track::block->slbunch->setdT(Track::block->dT.front());
-    // set the total charge
-    charge = beam->getCharge() * beam->getCurrent() / beam->getFrequency();
-    Track::block->slbunch->setCharge(charge);
-    // set coupling constant
-    double coefE = 1.0 / (4 * pi * epsilon_0);
-    Track::block->slbunch->setCouplingConstant(coefE);
-    //Track::block->slbunch->calcBeamParameters();
-
-
-    if(!opal->inRestartRun()) {
-        if(!opal->hasDataSinkAllocated()) {
-            opal->setDataSink(new DataSink(phaseSpaceSink_m));
-        } else {
-            ds = opal->getDataSink();
-            ds->changeH5Wrapper(phaseSpaceSink_m);
-        }
-    } else {
-        opal->setDataSink(new DataSink(phaseSpaceSink_m, -1));
-    }
-
-    ds = opal->getDataSink();
-
-    if(!opal->hasBunchAllocated())
-        *gmsg << *dist << endl;
-    *gmsg << *beam << endl;
-    *gmsg << *Track::block->slbunch  << endl;
-    *gmsg << "Phase space dump frequency is set to " << Options::psDumpFreq
-          << " Inputfile is " << opal->getInputFn() << endl;
-
-
-    findPhasesForMaxEnergy();
-
-    itsTracker = new ParallelSliceTracker(*Track::block->use->fetchLine(),
-                                          dynamic_cast<EnvelopeBunch &>(*Track::block->slbunch),
-                                          *ds,
-                                          Track::block->reference,
-                                          false, false,
-                                          Track::block->localTimeSteps.front(),
-                                          Track::block->zstop.front());
+    // OpalData::getInstance()->setInOPALEnvMode();
+    // bool isFollowupTrack = opal->hasSLBunchAllocated() && !Options::scan;
+    // if(!opal->hasSLBunchAllocated()) {
+    //     *gmsg << "* ********************************************************************************** " << endl;
+    //     *gmsg << "* Selected Tracking Method == PARALLEL-SLICE, NEW TRACK" << endl;
+    //     *gmsg << "* ********************************************************************************** " << endl;
+    // } else if(isFollowupTrack) {
+    //     *gmsg << "* ********************************************************************************** " << endl;
+    //     *gmsg << "* Selected Tracking Method == PARALLEL-SLICE, FOLLOWUP TRACK" << endl;
+    //     *gmsg << "* ********************************************************************************** " << endl;
+    // } else if(opal->hasSLBunchAllocated() && Options::scan) {
+    //     *gmsg << "* ********************************************************************************** " << endl;
+    //     *gmsg << "* Selected Tracking Method == PARALLEL-SLICE, SCAN TRACK" << endl;
+    //     *gmsg << "* ********************************************************************************** " << endl;
+    // }
+
+    // Beam   *beam = Beam::find(Attributes::getString(itsAttr[BEAM]));
+
+    // if(opal->inRestartRun()) {
+    //     phaseSpaceSink_m = new H5PartWrapperForPS(opal->getInputBasename() + std::string(".h5"),
+    //                                               opal->getRestartStep(),
+    //                                               OpalData::getInstance()->getRestartFileName(),
+    //                                               H5_O_WRONLY);
+    // } else if (isFollowupTrack) {
+    //     phaseSpaceSink_m = new H5PartWrapperForPS(opal->getInputBasename() + std::string(".h5"),
+    //                                               -1,
+    //                                               opal->getInputBasename() + std::string(".h5"),
+    //                                               H5_O_WRONLY);
+    // } else {
+    //     phaseSpaceSink_m = new H5PartWrapperForPS(opal->getInputBasename() + std::string(".h5"),
+    //                                               H5_O_WRONLY);
+    // }
+
+    // std::vector<std::string> distr_str = Attributes::getStringArray(itsAttr[DISTRIBUTION]);
+    // const size_t numberOfDistributions = distr_str.size();
+    // if (numberOfDistributions == 0) {
+    //     dist = Distribution::find(defaultDistribution);
+    // } else {
+    //     dist = Distribution::find(distr_str.at(0));
+    //     dist->setNumberOfDistributions(numberOfDistributions);
+
+    //     if(numberOfDistributions > 1) {
+    //         *gmsg << "Found more than one distribution: ";
+    //         for(size_t i = 1; i < numberOfDistributions; ++ i) {
+    //             Distribution *d = Distribution::find(distr_str.at(i));
+
+    //             d->setNumberOfDistributions(numberOfDistributions);
+    //             distrs_m.push_back(d);
+
+    //             *gmsg << " " << distr_str.at(i);
+    //         }
+    //         *gmsg << endl;
+    //     }
+    // }
+
+    // fs = FieldSolver::find(Attributes::getString(itsAttr[FIELDSOLVER]));
+    // fs->initCartesianFields();
+
+    // double charge = 0.0;
+
+    // if(!opal->hasSLBunchAllocated()) {
+    //     if(!opal->inRestartRun()) {
+
+    //         dist->createOpalE(beam, distrs_m, Track::block->slbunch, 0.0, 0.0);
+    //         opal->setGlobalPhaseShift(0.5 * dist->getTEmission());
+
+    //     } else {
+    //         /***
+    //             reload slice distribution
+    //         */
+
+    //         dist->doRestartOpalE(*Track::block->slbunch, beam->getNumberOfParticles(), opal->getRestartStep(), phaseSpaceSink_m);
+    //     }
+    // } else {
+    //     charge = 1.0;
+    // }
+
+    // Track::block->slbunch->setdT(Track::block->dT.front());
+    // // set the total charge
+    // charge = beam->getCharge() * beam->getCurrent() / beam->getFrequency();
+    // Track::block->slbunch->setCharge(charge);
+    // // set coupling constant
+    // double coefE = 1.0 / (4 * pi * epsilon_0);
+    // Track::block->slbunch->setCouplingConstant(coefE);
+    // //Track::block->slbunch->calcBeamParameters();
+
+
+    // if(!opal->inRestartRun()) {
+    //     if(!opal->hasDataSinkAllocated()) {
+    //         opal->setDataSink(new DataSink(phaseSpaceSink_m));
+    //     } else {
+    //         ds = opal->getDataSink();
+    //         ds->changeH5Wrapper(phaseSpaceSink_m);
+    //     }
+    // } else {
+    //     opal->setDataSink(new DataSink(phaseSpaceSink_m, -1));
+    // }
+
+    // ds = opal->getDataSink();
+
+    // if(!opal->hasBunchAllocated())
+    //     *gmsg << *dist << endl;
+    // *gmsg << *beam << endl;
+    // *gmsg << *Track::block->slbunch  << endl;
+    // *gmsg << "Phase space dump frequency is set to " << Options::psDumpFreq
+    //       << " Inputfile is " << opal->getInputFn() << endl;
+
+
+    // // findPhasesForMaxEnergy();
+
+    // itsTracker = new ParallelSliceTracker(*Track::block->use->fetchLine(),
+    //                                       dynamic_cast<EnvelopeBunch &>(*Track::block->slbunch),
+    //                                       *ds,
+    //                                       Track::block->reference,
+    //                                       false, false,
+    //                                       Track::block->localTimeSteps.front(),
+    //                                       Track::block->zstop.front());
 }
 
 void TrackRun::setupTTracker(){
@@ -410,7 +451,11 @@ void TrackRun::setupTTracker(){
 
     bool mpacflg = Attributes::getBool(itsAttr[MULTIPACTING]);
     if(!mpacflg) {
-        Track::block->bunch->setCharge(charge);
+        if (Track::block->bunch->getIfBeamEmitting()) {
+            Track::block->bunch->setChargeZeroPart(charge);
+        } else {
+            Track::block->bunch->setCharge(charge);
+        }
         // set coupling constant
         double coefE = 1.0 / (4 * pi * epsilon_0);
         Track::block->bunch->setCouplingConstant(coefE);
@@ -457,7 +502,7 @@ void TrackRun::setupTTracker(){
     }
 
     if (Track::block->bunch->getTotalNum() > 0) {
-        double spos = Track::block->bunch->get_sPos();
+        double spos = Track::block->bunch->get_sPos() + Track::block->zstart;
         auto &zstop = Track::block->zstop;
         auto &timeStep = Track::block->localTimeSteps;
         auto &dT = Track::block->dT;
@@ -472,30 +517,31 @@ void TrackRun::setupTTracker(){
         dT.erase(dT.begin(), dT.begin() + i);
 
         Track::block->bunch->setdT(dT.front());
+    } else {
+        Track::block->zstart = 0.0;
     }
 
     *gmsg << *beam << endl;
     *gmsg << *fs   << endl;
-    *gmsg << *Track::block->bunch  << endl;
 
-    findPhasesForMaxEnergy();
+    // findPhasesForMaxEnergy();
 
     *gmsg << level2
           << "Phase space dump frequency " << Options::psDumpFreq << " and "
           << "statistics dump frequency " << Options::statDumpFreq << " w.r.t. the time step." << endl;
-    
 #ifdef P3M_TEST
 
     Track::block->bunch->runTests();
 
 #else
+
     itsTracker = new ParallelTTracker(*Track::block->use->fetchLine(),
                                       dynamic_cast<PartBunch &>(*Track::block->bunch), *ds,
                                       Track::block->reference, false, false, Track::block->localTimeSteps,
-                                      Track::block->zstop, Track::block->timeIntegrator, Track::block->dT,  
-				      beam->getNumberOfParticles());
+                                      Track::block->zstart, Track::block->zstop, Track::block->dT);
 #endif
-    itsTracker->setMpacflg(mpacflg); // set multipacting flag in ParallelTTracker
+// #endif
+    // itsTracker->setMpacflg(mpacflg); // set multipacting flag in ParallelTTracker
 }
 
 void TrackRun::setupCyclotronTracker(){
@@ -547,7 +593,7 @@ void TrackRun::setupCyclotronTracker(){
     if(beam->getNumberOfParticles() < 3 || beam->getCurrent() == 0.0) {
         macrocharge = beam->getCharge() * q_e;
         macromass = beam->getMass();
-        dist->CreateOpalCycl(*Track::block->bunch,
+        dist->createOpalCycl(*Track::block->bunch,
                              beam->getNumberOfParticles(),
                              beam->getCurrent(),*Track::block->use->fetchLine(),
                              Options::scan);
@@ -565,14 +611,14 @@ void TrackRun::setupCyclotronTracker(){
             if(!opal->inRestartRun()) {
                 macrocharge /= beam->getNumberOfParticles();
                 macromass = beam->getMass() * macrocharge / (beam->getCharge() * q_e);
-                dist->CreateOpalCycl(*Track::block->bunch,
+                dist->createOpalCycl(*Track::block->bunch,
                                      beam->getNumberOfParticles(),
                                      beam->getCurrent(),
                                      *Track::block->use->fetchLine(),
                                      Options::scan);
 
             } else {
-                dist->DoRestartOpalCycl(*Track::block->bunch,
+                dist->doRestartOpalCycl(*Track::block->bunch,
                                         beam->getNumberOfParticles(),
                                         opal->getRestartStep(),
                                         specifiedNumBunch,
@@ -583,7 +629,7 @@ void TrackRun::setupCyclotronTracker(){
         } else if(opal->hasBunchAllocated() && Options::scan) {
             macrocharge /= beam->getNumberOfParticles();
             macromass = beam->getMass() * macrocharge / (beam->getCharge() * q_e);
-            dist->CreateOpalCycl(*Track::block->bunch,
+            dist->createOpalCycl(*Track::block->bunch,
                                  beam->getNumberOfParticles(),
                                  beam->getCurrent(),
                                  *Track::block->use->fetchLine(),
@@ -746,6 +792,48 @@ void TrackRun::setupCyclotronTracker(){
     }
 }
 
+void TrackRun::setupStatisticalErrors(const std::string & method) {
+    std::vector<std::string> tmp;
+    std::string arguments = method.substr(19,method.length() - 20);
+    boost::algorithm::split(tmp, arguments, boost::algorithm::is_any_of(","));
+
+    for (std::string &arg: tmp) {
+        boost::algorithm::trim(arg);
+    }
+
+    if (Util::toUpper(tmp.at(0)) == "PARALLEL-T" ||
+        Util::toUpper(tmp.at(0)) == "CYCLOTRON-T" ||
+        Util::toUpper(tmp.at(0)) == "PARALLEL-SLICE" ||
+        Util::toUpper(tmp.at(0)) == "THIN" ||
+        Util::toUpper(tmp.at(0)) == "THICK") {
+
+        if (tmp.size() != 3) {
+            throw OpalException("TrackRun::setupStatisticalErrors()",
+                                "number of arguments: " + std::to_string(tmp.size()) + " != 3");
+        }
+
+        if(!opal->hasBunchAllocated() && !Options::scan) {
+            itsTracker = new StatisticalErrors(*Track::block->use->fetchLine(),
+                                               Track::block->reference,
+                                               false,
+                                               false,
+                                               tmp.at(0),
+                                               std::stoul(tmp.at(1)),
+                                               std::stoul(tmp.at(2)),
+                                               Attributes::getStringArray(itsAttr[OBJECTIVES]));
+        } else {
+            itsTracker = new NilTracker(*Track::block->use->fetchLine(),
+                                        Track::block->reference,
+                                        false,
+                                        false);
+        }
+
+    } else {
+        throw OpalException("TrackRun::setupStatisticalErrors()",
+                            "unkonwn method '" + tmp.at(0) + "' provided");
+    }
+}
+
 void TrackRun::setupFieldsolver() {
     fs = FieldSolver::find(Attributes::getString(itsAttr[FIELDSOLVER]));
     fs->initCartesianFields();
@@ -819,17 +907,14 @@ double TrackRun::setDistributionParallelT(Beam *beam) {
                  * If this is an injected beam (rather than an emitted beam), we
                  * make sure it doesn't have any particles at z < 0.
                  */
-                Vector_t rMin;
-                Vector_t rMax;
-                Track::block->bunch->get_bounds(rMin, rMax);
 
-                opal->setGlobalPhaseShift(0.5 * dist->GetTEmission());
+                opal->setGlobalPhaseShift(0.5 * dist->getTEmission() + dist->getEmissionTimeShift());
             }
         } else {
             /*
              * Read in beam from restart file.
              */
-            dist->DoRestartOpalT(*Track::block->bunch, numberOfParticles, opal->getRestartStep(), phaseSpaceSink_m);
+            dist->doRestartOpalT(*Track::block->bunch, numberOfParticles, opal->getRestartStep(), phaseSpaceSink_m);
         }
     } else if (opal->hasBunchAllocated() && Options::scan) {
         /*
@@ -841,9 +926,8 @@ double TrackRun::setDistributionParallelT(Beam *beam) {
                                              numberOfParticles,
                                              Options::scan);
         Track::block->bunch->resetIfScan();
-        Track::block->bunch->LastSection = 1;
 
-        opal->setGlobalPhaseShift(0.5 * dist->GetTEmission());
+        opal->setGlobalPhaseShift(0.5 * dist->getTEmission() + dist->getEmissionTimeShift());
     }
 
     // Return charge per macroparticle.
@@ -851,97 +935,13 @@ double TrackRun::setDistributionParallelT(Beam *beam) {
 
 }
 
-void TrackRun::findPhasesForMaxEnergy(bool writeToFile) const {
-    if (Options::autoPhase == 0 ||
-        OpalData::getInstance()->inRestartRun() ||
-        OpalData::getInstance()->hasBunchAllocated()) return;
-
-    std::queue<unsigned long long> localTrackSteps;
-    std::queue<double> dtAllTracks;
-    std::queue<double> zStop;
-
-    const PartBunch *bunch = Track::block->bunch;
-    if (bunch == NULL) {
-        bunch = Track::block->slbunch;
-    }
-    if (bunch == NULL) {
-        throw OpalException("findPhasesForMaxEnergy()",
-                            "no valid PartBunch object found");
-    }
-
-    Vector_t meanP = bunch->get_pmean();
-    Vector_t meanR = bunch->get_rmean();
-    if (bunch->getTotalNum() == 0) {
-        meanP = bunch->get_pmean_Distribution();
-        meanR = 0.0;
-    }
-    AutophaseTracker apTracker(*Track::block->use->fetchLine(),
-                               Track::block->reference,
-                               bunch->getT(),
-                               meanR(2),
-                               meanP(2));
-
-    {
-        std::vector<unsigned long long>::const_iterator it = Track::block->localTimeSteps.begin();
-        std::vector<unsigned long long>::const_iterator end = Track::block->localTimeSteps.end();
-        for (; it != end; ++ it) {
-            localTrackSteps.push(*it);
-        }
-    }
-
-    {
-        std::vector<double>::const_iterator it = Track::block->dT.begin();
-        std::vector<double>::const_iterator end = Track::block->dT.end();
-        for (; it != end; ++ it) {
-            dtAllTracks.push(*it);
-        }
-    }
-
-    {
-        std::vector<double>::const_iterator it = Track::block->zstop.begin();
-        std::vector<double>::const_iterator end = Track::block->zstop.end();
-        for (; it != end; ++ it) {
-            zStop.push(*it);
-        }
-    }
-
-    apTracker.execute(dtAllTracks, zStop, localTrackSteps);
-
-    if (writeToFile) {
-        std::string fileName = OpalData::getInstance()->getInputBasename() + "_phases.in";
-        apTracker.save(fileName);
-    }
-}
-
-void TrackRun::executeAutophaseTracker() {
-
-    Beam *beam = Beam::find(Attributes::getString(itsAttr[BEAM]));
-    /*double charge =*/ setDistributionParallelT(beam);
-
-    Track::block->bunch->setdT(Track::block->dT.front());
-    Track::block->bunch->dtScInit_m = Track::block->dtScInit;
-    Track::block->bunch->deltaTau_m = Track::block->deltaTau;
-    Track::block->bunch->setT(Track::block->t0_m);
-
-    // Track::block->bunch->setCharge(charge);
-
-    double couplingConstant = 1.0 / (4 * pi * epsilon_0);
-    Track::block->bunch->setCouplingConstant(couplingConstant);
-
-
-    Track::block->bunch->calcBeamParameters();
-
-    findPhasesForMaxEnergy(true);
-
-}
-
 #ifdef HAVE_AMR_SOLVER
 void TrackRun::setupAMRSolver() {
     /*
     if ( fs->isAMRSolver() ) {
         *gmsg << *Track::block->bunch  << endl;
         *gmsg << *fs   << endl;
-        
+
         std::vector<double> x(3);
         std::vector<double> attr(11);
 
@@ -987,18 +987,18 @@ void TrackRun::setupAMRSolver() {
         //    may not currently be defined on the same processor as the grid
         //    that will hold them in the AMR world.
         fs->getAmrPtr()->RedistributeParticles();
-    
+
         // This part of the call must come after we add the particles
         // since this one calls post_init which does the field solve.
         double start_time = 0.0;
         double stop_time = 1.0;
-        
+
         fs->getAmrPtr()->FinalizeInit(start_time, stop_time);
         fs->getAmrPtr()->writePlotFile();
-    
+
         *gmsg << "A M R Initialization DONE" << endl;
     }
     */
 }
 
-#endif
+#endif
\ No newline at end of file
diff --git a/src/Track/TrackRun.h b/src/Track/TrackRun.h
index 446a6f852f420735d4818a0bc6f61781a4fa1d03..c2ad52c927c96133e46f25e087225ce458c18266 100644
--- a/src/Track/TrackRun.h
+++ b/src/Track/TrackRun.h
@@ -25,13 +25,13 @@
 	#include <fstream>
 	#include <iomanip>
 	#include <iostream>
-	#include <string>
 	#include <sstream>
 	#include <algorithm>
 	#include <iterator>
 	#include <utility>
 #endif
 
+#include <string>
 
 class Beam;
 class OpalData;
@@ -73,12 +73,11 @@ private:
     void setupSliceTracker();
     void setupTTracker();
     void setupCyclotronTracker();
+    void setupStatisticalErrors(const std::string & method);
 
     void setupFieldsolver();
 
     double setDistributionParallelT(Beam *beam);
-    void findPhasesForMaxEnergy(bool writeToFile = false) const;
-    void executeAutophaseTracker();
 
     // Pointer to tracking algorithm.
     Tracker *itsTracker;
diff --git a/src/Utilities/CMakeLists.txt b/src/Utilities/CMakeLists.txt
index 52dab8bc1fd7b7607b4a5c649181e3e4d709b2b1..8ad33aa57be7f5e274c28eb6059c2ab50ae24ae9 100644
--- a/src/Utilities/CMakeLists.txt
+++ b/src/Utilities/CMakeLists.txt
@@ -14,4 +14,18 @@ include_directories (
   ${CMAKE_CURRENT_SOURCE_DIR}
 )
 
-add_sources(${_SRCS})
+add_opal_sources(${_SRCS})
+
+set (HDRS
+    NumToStr.h
+    OpalException.h
+    OpalFilter.h
+    OpalSection.h
+    RegularExpression.h
+    Round.h
+    Timer.h
+    TpsWerrf.h
+    Truncate.h
+)
+
+install (FILES ${HDRS} DESTINATION "${CMAKE_INSTALL_PREFIX}/include/Utilities")
\ No newline at end of file
diff --git a/src/Utilities/OpalFilter.cpp b/src/Utilities/OpalFilter.cpp
index 9a5d8a23c636f914bfabfac5ba364f3d9c0edbf5..48854ce3e3f259e5667177fb7074f322a1a6110d 100644
--- a/src/Utilities/OpalFilter.cpp
+++ b/src/Utilities/OpalFilter.cpp
@@ -21,6 +21,7 @@
 #include "Attributes/Attributes.h"
 #include "Physics/Physics.h"
 #include "Utilities/OpalException.h"
+#include "Utilities/Util.h"
 #include "AbsBeamline/ElementBase.h"
 
 #include "Utility/IpplInfo.h"
@@ -99,7 +100,7 @@ OpalFilter::OpalFilter(const std::string &name, OpalFilter *parent):
 
 
 OpalFilter::~OpalFilter() {
-    if(filter_m)
+    if (filter_m)
         delete filter_m;
 }
 
@@ -123,7 +124,7 @@ void OpalFilter::execute() {
 OpalFilter *OpalFilter::find(const std::string &name) {
     OpalFilter *filter = dynamic_cast<OpalFilter *>(OpalData::getInstance()->find(name));
 
-    if(filter == 0) {
+    if (filter == 0) {
         throw OpalException("OpalFilter::find()", "OpalFilter \"" + name + "\" not found.");
     }
     return filter;
@@ -132,46 +133,47 @@ OpalFilter *OpalFilter::find(const std::string &name) {
 
 void OpalFilter::update() {
     // Set default name.
-    if(getOpalName().empty()) setOpalName("UNNAMED_FILTER");
+    if (getOpalName().empty()) setOpalName("UNNAMED_FILTER");
 }
 
 
 void OpalFilter::initOpalFilter() {
-    if(filter_m == 0) {
+    if (filter_m == 0) {
         *gmsg << "* ************* F I L T E R ************************************************************" << endl;
         *gmsg << "OpalFilter::initOpalFilterfunction " << endl;
         *gmsg << "* **********************************************************************************" << endl;
 
-        if(Attributes::getString(itsAttr[TYPE]) == "Savitzky-Golay") {
+        std::string type = Util::toUpper(Attributes::getString(itsAttr[TYPE]));
+        if (type == "SAVITZKY-GOLAY") {
             int num_points = (int)(Attributes::getReal(itsAttr[NPOINTS]));
             int num_points_left = (int)(Attributes::getReal(itsAttr[NLEFT]));
             int num_points_right = (int)(Attributes::getReal(itsAttr[NRIGHT]));
             int polynomial_order = std::abs((int)(Attributes::getReal(itsAttr[POLYORDER])));
 
             Inform svg("Savitzky-Golay: ");
-            if(num_points_left < 0) {
+            if (num_points_left < 0) {
                 svg << "Number of points to the left negative; using default (" << NLEFT_DEFAULT << ");" << endl;
                 num_points_left = NLEFT_DEFAULT;
             }
-            if(num_points_right < 0) {
+            if (num_points_right < 0) {
                 svg << "Number of points to the right negative; using default (" << NRIGHT_DEFAULT << ");" << endl;
                 num_points_right = NRIGHT_DEFAULT;
             }
-            if(num_points < num_points_left + num_points_right) {
+            if (num_points < num_points_left + num_points_right) {
                 svg << "Total number of points small than sum of the ones to the left and to the right plus 1; using default (NLEFT + NRIGHT + 1);" << endl;
                 num_points = num_points_left + num_points_right + 1;
             }
-            if(polynomial_order > num_points_left + num_points_right) {
+            if (polynomial_order > num_points_left + num_points_right) {
                 svg << "Polynomial order bigger than sum of points to the left and to the right; using default (NLEFT + NRIGHT);" << endl;
                 polynomial_order = num_points_left + num_points_right;
             }
 
             filter_m = new SavitzkyGolayFilter(num_points, num_points_left, num_points_right, polynomial_order);
-        } else if(Attributes::getString(itsAttr[TYPE]) == "FixedFFTLowPass") {
+        } else if (type == "FIXEDFFTLOWPASS") {
             filter_m = new FixedFFTLowPassFilter(std::abs((int)(Attributes::getReal(itsAttr[NFREQ]))));
-        } else if(Attributes::getString(itsAttr[TYPE]) == "RelativeFFTLowPass") {
+        } else if (type == "RELATIVEFFTLOWPASS") {
             filter_m = new RelativeFFTLowPassFilter(std::abs(Attributes::getReal(itsAttr[THRESHOLD])));
-        } else if(Attributes::getString(itsAttr[TYPE]) == "Stencil") {
+        } else if (type == "STENCIL") {
             filter_m = new IlyaPogorelovFilter();
         } else {
             filter_m = 0;
diff --git a/src/Utilities/OpalSection.cpp b/src/Utilities/OpalSection.cpp
index dcda27dd4b15232aed44c3a1d2cc7f5496970a95..907478560971a3103ea419ea116ccb8a7c63e1cc 100644
--- a/src/Utilities/OpalSection.cpp
+++ b/src/Utilities/OpalSection.cpp
@@ -29,7 +29,7 @@ OpalSection::OpalSection(const CompVec &elements, const double &start, const dou
     for(CompVec::const_iterator clit = elements_m.begin(); clit != elements_m.end(); ++ clit) {
         if((*clit)->bends()) {
             bends_m = true;
-            (*clit)->getOrientation(orientation_m, exit_face_angle_m);
+            // (*clit)->getOrientation(orientation_m, exit_face_angle_m);
         }
         if((*clit)->hasWake()) {
             if(has_wake_m && wakefunction_m != (*clit)->getWake()) {
@@ -185,4 +185,4 @@ bool OpalSection::doDipoleFieldsOverlap() const {
         }
     }
     return (numFieldContributions > 1);
-}
\ No newline at end of file
+}
diff --git a/src/ValueDefinitions/BoolConstant.cpp b/src/ValueDefinitions/BoolConstant.cpp
index baae151fd91a393f62385b9fd34d88117ce8a9ec..7c0f506e3db6e4048b971ccc5e4ec6e02db2b353 100644
--- a/src/ValueDefinitions/BoolConstant.cpp
+++ b/src/ValueDefinitions/BoolConstant.cpp
@@ -62,3 +62,7 @@ void BoolConstant::print(std::ostream &os) const {
     os << "BOOL CONST " << getOpalName() << '=' << itsAttr[0] << ';';
     os << std::endl;
 }
+
+void BoolConstant::printValue(std::ostream &os) const {
+    os << itsAttr[0];
+}
\ No newline at end of file
diff --git a/src/ValueDefinitions/BoolConstant.h b/src/ValueDefinitions/BoolConstant.h
index 387ce34d9a03dc989274c7ebbe784d755ea863c1..c0f287461070561f54e0d1ec214f9ce01a9504be 100644
--- a/src/ValueDefinitions/BoolConstant.h
+++ b/src/ValueDefinitions/BoolConstant.h
@@ -43,6 +43,9 @@ public:
     /// Print the constant.
     virtual void print(std::ostream &) const;
 
+    /// Print its value
+    virtual void printValue(std::ostream &os) const;
+
     /// Return value.
     virtual bool getBool() const;
 
@@ -56,4 +59,4 @@ private:
     BoolConstant(const std::string &name, BoolConstant *parent);
 };
 
-#endif // OPAL_BoolConstant_HH
+#endif // OPAL_BoolConstant_HH
\ No newline at end of file
diff --git a/src/ValueDefinitions/CMakeLists.txt b/src/ValueDefinitions/CMakeLists.txt
index 3a7402b0ce1b4ae3b9f72c70bd8170dcf8891c13..82f11d4ed96d60e485a8d10d5830c737f811dc95 100644
--- a/src/ValueDefinitions/CMakeLists.txt
+++ b/src/ValueDefinitions/CMakeLists.txt
@@ -10,4 +10,14 @@ include_directories (
   ${CMAKE_CURRENT_SOURCE_DIR}
 )
 
-add_sources(${_SRCS})
+add_opal_sources(${_SRCS})
+
+set (HDRS
+    BoolConstant.h
+    RealConstant.h
+    RealVariable.h
+    RealVector.h
+    StringConstant.h
+)
+
+install (FILES ${HDRS} DESTINATION "${CMAKE_INSTALL_PREFIX}/include/ValueDefinitions")
\ No newline at end of file
diff --git a/src/ValueDefinitions/RealConstant.cpp b/src/ValueDefinitions/RealConstant.cpp
index 01b9d92e6f121eedd6a9edc4dc1aa47082e6b863..3660222970f5f040f872a6dd0eff968582b73c0d 100644
--- a/src/ValueDefinitions/RealConstant.cpp
+++ b/src/ValueDefinitions/RealConstant.cpp
@@ -21,7 +21,7 @@
 #include "Attributes/Attributes.h"
 #include "Utilities/Options.h"
 #include "Physics/Physics.h"
-#include "config.h"
+#include "OPALconfig.h"
 
 #include "Utility/IpplInfo.h"
 
@@ -57,20 +57,7 @@ RealConstant::RealConstant():
 
     opal->create(new RealConstant("CLIGHT", this, Physics::c));
 
-    std::string version_str(PACKAGE_VERSION);
-    int version = 0;
-    {
-        size_t i = 0;
-        while (i < version_str.size()) {
-            size_t n = version_str.find_first_of("0123456789",i);
-            if (n != std::string::npos) {
-                version = version * 10 + version_str[n] - 48;
-                version_str[n] = '.';
-            }
-            i = n;
-        }
-    }
-    opal->create(new RealConstant("OPALVERSION", this, version));
+    opal->create(new RealConstant("OPALVERSION", this, PACKAGE_VERSION));
     opal->create(new RealConstant("RANK", this, Ippl::myNode()));
 }
 
@@ -111,4 +98,8 @@ double RealConstant::getReal() const {
 void RealConstant::print(std::ostream &os) const {
     os << "REAL CONST " << getOpalName() << '=' << itsAttr[0] << ';';
     os << std::endl;
+}
+
+void RealConstant::printValue(std::ostream &os) const {
+    os << itsAttr[0];
 }
\ No newline at end of file
diff --git a/src/ValueDefinitions/RealConstant.h b/src/ValueDefinitions/RealConstant.h
index e0c74507c02bc514351c37b7b7dd2f1a4c6a2c13..4443005afbddf8bf4043db514b4f93046427ead2 100644
--- a/src/ValueDefinitions/RealConstant.h
+++ b/src/ValueDefinitions/RealConstant.h
@@ -46,6 +46,9 @@ public:
     /// Print the constant.
     virtual void print(std::ostream &) const;
 
+    /// Print its value
+    virtual void printValue(std::ostream &os) const;
+
     /// Return value.
     virtual double getReal() const;
 
@@ -59,4 +62,4 @@ private:
     RealConstant(const std::string &name, RealConstant *parent);
 };
 
-#endif // OPAL_RealConstant_HH
+#endif // OPAL_RealConstant_HH
\ No newline at end of file
diff --git a/src/ValueDefinitions/RealVariable.cpp b/src/ValueDefinitions/RealVariable.cpp
index 699bee839692328ae807fad5afd3daecff347db7..336edc6ba72efdc446a371067edda7143b3e3875 100644
--- a/src/ValueDefinitions/RealVariable.cpp
+++ b/src/ValueDefinitions/RealVariable.cpp
@@ -78,3 +78,7 @@ void RealVariable::print(std::ostream &os) const {
        << (itsAttr[0].isExpression() ? ":=" : "=") << itsAttr[0] << ';';
     os << std::endl;
 }
+
+void RealVariable::printValue(std::ostream &os) const {
+    os << itsAttr[0];
+}
\ No newline at end of file
diff --git a/src/ValueDefinitions/RealVariable.h b/src/ValueDefinitions/RealVariable.h
index d6a1424e20fd4b717af17b719fdb5946aa2f671a..df2c211758e21b802c4258bdded33f7414061249 100644
--- a/src/ValueDefinitions/RealVariable.h
+++ b/src/ValueDefinitions/RealVariable.h
@@ -45,6 +45,9 @@ public:
     /// Print the variable.
     virtual void print(std::ostream &) const;
 
+    /// Print its value
+    virtual void printValue(std::ostream &os) const;
+
     /// Return value.
     virtual double getReal() const;
 
@@ -58,4 +61,4 @@ private:
     RealVariable(const std::string &name, RealVariable *parent);
 };
 
-#endif // OPAL_RealVariable_HH
+#endif // OPAL_RealVariable_HH
\ No newline at end of file
diff --git a/src/ValueDefinitions/RealVector.cpp b/src/ValueDefinitions/RealVector.cpp
index 2a14eeaf42e64df97438e31ad1657f661011b263..5c7d46065da4f88cf8676192c66706a1055d5658 100644
--- a/src/ValueDefinitions/RealVector.cpp
+++ b/src/ValueDefinitions/RealVector.cpp
@@ -61,8 +61,11 @@ void RealVector::print(std::ostream &os) const {
        << itsAttr[0] << ';' << std::endl;
 }
 
+void RealVector::printValue(std::ostream &os) const {
+    os << itsAttr[0];
+}
 
 double RealVector::getRealComponent(int index) const {
     std::vector<double> array = Attributes::getRealArray(itsAttr[0]);
     return array[index-1];
-}
+}
\ No newline at end of file
diff --git a/src/ValueDefinitions/RealVector.h b/src/ValueDefinitions/RealVector.h
index df62a844f535fcf0db02178ec9b9d66385572702..fe4b9e7ee99a419f8d37be13e045eb6625d9de89 100644
--- a/src/ValueDefinitions/RealVector.h
+++ b/src/ValueDefinitions/RealVector.h
@@ -43,6 +43,9 @@ public:
     /// Print the vector.
     virtual void print(std::ostream &) const;
 
+    /// Print its value
+    virtual void printValue(std::ostream &os) const;
+
     /// Return indexed value.
     virtual double getRealComponent(int) const;
 
@@ -56,4 +59,4 @@ private:
     RealVector(const std::string &name, RealVector *parent);
 };
 
-#endif // OPAL_RealVector_HH
+#endif // OPAL_RealVector_HH
\ No newline at end of file
diff --git a/src/ValueDefinitions/StringConstant.cpp b/src/ValueDefinitions/StringConstant.cpp
index ba3bce39ce103e79f3c07a008d877cff3c3ba29a..37efb175a9028f11bf65330bbe81549bd646b8bc 100644
--- a/src/ValueDefinitions/StringConstant.cpp
+++ b/src/ValueDefinitions/StringConstant.cpp
@@ -20,7 +20,7 @@
 #include "AbstractObjects/OpalData.h"
 #include "Attributes/Attributes.h"
 #include "Utilities/Options.h"
-#include "revision.h"
+#include "Utilities/Util.h"
 #include <iostream>
 
 
@@ -35,8 +35,7 @@ StringConstant::StringConstant():
     itsAttr[0] = Attributes::makeString("VALUE", "The constant value");
 
     OpalData *opal = OpalData::getInstance();
-    std::string gitRevision(GIT_VERSION);
-    opal->create(new StringConstant("GITREVISION", this, gitRevision));
+    opal->create(new StringConstant("GITREVISION", this, Util::getGitRevision()));
 }
 
 
@@ -78,4 +77,8 @@ std::string StringConstant::getString() const {
 void StringConstant::print(std::ostream &os) const {
     os << "STRING " << getOpalName() << '=' << itsAttr[0] << ';';
     os << std::endl;
+}
+
+void StringConstant::printValue(std::ostream &os) const {
+    os << itsAttr[0];
 }
\ No newline at end of file
diff --git a/src/ValueDefinitions/StringConstant.h b/src/ValueDefinitions/StringConstant.h
index 2a6a574cfd1e1d0d48b2475744383d1a1303beb6..be4b7cb717025e5f3c8062eb9165d67f0cbe9a76 100644
--- a/src/ValueDefinitions/StringConstant.h
+++ b/src/ValueDefinitions/StringConstant.h
@@ -43,6 +43,9 @@ public:
     /// Print the constant.
     virtual void print(std::ostream &) const;
 
+    /// Print its value
+    virtual void printValue(std::ostream &os) const;
+
     /// Return value.
     virtual std::string getString() const;
 
diff --git a/src/addToDoxygenMainPage.h b/src/addToDoxygenMainPage.h
index 9b2ef97b67aadd4ef2f395c22d7bffc976f09dcc..a18c26fd8b9863d6b9e56bdd298af79c2ccd4fb4 100644
--- a/src/addToDoxygenMainPage.h
+++ b/src/addToDoxygenMainPage.h
@@ -15,28 +15,28 @@ OPAL-CYCL tracks particles with 3D space charge including neighbouring turns in
 FFAG’s with time as the independent variable.
 OPAL-T can be used to model beam lines, linacs, rf-photo injectors and complete XFEL’s excluding
 the undulator.
-<P>
+</B>
+</P>
 
 <P>
-Developed by 
+<B>
+Developed by
 Andreas Adelmann, Achim Gsell, Valeria Rizzoglio (PSI),
-Christof Metzger-Kraus (HZB), 
-Yves Ineichen (IBM), 
-Xiaoying Pang, Steve Russell (LANL), 
-Chuan Wang, Jianjun Yang (CIAE), 
-Suzanne Sheehy, Chris Rogers (RAL) and 
+Christof Metzger-Kraus (HZB),
+Yves Ineichen (IBM),
+Xiaoying Pang, Steve Russell (LANL),
+Chuan Wang, Jianjun Yang (CIAE),
+Suzanne Sheehy, Chris Rogers (RAL) and
 Daniel Winklehner (MIT)
 </B>
 <P>
 For further information contact: <a href="mailto:andreas.adelmann@psi.ch">andreas.adelmann@psi.ch</a> -
 Andreas Adelmann
-<P>
+</P>
 Last modified today
-<P>
+</P>
 
 <P>
 <a href="http://www.psi.ch">PSI Disclaimers</a><br>
-*/
-
-
-
+</P>
+*/
\ No newline at end of file
diff --git a/src/config.h.in b/src/config.h.in
index 6e2f6c4a43affc822e8f47ee910ee55686d8ad8e..899f36131b7cf3aa2b83dc0d9dcecd14d873041f 100644
--- a/src/config.h.in
+++ b/src/config.h.in
@@ -13,5 +13,8 @@
 /* Define to the version of this package. */
 #define PACKAGE_VERSION ${PACKAGE_VERSION}
 
+/* Define string PACKAGE_VERSION */
+#define PACKAGE_VERSION_STR ${PACKAGE_VERSION_STR}
+
 /* Define DKS version used in this package. */
-#define DKS_VERSION ${DKS_VERSION}
+#define DKS_VERSION ${DKS_VERSION}
\ No newline at end of file
diff --git a/src/opal.cpp b/src/opal.cpp
index 473996cde51b7ede6e549ede7cc6e729d51f6e65..489dc762b1a79bbc77a775803d138c9bf7dc31ff 100644
--- a/src/opal.cpp
+++ b/src/opal.cpp
@@ -11,7 +11,7 @@ Inform *gmsg;
 #include "Utilities/OpalException.h"
 #include "Fields/Fieldmap.h"
 
-#include "config.h"
+#include "OPALconfig.h"
 
 
 int run_opal(char *arg[], std::string inputfile, int restartStep, MPI_Comm comm) {
@@ -65,4 +65,4 @@ int run_opal(char *arg[], std::string inputfile, int restartStep, MPI_Comm comm)
     //delete ippl;
 
     return 0;
-}
+}
\ No newline at end of file
diff --git a/tests/CMakeLists.txt b/tests/CMakeLists.txt
index 7eceb3ca4ef6ef6983d782bba26a3a08e099a88a..4841084b99058044daf97d730a87d621cc0fb8fd 100644
--- a/tests/CMakeLists.txt
+++ b/tests/CMakeLists.txt
@@ -5,7 +5,7 @@ set (TEST_EXE opal_unit_tests)
 set (SRC_DIRS classic_src opal_src)
 
 set (CMAKE_CXX_FLAGS
-    "${OPAL_CXX_FLAGS} -DWITH_UNIT_TESTS"
+    "${IPPL_CMAKE_CXX_FLAGS} -DUSEH5FEDV2 -DPARALLEL_IO ${CMAKE_CXX_FLAGS} -DWITH_UNIT_TESTS"
 )
 
 set (TEST_SRC_DIR ${CMAKE_CURRENT_SOURCE_DIR})
@@ -51,7 +51,7 @@ INCLUDE_DIRECTORIES(${GTEST_INCLUDE_DIR}
     ${Trilinos_TPL_INCLUDE_DIRS}
     ${IPPL_SOURCE_DIRS}
     ${CCSE_INCLUDE_DIRS}
-    ${GTest_INCLUDE_DIRS}
+    ${GTEST_INCLUDE_DIR}
 )
 
 # Check to see if cmake finds the test files
diff --git a/tests/Kollimator/Degrader/Degrader-1-RT.o b/tests/Kollimator/Degrader/Degrader-1-RT.o
index 366b2594f9f45fb8f1c3ebd96a6e30311b2582d3..eef8333c6f038e29749c16cafc7515a58cc957c2 100644
--- a/tests/Kollimator/Degrader/Degrader-1-RT.o
+++ b/tests/Kollimator/Degrader/Degrader-1-RT.o
@@ -6,46 +6,46 @@ Ippl> CommMPI: Started job 3 on host `Dude.psi.ch'.
 Ippl> CommMPI: Child 2 ready.
 Ippl> CommMPI: Child 3 ready.
 Ippl> CommMPI: Initialization complete.
-{0}>                ____  _____       ___ 
-{0}>               / __ \|  __ \ /\   | | 
+{0}>                ____  _____       ___
+{0}>               / __ \|  __ \ /\   | |
 {0}>              | |  | | |__) /  \  | |
 {0}>              | |  | |  ___/ /\ \ | |
 {0}>              | |__| | |  / ____ \| |____
 {0}>               \____/|_| /_/    \_\______|
-OPAL{0}> 
+OPAL{0}>
 OPAL{0}> This is OPAL (Object Oriented Parallel Accelerator Library) Version 1.3.99.1
-OPAL{0}> 
+OPAL{0}>
 OPAL{0}>                 (c) PSI, http://amas.web.psi.ch
-OPAL{0}> 
-OPAL{0}> Please send cookies, goodies or other motivations (wine and beer ... ) 
+OPAL{0}>
+OPAL{0}> Please send cookies, goodies or other motivations (wine and beer ... )
 OPAL{0}> to the OPAL developers opal@lists.psi.ch
-OPAL{0}> 
+OPAL{0}>
 OPAL{0}> Time: 12:36:47 date: 10/10/2015
-OPAL{0}> 
+OPAL{0}>
 OPAL{0}> Couldn't find startup file "/Users/adelmann/init.opal".
 OPAL{0}> Note: this is not mandatory for an OPAL simulation!
-OPAL{0}> 
+OPAL{0}>
 OPAL{0}> * Reading input stream "Degrader-1.in".
-OPAL{0}> 
+OPAL{0}>
 OPAL{0}> value: {GAMMA,BRHO,EDES,BETA,GAMBET}={1.07674,1.2494,0.072,0.370752,0.399202}
-OPAL{0}> 
-OPAL{0}> * ************* S U R F A C E P H Y S I C S **************************************** 
-OPAL{0}> * SurfacePhysics::initSurfacePhysicsHandler 
-OPAL{0}> * ********************************************************************************** 
-OPAL{0}> * ************* S U R F A C E P H Y S I C S **************************************** 
+OPAL{0}>
+OPAL{0}> * ************* S U R F A C E P H Y S I C S ****************************************
+OPAL{0}> * SurfacePhysics::initSurfacePhysicsHandler
+OPAL{0}> * **********************************************************************************
+OPAL{0}> * ************* S U R F A C E P H Y S I C S ****************************************
 OPAL{0}> * SURFACEPHYSICS DEG1_sphys
 OPAL{0}> * MATERIAL       Graphite
 OPAL{0}> * RADIUS         0
 OPAL{0}> * SIGMA          0
 OPAL{0}> * TAU            0
-OPAL{0}> * ********************************************************************************** 
-OPAL{0}> 
-OPAL{0}[3]> 
+OPAL{0}> * **********************************************************************************
+OPAL{0}>
+OPAL{0}[3]>
 OPAL{0}[3]> 5 elements selected.
-OPAL{0}[3]> 
-OPAL{0}> * ********************************************************************************** 
+OPAL{0}[3]>
+OPAL{0}> * **********************************************************************************
 OPAL{0}> * Selected Tracking Method == PARALLEL-T, NEW TRACK
-OPAL{0}> * ********************************************************************************** 
+OPAL{0}> * **********************************************************************************
 Ippl{0}> no solver attached
 Ippl{0}[3]> BC set for normal Beam
 OPAL{0}> * m before gsl_linalg_cholesky_decomp
@@ -63,11 +63,11 @@ OPAL{0}> * r(3, : ) =          0 &          0 &          0 &          1 &
 OPAL{0}> * r(4, : ) =          0 &          0 &          0 &          0 &          1 &          0 \\
 OPAL{0}> * r(5, : ) =          0 &          0 &          0 &          0 &          0 &          1 \\
 OPAL{0}> * ************* D I S T R I B U T I O N ********************************************
-OPAL{0}> * 
+OPAL{0}> *
 OPAL{0}> * Number of particles: 1000000
-OPAL{0}> * 
+OPAL{0}> *
 OPAL{0}> * Distribution type: GAUSS
-OPAL{0}> * 
+OPAL{0}> *
 OPAL{0}> * SIGMAX   = 0.005 [m]
 OPAL{0}> * SIGMAY   = 0.005 [m]
 OPAL{0}> * SIGMAZ   = 0.0005 [m]
@@ -88,23 +88,23 @@ OPAL{0}> * CUTOFFZ  = 3 [units of SIGMAZ]
 OPAL{0}> * CUTOFFPX = 3 [units of SIGMAPX]
 OPAL{0}> * CUTOFFPY = 3 [units of SIGMAPY]
 OPAL{0}> * CUTOFFPZ = 3 [units of SIGMAPY]
-OPAL{0}> * 
+OPAL{0}> *
 OPAL{0}> * Distribution is injected.
-OPAL{0}> * 
+OPAL{0}> *
 OPAL{0}> * **********************************************************************************
-OPAL{0}> 
-OPAL{0}> * ************* B E A M ************************************************************ 
+OPAL{0}>
+OPAL{0}> * ************* B E A M ************************************************************
 OPAL{0}> * BEAM        BEAM1
 OPAL{0}> * PARTICLE    PROTON
 OPAL{0}> * CURRENT     0.002 A
 OPAL{0}> * FREQUENCY   5.063e+07 Hz
-OPAL{0}> * CHARGE      +e * 1 
+OPAL{0}> * CHARGE      +e * 1
 OPAL{0}> * REST MASS   0.9383 GeV
 OPAL{0}> * MOMENTUM    0.3746
 OPAL{0}> * NPART       1e+06
-OPAL{0}> * ********************************************************************************** 
-OPAL{0}> 
-OPAL{0}> * ************* F I E L D S O L V E R ********************************************** 
+OPAL{0}> * **********************************************************************************
+OPAL{0}>
+OPAL{0}> * ************* F I E L D S O L V E R **********************************************
 OPAL{0}> * FIELDSOLVER  FS1
 OPAL{0}> * TYPE         NONE
 OPAL{0}> * N-PROCESSORS 4
@@ -112,9 +112,9 @@ OPAL{0}> * MX           64
 OPAL{0}> * MY           64
 OPAL{0}> * MT           64
 OPAL{0}> * BBOXINCR     1
-OPAL{0}> * XDIM         parallel  
-OPAL{0}> * YDIM         parallel  
-OPAL{0}> * Z(T)DIM      parallel  
+OPAL{0}> * XDIM         parallel
+OPAL{0}> * YDIM         parallel
+OPAL{0}> * Z(T)DIM      parallel
 Ippl{0}[3]> ======UniformCartesian<3,MFLOAT>==begin======
 Ippl{0}[3]> gridSizes[0] = 65
 Ippl{0}[3]> gridSizes[1] = 65
@@ -133,9 +133,9 @@ Ippl{0}[3]> Dvc[6] = ( -525.977 , 525.569 , 5250.03 )
 Ippl{0}[3]> Dvc[7] = ( 525.977 , 525.569 , 5250.03 )
 Ippl{0}[3]> cell volume = 1.07662e-11
 Ippl{0}[3]> ======UniformCartesian<3,MFLOAT>==end========
-Ippl{0}[3]> 
+Ippl{0}[3]>
 Ippl{0}[3]> ParticleSpatialLayout, with particle distribution:
-Ippl{0}[3]>     Number of particles 251711  Number of particles 249251  Number of particles 249803  Number of particles 249235  
+Ippl{0}[3]>     Number of particles 251711  Number of particles 249251  Number of particles 249803  Number of particles 249235
 Ippl{0}[3]> SpatialLayout decomposition = Total Domain = {[-0.0152028,0.0152168),[-0.0152151,0.0152281),[0.0034762,0.00652381)}
 Ippl{0}[3]> Local Rnodes = 1
 Ippl{0}[3]>  rnode 0 : {[-0.0152028,6.99247e-06),[-0.0152151,6.53305e-06),[0.0034762,0.00652381)}
@@ -152,11 +152,11 @@ Ippl{0}[3]> Remote Vnodes = 3
 Ippl{0}[3]>  vnode 0 : Node = 1 ; vnode_m = 1 ; Domain = {[0:31:1],[32:63:1],[0:63:1]}
 Ippl{0}[3]>  vnode 1 : Node = 2 ; vnode_m = 2 ; Domain = {[32:63:1],[0:31:1],[0:63:1]}
 Ippl{0}[3]>  vnode 2 : Node = 3 ; vnode_m = 3 ; Domain = {[32:63:1],[32:63:1],[0:63:1]}
-Ippl{0}[3]> 
-OPAL{0}> * ********************************************************************************** 
-OPAL{0}> 
-OPAL{0}> 
-OPAL{0}> * ************** B U N C H ********************************************************* 
+Ippl{0}[3]>
+OPAL{0}> * **********************************************************************************
+OPAL{0}>
+OPAL{0}>
+OPAL{0}> * ************** B U N C H *********************************************************
 OPAL{0}> * NP              =   1000000
 OPAL{0}> * Qtot            =    3.95001e-02 [nC]       Qi    =  3.95001e-08 [nC]
 OPAL{0}> * Ekin            =    7.20000e+01 [MeV]      dEkin =  0.00000e+00 [MeV]
@@ -172,33 +172,33 @@ OPAL{0}> * hr              = (  4.75306e-04 ,  4.75675e-04 ,  4.76188e-05 ) [m]
 OPAL{0}> * dh              =    1.00000e-10 [%]
 OPAL{0}> * t               =    0.00000e+00 [s]        dT    =  1.00000e-12 [s]
 OPAL{0}> * spos            =    5.00044e-03 [m]
-OPAL{0}> * ********************************************************************************** 
-OPAL{0}> 
+OPAL{0}> * **********************************************************************************
+OPAL{0}>
 OPAL{0}[2]> Phase space dump frequency 10 and statistics dump frequency 10 w.r.t. the time step.
 OPAL{0}> Track start at: 12:36:49, t= 0; zstop at: 1e+06 [m]
 OPAL{0}> Executing ParallelTTracker, initial DT 1e-12 [s];
 OPAL{0}> max integration steps 230, next step= 0
 OPAL{0}> Using default (Boris-Buneman) integrator
-OPAL{0}> 
+OPAL{0}>
 OPAL{0}> --- BEGIN FIELD LIST ---------------------------------------------------------------
-OPAL{0}> 
+OPAL{0}>
 OPAL{0}> --- 0.005 m -- 0.015 m -- ----------------------------------------------------------
 OPAL{0}> M0
 OPAL{0}> --- 0.02 m -- 0.03 m --  has surface physics ---------------------------------------
 OPAL{0}> DEG1
 OPAL{0}> --- 0.03 m -- 0.04 m -- ------------------------------------------------------------
 OPAL{0}> M1
-OPAL{0}> 
+OPAL{0}>
 OPAL{0}> --- END FIELD LIST -----------------------------------------------------------------
-OPAL{0}> 
+OPAL{0}>
 ParallelTTracker {0}[2]> MINBINEMITTED 1
 ParallelTTracker {0}[2]> MINSTEPFORREBIN 200
 ParallelTTracker {0}[2]> SURFACEEMISSIONSTOP after 1000 seconds
 ParallelTTracker {0}[2]> REPARTFREQ 1000
-ParallelTTracker {0}[3]> 12:36:49 Step      0 at    5.112 [mm] t=  1.000e-12 [s] E=   72.000 [MeV] 
+ParallelTTracker {0}[3]> 12:36:49 Step      0 at    5.112 [mm] t=  1.000e-12 [s] E=   72.000 [MeV]
 OPAL {0}[3]> * Wrote beam phase space.
-OPAL {0}> 
-OPAL {0}> * ************** B U N C H ********************************************************* 
+OPAL {0}>
+OPAL {0}> * ************** B U N C H *********************************************************
 OPAL {0}> * NP              =   1000000
 OPAL {0}> * Qtot            =    3.95001e-02 [nC]       Qi    =  3.95001e-08 [nC]
 OPAL {0}> * Ekin            =    7.20000e+01 [MeV]      dEkin =  0.00000e+00 [MeV]
@@ -214,22 +214,22 @@ OPAL {0}> * hr              = (  4.75306e-04 ,  4.75675e-04 ,  4.76188e-05 ) [m]
 OPAL {0}> * dh              =    1.00000e-10 [%]
 OPAL {0}> * t               =    1.00000e-12 [s]        dT    =  1.00000e-12 [s]
 OPAL {0}> * spos            =    5.11159e-03 [m]
-OPAL {0}> * ********************************************************************************** 
-OPAL {0}> 
+OPAL {0}> * **********************************************************************************
+OPAL {0}>
 OPAL {0}[3]> * Wrote beam statistics.
-ParallelTTracker {0}[3]> 12:36:50 Step      1 at    5.223 [mm] t=  2.000e-12 [s] E=   72.000 [MeV] 
-ParallelTTracker {0}[3]> 12:36:50 Step      2 at    5.334 [mm] t=  3.000e-12 [s] E=   72.000 [MeV] 
-ParallelTTracker {0}[3]> 12:36:50 Step      3 at    5.445 [mm] t=  4.000e-12 [s] E=   72.000 [MeV] 
-ParallelTTracker {0}[3]> 12:36:50 Step      4 at    5.556 [mm] t=  5.000e-12 [s] E=   72.000 [MeV] 
-ParallelTTracker {0}[3]> 12:36:50 Step      5 at    5.667 [mm] t=  6.000e-12 [s] E=   72.000 [MeV] 
-ParallelTTracker {0}[3]> 12:36:51 Step      6 at    5.778 [mm] t=  7.000e-12 [s] E=   72.000 [MeV] 
-ParallelTTracker {0}[3]> 12:36:51 Step      7 at    5.890 [mm] t=  8.000e-12 [s] E=   72.000 [MeV] 
-ParallelTTracker {0}[3]> 12:36:51 Step      8 at    6.001 [mm] t=  9.000e-12 [s] E=   72.000 [MeV] 
-ParallelTTracker {0}[3]> 12:36:51 Step      9 at    6.112 [mm] t=  1.000e-11 [s] E=   72.000 [MeV] 
-ParallelTTracker {0}[3]> 12:36:51 Step     10 at    6.223 [mm] t=  1.100e-11 [s] E=   72.000 [MeV] 
+ParallelTTracker {0}[3]> 12:36:50 Step      1 at    5.223 [mm] t=  2.000e-12 [s] E=   72.000 [MeV]
+ParallelTTracker {0}[3]> 12:36:50 Step      2 at    5.334 [mm] t=  3.000e-12 [s] E=   72.000 [MeV]
+ParallelTTracker {0}[3]> 12:36:50 Step      3 at    5.445 [mm] t=  4.000e-12 [s] E=   72.000 [MeV]
+ParallelTTracker {0}[3]> 12:36:50 Step      4 at    5.556 [mm] t=  5.000e-12 [s] E=   72.000 [MeV]
+ParallelTTracker {0}[3]> 12:36:50 Step      5 at    5.667 [mm] t=  6.000e-12 [s] E=   72.000 [MeV]
+ParallelTTracker {0}[3]> 12:36:51 Step      6 at    5.778 [mm] t=  7.000e-12 [s] E=   72.000 [MeV]
+ParallelTTracker {0}[3]> 12:36:51 Step      7 at    5.890 [mm] t=  8.000e-12 [s] E=   72.000 [MeV]
+ParallelTTracker {0}[3]> 12:36:51 Step      8 at    6.001 [mm] t=  9.000e-12 [s] E=   72.000 [MeV]
+ParallelTTracker {0}[3]> 12:36:51 Step      9 at    6.112 [mm] t=  1.000e-11 [s] E=   72.000 [MeV]
+ParallelTTracker {0}[3]> 12:36:51 Step     10 at    6.223 [mm] t=  1.100e-11 [s] E=   72.000 [MeV]
 OPAL {0}[3]> * Wrote beam phase space.
-OPAL {0}> 
-OPAL {0}> * ************** B U N C H ********************************************************* 
+OPAL {0}>
+OPAL {0}> * ************** B U N C H *********************************************************
 OPAL {0}> * NP              =   1000000
 OPAL {0}> * Qtot            =    3.95001e-02 [nC]       Qi    =  3.95001e-08 [nC]
 OPAL {0}> * Ekin            =    7.20000e+01 [MeV]      dEkin =  0.00000e+00 [MeV]
@@ -245,22 +245,22 @@ OPAL {0}> * hr              = (  4.75306e-04 ,  4.75675e-04 ,  4.76188e-05 ) [m]
 OPAL {0}> * dh              =    1.00000e-10 [%]
 OPAL {0}> * t               =    1.10000e-11 [s]        dT    =  1.00000e-12 [s]
 OPAL {0}> * spos            =    6.22308e-03 [m]
-OPAL {0}> * ********************************************************************************** 
-OPAL {0}> 
+OPAL {0}> * **********************************************************************************
+OPAL {0}>
 OPAL {0}[3]> * Wrote beam statistics.
-ParallelTTracker {0}[3]> 12:36:52 Step     11 at    6.334 [mm] t=  1.200e-11 [s] E=   72.000 [MeV] 
-ParallelTTracker {0}[3]> 12:36:52 Step     12 at    6.445 [mm] t=  1.300e-11 [s] E=   72.000 [MeV] 
-ParallelTTracker {0}[3]> 12:36:53 Step     13 at    6.557 [mm] t=  1.400e-11 [s] E=   72.000 [MeV] 
-ParallelTTracker {0}[3]> 12:36:53 Step     14 at    6.668 [mm] t=  1.500e-11 [s] E=   72.000 [MeV] 
-ParallelTTracker {0}[3]> 12:36:53 Step     15 at    6.779 [mm] t=  1.600e-11 [s] E=   72.000 [MeV] 
-ParallelTTracker {0}[3]> 12:36:53 Step     16 at    6.890 [mm] t=  1.700e-11 [s] E=   72.000 [MeV] 
-ParallelTTracker {0}[3]> 12:36:53 Step     17 at    7.001 [mm] t=  1.800e-11 [s] E=   72.000 [MeV] 
-ParallelTTracker {0}[3]> 12:36:53 Step     18 at    7.112 [mm] t=  1.900e-11 [s] E=   72.000 [MeV] 
-ParallelTTracker {0}[3]> 12:36:53 Step     19 at    7.223 [mm] t=  2.000e-11 [s] E=   72.000 [MeV] 
-ParallelTTracker {0}[3]> 12:36:54 Step     20 at    7.335 [mm] t=  2.100e-11 [s] E=   72.000 [MeV] 
+ParallelTTracker {0}[3]> 12:36:52 Step     11 at    6.334 [mm] t=  1.200e-11 [s] E=   72.000 [MeV]
+ParallelTTracker {0}[3]> 12:36:52 Step     12 at    6.445 [mm] t=  1.300e-11 [s] E=   72.000 [MeV]
+ParallelTTracker {0}[3]> 12:36:53 Step     13 at    6.557 [mm] t=  1.400e-11 [s] E=   72.000 [MeV]
+ParallelTTracker {0}[3]> 12:36:53 Step     14 at    6.668 [mm] t=  1.500e-11 [s] E=   72.000 [MeV]
+ParallelTTracker {0}[3]> 12:36:53 Step     15 at    6.779 [mm] t=  1.600e-11 [s] E=   72.000 [MeV]
+ParallelTTracker {0}[3]> 12:36:53 Step     16 at    6.890 [mm] t=  1.700e-11 [s] E=   72.000 [MeV]
+ParallelTTracker {0}[3]> 12:36:53 Step     17 at    7.001 [mm] t=  1.800e-11 [s] E=   72.000 [MeV]
+ParallelTTracker {0}[3]> 12:36:53 Step     18 at    7.112 [mm] t=  1.900e-11 [s] E=   72.000 [MeV]
+ParallelTTracker {0}[3]> 12:36:53 Step     19 at    7.223 [mm] t=  2.000e-11 [s] E=   72.000 [MeV]
+ParallelTTracker {0}[3]> 12:36:54 Step     20 at    7.335 [mm] t=  2.100e-11 [s] E=   72.000 [MeV]
 OPAL {0}[3]> * Wrote beam phase space.
-OPAL {0}> 
-OPAL {0}> * ************** B U N C H ********************************************************* 
+OPAL {0}>
+OPAL {0}> * ************** B U N C H *********************************************************
 OPAL {0}> * NP              =   1000000
 OPAL {0}> * Qtot            =    3.95001e-02 [nC]       Qi    =  3.95001e-08 [nC]
 OPAL {0}> * Ekin            =    7.20000e+01 [MeV]      dEkin =  0.00000e+00 [MeV]
@@ -276,22 +276,22 @@ OPAL {0}> * hr              = (  4.75306e-04 ,  4.75675e-04 ,  4.76188e-05 ) [m]
 OPAL {0}> * dh              =    1.00000e-10 [%]
 OPAL {0}> * t               =    2.10000e-11 [s]        dT    =  1.00000e-12 [s]
 OPAL {0}> * spos            =    7.33456e-03 [m]
-OPAL {0}> * ********************************************************************************** 
-OPAL {0}> 
+OPAL {0}> * **********************************************************************************
+OPAL {0}>
 OPAL {0}[3]> * Wrote beam statistics.
-ParallelTTracker {0}[3]> 12:36:55 Step     21 at    7.446 [mm] t=  2.200e-11 [s] E=   72.000 [MeV] 
-ParallelTTracker {0}[3]> 12:36:55 Step     22 at    7.557 [mm] t=  2.300e-11 [s] E=   72.000 [MeV] 
-ParallelTTracker {0}[3]> 12:36:55 Step     23 at    7.668 [mm] t=  2.400e-11 [s] E=   72.000 [MeV] 
-ParallelTTracker {0}[3]> 12:36:55 Step     24 at    7.779 [mm] t=  2.500e-11 [s] E=   72.000 [MeV] 
-ParallelTTracker {0}[3]> 12:36:55 Step     25 at    7.890 [mm] t=  2.600e-11 [s] E=   72.000 [MeV] 
-ParallelTTracker {0}[3]> 12:36:55 Step     26 at    8.001 [mm] t=  2.700e-11 [s] E=   72.000 [MeV] 
-ParallelTTracker {0}[3]> 12:36:56 Step     27 at    8.113 [mm] t=  2.800e-11 [s] E=   72.000 [MeV] 
-ParallelTTracker {0}[3]> 12:36:56 Step     28 at    8.224 [mm] t=  2.900e-11 [s] E=   72.000 [MeV] 
-ParallelTTracker {0}[3]> 12:36:56 Step     29 at    8.335 [mm] t=  3.000e-11 [s] E=   72.000 [MeV] 
-ParallelTTracker {0}[3]> 12:36:56 Step     30 at    8.446 [mm] t=  3.100e-11 [s] E=   72.000 [MeV] 
+ParallelTTracker {0}[3]> 12:36:55 Step     21 at    7.446 [mm] t=  2.200e-11 [s] E=   72.000 [MeV]
+ParallelTTracker {0}[3]> 12:36:55 Step     22 at    7.557 [mm] t=  2.300e-11 [s] E=   72.000 [MeV]
+ParallelTTracker {0}[3]> 12:36:55 Step     23 at    7.668 [mm] t=  2.400e-11 [s] E=   72.000 [MeV]
+ParallelTTracker {0}[3]> 12:36:55 Step     24 at    7.779 [mm] t=  2.500e-11 [s] E=   72.000 [MeV]
+ParallelTTracker {0}[3]> 12:36:55 Step     25 at    7.890 [mm] t=  2.600e-11 [s] E=   72.000 [MeV]
+ParallelTTracker {0}[3]> 12:36:55 Step     26 at    8.001 [mm] t=  2.700e-11 [s] E=   72.000 [MeV]
+ParallelTTracker {0}[3]> 12:36:56 Step     27 at    8.113 [mm] t=  2.800e-11 [s] E=   72.000 [MeV]
+ParallelTTracker {0}[3]> 12:36:56 Step     28 at    8.224 [mm] t=  2.900e-11 [s] E=   72.000 [MeV]
+ParallelTTracker {0}[3]> 12:36:56 Step     29 at    8.335 [mm] t=  3.000e-11 [s] E=   72.000 [MeV]
+ParallelTTracker {0}[3]> 12:36:56 Step     30 at    8.446 [mm] t=  3.100e-11 [s] E=   72.000 [MeV]
 OPAL {0}[3]> * Wrote beam phase space.
-OPAL {0}> 
-OPAL {0}> * ************** B U N C H ********************************************************* 
+OPAL {0}>
+OPAL {0}> * ************** B U N C H *********************************************************
 OPAL {0}> * NP              =   1000000
 OPAL {0}> * Qtot            =    3.95001e-02 [nC]       Qi    =  3.95001e-08 [nC]
 OPAL {0}> * Ekin            =    7.20000e+01 [MeV]      dEkin =  0.00000e+00 [MeV]
@@ -307,23 +307,23 @@ OPAL {0}> * hr              = (  4.75306e-04 ,  4.75675e-04 ,  4.76188e-05 ) [m]
 OPAL {0}> * dh              =    1.00000e-10 [%]
 OPAL {0}> * t               =    3.10000e-11 [s]        dT    =  1.00000e-12 [s]
 OPAL {0}> * spos            =    8.44605e-03 [m]
-OPAL {0}> * ********************************************************************************** 
-OPAL {0}> 
+OPAL {0}> * **********************************************************************************
+OPAL {0}>
 OPAL {0}[3]> * Wrote beam statistics.
 Ippl{0}[3]> DEG1 gone live
-ParallelTTracker {0}[3]> 12:36:57 Step     31 at    8.557 [mm] t=  3.200e-11 [s] E=   72.000 [MeV] 
-ParallelTTracker {0}[3]> 12:36:57 Step     32 at    8.668 [mm] t=  3.300e-11 [s] E=   72.000 [MeV] 
-ParallelTTracker {0}[3]> 12:36:58 Step     33 at    8.779 [mm] t=  3.400e-11 [s] E=   72.000 [MeV] 
-ParallelTTracker {0}[3]> 12:36:58 Step     34 at    8.891 [mm] t=  3.500e-11 [s] E=   72.000 [MeV] 
-ParallelTTracker {0}[3]> 12:36:58 Step     35 at    9.002 [mm] t=  3.600e-11 [s] E=   72.000 [MeV] 
-ParallelTTracker {0}[3]> 12:36:58 Step     36 at    9.113 [mm] t=  3.700e-11 [s] E=   72.000 [MeV] 
-ParallelTTracker {0}[3]> 12:36:58 Step     37 at    9.224 [mm] t=  3.800e-11 [s] E=   72.000 [MeV] 
-ParallelTTracker {0}[3]> 12:36:58 Step     38 at    9.335 [mm] t=  3.900e-11 [s] E=   72.000 [MeV] 
-ParallelTTracker {0}[3]> 12:36:58 Step     39 at    9.446 [mm] t=  4.000e-11 [s] E=   72.000 [MeV] 
-ParallelTTracker {0}[3]> 12:36:59 Step     40 at    9.558 [mm] t=  4.100e-11 [s] E=   72.000 [MeV] 
+ParallelTTracker {0}[3]> 12:36:57 Step     31 at    8.557 [mm] t=  3.200e-11 [s] E=   72.000 [MeV]
+ParallelTTracker {0}[3]> 12:36:57 Step     32 at    8.668 [mm] t=  3.300e-11 [s] E=   72.000 [MeV]
+ParallelTTracker {0}[3]> 12:36:58 Step     33 at    8.779 [mm] t=  3.400e-11 [s] E=   72.000 [MeV]
+ParallelTTracker {0}[3]> 12:36:58 Step     34 at    8.891 [mm] t=  3.500e-11 [s] E=   72.000 [MeV]
+ParallelTTracker {0}[3]> 12:36:58 Step     35 at    9.002 [mm] t=  3.600e-11 [s] E=   72.000 [MeV]
+ParallelTTracker {0}[3]> 12:36:58 Step     36 at    9.113 [mm] t=  3.700e-11 [s] E=   72.000 [MeV]
+ParallelTTracker {0}[3]> 12:36:58 Step     37 at    9.224 [mm] t=  3.800e-11 [s] E=   72.000 [MeV]
+ParallelTTracker {0}[3]> 12:36:58 Step     38 at    9.335 [mm] t=  3.900e-11 [s] E=   72.000 [MeV]
+ParallelTTracker {0}[3]> 12:36:58 Step     39 at    9.446 [mm] t=  4.000e-11 [s] E=   72.000 [MeV]
+ParallelTTracker {0}[3]> 12:36:59 Step     40 at    9.558 [mm] t=  4.100e-11 [s] E=   72.000 [MeV]
 OPAL {0}[3]> * Wrote beam phase space.
-OPAL {0}> 
-OPAL {0}> * ************** B U N C H ********************************************************* 
+OPAL {0}>
+OPAL {0}> * ************** B U N C H *********************************************************
 OPAL {0}> * NP              =   1000000
 OPAL {0}> * Qtot            =    3.95001e-02 [nC]       Qi    =  3.95001e-08 [nC]
 OPAL {0}> * Ekin            =    7.20000e+01 [MeV]      dEkin =  0.00000e+00 [MeV]
@@ -339,22 +339,22 @@ OPAL {0}> * hr              = (  4.75306e-04 ,  4.75675e-04 ,  4.76188e-05 ) [m]
 OPAL {0}> * dh              =    1.00000e-10 [%]
 OPAL {0}> * t               =    4.10000e-11 [s]        dT    =  1.00000e-12 [s]
 OPAL {0}> * spos            =    9.55753e-03 [m]
-OPAL {0}> * ********************************************************************************** 
-OPAL {0}> 
+OPAL {0}> * **********************************************************************************
+OPAL {0}>
 OPAL {0}[3]> * Wrote beam statistics.
-ParallelTTracker {0}[3]> 12:37:00 Step     41 at    9.669 [mm] t=  4.200e-11 [s] E=   72.000 [MeV] 
-ParallelTTracker {0}[3]> 12:37:00 Step     42 at    9.780 [mm] t=  4.300e-11 [s] E=   72.000 [MeV] 
-ParallelTTracker {0}[3]> 12:37:00 Step     43 at    9.891 [mm] t=  4.400e-11 [s] E=   72.000 [MeV] 
-ParallelTTracker {0}[3]> 12:37:00 Step     44 at   10.002 [mm] t=  4.500e-11 [s] E=   72.000 [MeV] 
-ParallelTTracker {0}[3]> 12:37:00 Step     45 at   10.113 [mm] t=  4.600e-11 [s] E=   72.000 [MeV] 
-ParallelTTracker {0}[3]> 12:37:01 Step     46 at   10.224 [mm] t=  4.700e-11 [s] E=   72.000 [MeV] 
-ParallelTTracker {0}[3]> 12:37:01 Step     47 at   10.336 [mm] t=  4.800e-11 [s] E=   72.000 [MeV] 
-ParallelTTracker {0}[3]> 12:37:01 Step     48 at   10.447 [mm] t=  4.900e-11 [s] E=   72.000 [MeV] 
-ParallelTTracker {0}[3]> 12:37:01 Step     49 at   10.558 [mm] t=  5.000e-11 [s] E=   72.000 [MeV] 
-ParallelTTracker {0}[3]> 12:37:01 Step     50 at   10.669 [mm] t=  5.100e-11 [s] E=   72.000 [MeV] 
+ParallelTTracker {0}[3]> 12:37:00 Step     41 at    9.669 [mm] t=  4.200e-11 [s] E=   72.000 [MeV]
+ParallelTTracker {0}[3]> 12:37:00 Step     42 at    9.780 [mm] t=  4.300e-11 [s] E=   72.000 [MeV]
+ParallelTTracker {0}[3]> 12:37:00 Step     43 at    9.891 [mm] t=  4.400e-11 [s] E=   72.000 [MeV]
+ParallelTTracker {0}[3]> 12:37:00 Step     44 at   10.002 [mm] t=  4.500e-11 [s] E=   72.000 [MeV]
+ParallelTTracker {0}[3]> 12:37:00 Step     45 at   10.113 [mm] t=  4.600e-11 [s] E=   72.000 [MeV]
+ParallelTTracker {0}[3]> 12:37:01 Step     46 at   10.224 [mm] t=  4.700e-11 [s] E=   72.000 [MeV]
+ParallelTTracker {0}[3]> 12:37:01 Step     47 at   10.336 [mm] t=  4.800e-11 [s] E=   72.000 [MeV]
+ParallelTTracker {0}[3]> 12:37:01 Step     48 at   10.447 [mm] t=  4.900e-11 [s] E=   72.000 [MeV]
+ParallelTTracker {0}[3]> 12:37:01 Step     49 at   10.558 [mm] t=  5.000e-11 [s] E=   72.000 [MeV]
+ParallelTTracker {0}[3]> 12:37:01 Step     50 at   10.669 [mm] t=  5.100e-11 [s] E=   72.000 [MeV]
 OPAL {0}[3]> * Wrote beam phase space.
-OPAL {0}> 
-OPAL {0}> * ************** B U N C H ********************************************************* 
+OPAL {0}>
+OPAL {0}> * ************** B U N C H *********************************************************
 OPAL {0}> * NP              =   1000000
 OPAL {0}> * Qtot            =    3.95001e-02 [nC]       Qi    =  3.95001e-08 [nC]
 OPAL {0}> * Ekin            =    7.20000e+01 [MeV]      dEkin =  0.00000e+00 [MeV]
@@ -370,22 +370,22 @@ OPAL {0}> * hr              = (  4.75306e-04 ,  4.75675e-04 ,  4.76188e-05 ) [m]
 OPAL {0}> * dh              =    1.00000e-10 [%]
 OPAL {0}> * t               =    5.10000e-11 [s]        dT    =  1.00000e-12 [s]
 OPAL {0}> * spos            =    1.06690e-02 [m]
-OPAL {0}> * ********************************************************************************** 
-OPAL {0}> 
+OPAL {0}> * **********************************************************************************
+OPAL {0}>
 OPAL {0}[3]> * Wrote beam statistics.
-ParallelTTracker {0}[3]> 12:37:02 Step     51 at   10.780 [mm] t=  5.200e-11 [s] E=   72.000 [MeV] 
-ParallelTTracker {0}[3]> 12:37:02 Step     52 at   10.891 [mm] t=  5.300e-11 [s] E=   72.000 [MeV] 
-ParallelTTracker {0}[3]> 12:37:02 Step     53 at   11.002 [mm] t=  5.400e-11 [s] E=   72.000 [MeV] 
-ParallelTTracker {0}[3]> 12:37:03 Step     54 at   11.114 [mm] t=  5.500e-11 [s] E=   72.000 [MeV] 
-ParallelTTracker {0}[3]> 12:37:03 Step     55 at   11.225 [mm] t=  5.600e-11 [s] E=   72.000 [MeV] 
-ParallelTTracker {0}[3]> 12:37:03 Step     56 at   11.336 [mm] t=  5.700e-11 [s] E=   72.000 [MeV] 
-ParallelTTracker {0}[3]> 12:37:03 Step     57 at   11.447 [mm] t=  5.800e-11 [s] E=   72.000 [MeV] 
-ParallelTTracker {0}[3]> 12:37:03 Step     58 at   11.558 [mm] t=  5.900e-11 [s] E=   72.000 [MeV] 
-ParallelTTracker {0}[3]> 12:37:03 Step     59 at   11.669 [mm] t=  6.000e-11 [s] E=   72.000 [MeV] 
-ParallelTTracker {0}[3]> 12:37:04 Step     60 at   11.781 [mm] t=  6.100e-11 [s] E=   72.000 [MeV] 
+ParallelTTracker {0}[3]> 12:37:02 Step     51 at   10.780 [mm] t=  5.200e-11 [s] E=   72.000 [MeV]
+ParallelTTracker {0}[3]> 12:37:02 Step     52 at   10.891 [mm] t=  5.300e-11 [s] E=   72.000 [MeV]
+ParallelTTracker {0}[3]> 12:37:02 Step     53 at   11.002 [mm] t=  5.400e-11 [s] E=   72.000 [MeV]
+ParallelTTracker {0}[3]> 12:37:03 Step     54 at   11.114 [mm] t=  5.500e-11 [s] E=   72.000 [MeV]
+ParallelTTracker {0}[3]> 12:37:03 Step     55 at   11.225 [mm] t=  5.600e-11 [s] E=   72.000 [MeV]
+ParallelTTracker {0}[3]> 12:37:03 Step     56 at   11.336 [mm] t=  5.700e-11 [s] E=   72.000 [MeV]
+ParallelTTracker {0}[3]> 12:37:03 Step     57 at   11.447 [mm] t=  5.800e-11 [s] E=   72.000 [MeV]
+ParallelTTracker {0}[3]> 12:37:03 Step     58 at   11.558 [mm] t=  5.900e-11 [s] E=   72.000 [MeV]
+ParallelTTracker {0}[3]> 12:37:03 Step     59 at   11.669 [mm] t=  6.000e-11 [s] E=   72.000 [MeV]
+ParallelTTracker {0}[3]> 12:37:04 Step     60 at   11.781 [mm] t=  6.100e-11 [s] E=   72.000 [MeV]
 OPAL {0}[3]> * Wrote beam phase space.
-OPAL {0}> 
-OPAL {0}> * ************** B U N C H ********************************************************* 
+OPAL {0}>
+OPAL {0}> * ************** B U N C H *********************************************************
 OPAL {0}> * NP              =   1000000
 OPAL {0}> * Qtot            =    3.95001e-02 [nC]       Qi    =  3.95001e-08 [nC]
 OPAL {0}> * Ekin            =    7.20000e+01 [MeV]      dEkin =  0.00000e+00 [MeV]
@@ -401,22 +401,22 @@ OPAL {0}> * hr              = (  4.75306e-04 ,  4.75675e-04 ,  4.76188e-05 ) [m]
 OPAL {0}> * dh              =    1.00000e-10 [%]
 OPAL {0}> * t               =    6.10000e-11 [s]        dT    =  1.00000e-12 [s]
 OPAL {0}> * spos            =    1.17805e-02 [m]
-OPAL {0}> * ********************************************************************************** 
-OPAL {0}> 
+OPAL {0}> * **********************************************************************************
+OPAL {0}>
 OPAL {0}[3]> * Wrote beam statistics.
-ParallelTTracker {0}[3]> 12:37:05 Step     61 at   11.892 [mm] t=  6.200e-11 [s] E=   72.000 [MeV] 
-ParallelTTracker {0}[3]> 12:37:05 Step     62 at   12.003 [mm] t=  6.300e-11 [s] E=   72.000 [MeV] 
-ParallelTTracker {0}[3]> 12:37:05 Step     63 at   12.114 [mm] t=  6.400e-11 [s] E=   72.000 [MeV] 
-ParallelTTracker {0}[3]> 12:37:05 Step     64 at   12.225 [mm] t=  6.500e-11 [s] E=   72.000 [MeV] 
-ParallelTTracker {0}[3]> 12:37:05 Step     65 at   12.336 [mm] t=  6.600e-11 [s] E=   72.000 [MeV] 
-ParallelTTracker {0}[3]> 12:37:05 Step     66 at   12.447 [mm] t=  6.700e-11 [s] E=   72.000 [MeV] 
-ParallelTTracker {0}[3]> 12:37:06 Step     67 at   12.559 [mm] t=  6.800e-11 [s] E=   72.000 [MeV] 
-ParallelTTracker {0}[3]> 12:37:06 Step     68 at   12.670 [mm] t=  6.900e-11 [s] E=   72.000 [MeV] 
-ParallelTTracker {0}[3]> 12:37:06 Step     69 at   12.781 [mm] t=  7.000e-11 [s] E=   72.000 [MeV] 
-ParallelTTracker {0}[3]> 12:37:06 Step     70 at   12.892 [mm] t=  7.100e-11 [s] E=   72.000 [MeV] 
+ParallelTTracker {0}[3]> 12:37:05 Step     61 at   11.892 [mm] t=  6.200e-11 [s] E=   72.000 [MeV]
+ParallelTTracker {0}[3]> 12:37:05 Step     62 at   12.003 [mm] t=  6.300e-11 [s] E=   72.000 [MeV]
+ParallelTTracker {0}[3]> 12:37:05 Step     63 at   12.114 [mm] t=  6.400e-11 [s] E=   72.000 [MeV]
+ParallelTTracker {0}[3]> 12:37:05 Step     64 at   12.225 [mm] t=  6.500e-11 [s] E=   72.000 [MeV]
+ParallelTTracker {0}[3]> 12:37:05 Step     65 at   12.336 [mm] t=  6.600e-11 [s] E=   72.000 [MeV]
+ParallelTTracker {0}[3]> 12:37:05 Step     66 at   12.447 [mm] t=  6.700e-11 [s] E=   72.000 [MeV]
+ParallelTTracker {0}[3]> 12:37:06 Step     67 at   12.559 [mm] t=  6.800e-11 [s] E=   72.000 [MeV]
+ParallelTTracker {0}[3]> 12:37:06 Step     68 at   12.670 [mm] t=  6.900e-11 [s] E=   72.000 [MeV]
+ParallelTTracker {0}[3]> 12:37:06 Step     69 at   12.781 [mm] t=  7.000e-11 [s] E=   72.000 [MeV]
+ParallelTTracker {0}[3]> 12:37:06 Step     70 at   12.892 [mm] t=  7.100e-11 [s] E=   72.000 [MeV]
 OPAL {0}[3]> * Wrote beam phase space.
-OPAL {0}> 
-OPAL {0}> * ************** B U N C H ********************************************************* 
+OPAL {0}>
+OPAL {0}> * ************** B U N C H *********************************************************
 OPAL {0}> * NP              =   1000000
 OPAL {0}> * Qtot            =    3.95001e-02 [nC]       Qi    =  3.95001e-08 [nC]
 OPAL {0}> * Ekin            =    7.20000e+01 [MeV]      dEkin =  0.00000e+00 [MeV]
@@ -432,22 +432,22 @@ OPAL {0}> * hr              = (  4.75306e-04 ,  4.75675e-04 ,  4.76188e-05 ) [m]
 OPAL {0}> * dh              =    1.00000e-10 [%]
 OPAL {0}> * t               =    7.10000e-11 [s]        dT    =  1.00000e-12 [s]
 OPAL {0}> * spos            =    1.28920e-02 [m]
-OPAL {0}> * ********************************************************************************** 
-OPAL {0}> 
+OPAL {0}> * **********************************************************************************
+OPAL {0}>
 OPAL {0}[3]> * Wrote beam statistics.
-ParallelTTracker {0}[3]> 12:37:07 Step     71 at   13.003 [mm] t=  7.200e-11 [s] E=   72.000 [MeV] 
-ParallelTTracker {0}[3]> 12:37:07 Step     72 at   13.114 [mm] t=  7.300e-11 [s] E=   72.000 [MeV] 
-ParallelTTracker {0}[3]> 12:37:07 Step     73 at   13.225 [mm] t=  7.400e-11 [s] E=   72.000 [MeV] 
-ParallelTTracker {0}[3]> 12:37:08 Step     74 at   13.337 [mm] t=  7.500e-11 [s] E=   72.000 [MeV] 
-ParallelTTracker {0}[3]> 12:37:08 Step     75 at   13.448 [mm] t=  7.600e-11 [s] E=   72.000 [MeV] 
-ParallelTTracker {0}[3]> 12:37:08 Step     76 at   13.559 [mm] t=  7.700e-11 [s] E=   72.000 [MeV] 
-ParallelTTracker {0}[3]> 12:37:08 Step     77 at   13.670 [mm] t=  7.800e-11 [s] E=   72.000 [MeV] 
-ParallelTTracker {0}[3]> 12:37:08 Step     78 at   13.781 [mm] t=  7.900e-11 [s] E=   72.000 [MeV] 
-ParallelTTracker {0}[3]> 12:37:08 Step     79 at   13.892 [mm] t=  8.000e-11 [s] E=   72.000 [MeV] 
-ParallelTTracker {0}[3]> 12:37:08 Step     80 at   14.003 [mm] t=  8.100e-11 [s] E=   72.000 [MeV] 
+ParallelTTracker {0}[3]> 12:37:07 Step     71 at   13.003 [mm] t=  7.200e-11 [s] E=   72.000 [MeV]
+ParallelTTracker {0}[3]> 12:37:07 Step     72 at   13.114 [mm] t=  7.300e-11 [s] E=   72.000 [MeV]
+ParallelTTracker {0}[3]> 12:37:07 Step     73 at   13.225 [mm] t=  7.400e-11 [s] E=   72.000 [MeV]
+ParallelTTracker {0}[3]> 12:37:08 Step     74 at   13.337 [mm] t=  7.500e-11 [s] E=   72.000 [MeV]
+ParallelTTracker {0}[3]> 12:37:08 Step     75 at   13.448 [mm] t=  7.600e-11 [s] E=   72.000 [MeV]
+ParallelTTracker {0}[3]> 12:37:08 Step     76 at   13.559 [mm] t=  7.700e-11 [s] E=   72.000 [MeV]
+ParallelTTracker {0}[3]> 12:37:08 Step     77 at   13.670 [mm] t=  7.800e-11 [s] E=   72.000 [MeV]
+ParallelTTracker {0}[3]> 12:37:08 Step     78 at   13.781 [mm] t=  7.900e-11 [s] E=   72.000 [MeV]
+ParallelTTracker {0}[3]> 12:37:08 Step     79 at   13.892 [mm] t=  8.000e-11 [s] E=   72.000 [MeV]
+ParallelTTracker {0}[3]> 12:37:08 Step     80 at   14.003 [mm] t=  8.100e-11 [s] E=   72.000 [MeV]
 OPAL {0}[3]> * Wrote beam phase space.
-OPAL {0}> 
-OPAL {0}> * ************** B U N C H ********************************************************* 
+OPAL {0}>
+OPAL {0}> * ************** B U N C H *********************************************************
 OPAL {0}> * NP              =   1000000
 OPAL {0}> * Qtot            =    3.95001e-02 [nC]       Qi    =  3.95001e-08 [nC]
 OPAL {0}> * Ekin            =    7.20000e+01 [MeV]      dEkin =  0.00000e+00 [MeV]
@@ -463,22 +463,22 @@ OPAL {0}> * hr              = (  4.75306e-04 ,  4.75675e-04 ,  4.76188e-05 ) [m]
 OPAL {0}> * dh              =    1.00000e-10 [%]
 OPAL {0}> * t               =    8.10000e-11 [s]        dT    =  1.00000e-12 [s]
 OPAL {0}> * spos            =    1.40035e-02 [m]
-OPAL {0}> * ********************************************************************************** 
-OPAL {0}> 
+OPAL {0}> * **********************************************************************************
+OPAL {0}>
 OPAL {0}[3]> * Wrote beam statistics.
-ParallelTTracker {0}[3]> 12:37:10 Step     81 at   14.115 [mm] t=  8.200e-11 [s] E=   72.000 [MeV] 
-ParallelTTracker {0}[3]> 12:37:10 Step     82 at   14.226 [mm] t=  8.300e-11 [s] E=   72.000 [MeV] 
-ParallelTTracker {0}[3]> 12:37:10 Step     83 at   14.337 [mm] t=  8.400e-11 [s] E=   72.000 [MeV] 
-ParallelTTracker {0}[3]> 12:37:10 Step     84 at   14.448 [mm] t=  8.500e-11 [s] E=   72.000 [MeV] 
-ParallelTTracker {0}[3]> 12:37:10 Step     85 at   14.559 [mm] t=  8.600e-11 [s] E=   72.000 [MeV] 
-ParallelTTracker {0}[3]> 12:37:10 Step     86 at   14.670 [mm] t=  8.700e-11 [s] E=   72.000 [MeV] 
-ParallelTTracker {0}[3]> 12:37:11 Step     87 at   14.782 [mm] t=  8.800e-11 [s] E=   72.000 [MeV] 
-ParallelTTracker {0}[3]> 12:37:11 Step     88 at   14.893 [mm] t=  8.900e-11 [s] E=   72.000 [MeV] 
-ParallelTTracker {0}[3]> 12:37:11 Step     89 at   15.004 [mm] t=  9.000e-11 [s] E=   72.000 [MeV] 
-ParallelTTracker {0}[3]> 12:37:11 Step     90 at   15.115 [mm] t=  9.100e-11 [s] E=   72.000 [MeV] 
+ParallelTTracker {0}[3]> 12:37:10 Step     81 at   14.115 [mm] t=  8.200e-11 [s] E=   72.000 [MeV]
+ParallelTTracker {0}[3]> 12:37:10 Step     82 at   14.226 [mm] t=  8.300e-11 [s] E=   72.000 [MeV]
+ParallelTTracker {0}[3]> 12:37:10 Step     83 at   14.337 [mm] t=  8.400e-11 [s] E=   72.000 [MeV]
+ParallelTTracker {0}[3]> 12:37:10 Step     84 at   14.448 [mm] t=  8.500e-11 [s] E=   72.000 [MeV]
+ParallelTTracker {0}[3]> 12:37:10 Step     85 at   14.559 [mm] t=  8.600e-11 [s] E=   72.000 [MeV]
+ParallelTTracker {0}[3]> 12:37:10 Step     86 at   14.670 [mm] t=  8.700e-11 [s] E=   72.000 [MeV]
+ParallelTTracker {0}[3]> 12:37:11 Step     87 at   14.782 [mm] t=  8.800e-11 [s] E=   72.000 [MeV]
+ParallelTTracker {0}[3]> 12:37:11 Step     88 at   14.893 [mm] t=  8.900e-11 [s] E=   72.000 [MeV]
+ParallelTTracker {0}[3]> 12:37:11 Step     89 at   15.004 [mm] t=  9.000e-11 [s] E=   72.000 [MeV]
+ParallelTTracker {0}[3]> 12:37:11 Step     90 at   15.115 [mm] t=  9.100e-11 [s] E=   72.000 [MeV]
 OPAL {0}[3]> * Wrote beam phase space.
-OPAL {0}> 
-OPAL {0}> * ************** B U N C H ********************************************************* 
+OPAL {0}>
+OPAL {0}> * ************** B U N C H *********************************************************
 OPAL {0}> * NP              =   1000000
 OPAL {0}> * Qtot            =    3.95001e-02 [nC]       Qi    =  3.95001e-08 [nC]
 OPAL {0}> * Ekin            =    7.20000e+01 [MeV]      dEkin =  0.00000e+00 [MeV]
@@ -494,22 +494,22 @@ OPAL {0}> * hr              = (  4.75306e-04 ,  4.75675e-04 ,  4.76188e-05 ) [m]
 OPAL {0}> * dh              =    1.00000e-10 [%]
 OPAL {0}> * t               =    9.10000e-11 [s]        dT    =  1.00000e-12 [s]
 OPAL {0}> * spos            =    1.51150e-02 [m]
-OPAL {0}> * ********************************************************************************** 
-OPAL {0}> 
+OPAL {0}> * **********************************************************************************
+OPAL {0}>
 OPAL {0}[3]> * Wrote beam statistics.
-ParallelTTracker {0}[3]> 12:37:12 Step     91 at   15.226 [mm] t=  9.200e-11 [s] E=   72.000 [MeV] 
-ParallelTTracker {0}[3]> 12:37:12 Step     92 at   15.337 [mm] t=  9.300e-11 [s] E=   72.000 [MeV] 
-ParallelTTracker {0}[3]> 12:37:13 Step     93 at   15.448 [mm] t=  9.400e-11 [s] E=   72.000 [MeV] 
-ParallelTTracker {0}[3]> 12:37:13 Step     94 at   15.560 [mm] t=  9.500e-11 [s] E=   72.000 [MeV] 
-ParallelTTracker {0}[3]> 12:37:13 Step     95 at   15.671 [mm] t=  9.600e-11 [s] E=   72.000 [MeV] 
-ParallelTTracker {0}[3]> 12:37:13 Step     96 at   15.782 [mm] t=  9.700e-11 [s] E=   72.000 [MeV] 
-ParallelTTracker {0}[3]> 12:37:13 Step     97 at   15.893 [mm] t=  9.800e-11 [s] E=   72.000 [MeV] 
-ParallelTTracker {0}[3]> 12:37:13 Step     98 at   16.004 [mm] t=  9.900e-11 [s] E=   72.000 [MeV] 
-ParallelTTracker {0}[2]> 12:37:14 Step     99 at   16.115 [mm] t=  1.000e-10 [s] E=   72.000 [MeV] 
-ParallelTTracker {0}[3]> 12:37:14 Step    100 at   16.226 [mm] t=  1.010e-10 [s] E=   72.000 [MeV] 
+ParallelTTracker {0}[3]> 12:37:12 Step     91 at   15.226 [mm] t=  9.200e-11 [s] E=   72.000 [MeV]
+ParallelTTracker {0}[3]> 12:37:12 Step     92 at   15.337 [mm] t=  9.300e-11 [s] E=   72.000 [MeV]
+ParallelTTracker {0}[3]> 12:37:13 Step     93 at   15.448 [mm] t=  9.400e-11 [s] E=   72.000 [MeV]
+ParallelTTracker {0}[3]> 12:37:13 Step     94 at   15.560 [mm] t=  9.500e-11 [s] E=   72.000 [MeV]
+ParallelTTracker {0}[3]> 12:37:13 Step     95 at   15.671 [mm] t=  9.600e-11 [s] E=   72.000 [MeV]
+ParallelTTracker {0}[3]> 12:37:13 Step     96 at   15.782 [mm] t=  9.700e-11 [s] E=   72.000 [MeV]
+ParallelTTracker {0}[3]> 12:37:13 Step     97 at   15.893 [mm] t=  9.800e-11 [s] E=   72.000 [MeV]
+ParallelTTracker {0}[3]> 12:37:13 Step     98 at   16.004 [mm] t=  9.900e-11 [s] E=   72.000 [MeV]
+ParallelTTracker {0}[2]> 12:37:14 Step     99 at   16.115 [mm] t=  1.000e-10 [s] E=   72.000 [MeV]
+ParallelTTracker {0}[3]> 12:37:14 Step    100 at   16.226 [mm] t=  1.010e-10 [s] E=   72.000 [MeV]
 OPAL {0}[3]> * Wrote beam phase space.
-OPAL {0}> 
-OPAL {0}> * ************** B U N C H ********************************************************* 
+OPAL {0}>
+OPAL {0}> * ************** B U N C H *********************************************************
 OPAL {0}> * NP              =   1000000
 OPAL {0}> * Qtot            =    3.95001e-02 [nC]       Qi    =  3.95001e-08 [nC]
 OPAL {0}> * Ekin            =    7.20000e+01 [MeV]      dEkin =  0.00000e+00 [MeV]
@@ -525,22 +525,22 @@ OPAL {0}> * hr              = (  4.75306e-04 ,  4.75675e-04 ,  4.76188e-05 ) [m]
 OPAL {0}> * dh              =    1.00000e-10 [%]
 OPAL {0}> * t               =    1.01000e-10 [s]        dT    =  1.00000e-12 [s]
 OPAL {0}> * spos            =    1.62264e-02 [m]
-OPAL {0}> * ********************************************************************************** 
-OPAL {0}> 
+OPAL {0}> * **********************************************************************************
+OPAL {0}>
 OPAL {0}[3]> * Wrote beam statistics.
-ParallelTTracker {0}[3]> 12:37:15 Step    101 at   16.338 [mm] t=  1.020e-10 [s] E=   72.000 [MeV] 
-ParallelTTracker {0}[3]> 12:37:15 Step    102 at   16.449 [mm] t=  1.030e-10 [s] E=   72.000 [MeV] 
-ParallelTTracker {0}[3]> 12:37:15 Step    103 at   16.560 [mm] t=  1.040e-10 [s] E=   72.000 [MeV] 
-ParallelTTracker {0}[3]> 12:37:15 Step    104 at   16.671 [mm] t=  1.050e-10 [s] E=   72.000 [MeV] 
-ParallelTTracker {0}[3]> 12:37:15 Step    105 at   16.782 [mm] t=  1.060e-10 [s] E=   72.000 [MeV] 
-ParallelTTracker {0}[3]> 12:37:16 Step    106 at   16.893 [mm] t=  1.070e-10 [s] E=   72.000 [MeV] 
-ParallelTTracker {0}[3]> 12:37:16 Step    107 at   17.004 [mm] t=  1.080e-10 [s] E=   72.000 [MeV] 
-ParallelTTracker {0}[3]> 12:37:16 Step    108 at   17.116 [mm] t=  1.090e-10 [s] E=   72.000 [MeV] 
-ParallelTTracker {0}[3]> 12:37:16 Step    109 at   17.227 [mm] t=  1.100e-10 [s] E=   72.000 [MeV] 
-ParallelTTracker {0}[3]> 12:37:16 Step    110 at   17.338 [mm] t=  1.110e-10 [s] E=   72.000 [MeV] 
+ParallelTTracker {0}[3]> 12:37:15 Step    101 at   16.338 [mm] t=  1.020e-10 [s] E=   72.000 [MeV]
+ParallelTTracker {0}[3]> 12:37:15 Step    102 at   16.449 [mm] t=  1.030e-10 [s] E=   72.000 [MeV]
+ParallelTTracker {0}[3]> 12:37:15 Step    103 at   16.560 [mm] t=  1.040e-10 [s] E=   72.000 [MeV]
+ParallelTTracker {0}[3]> 12:37:15 Step    104 at   16.671 [mm] t=  1.050e-10 [s] E=   72.000 [MeV]
+ParallelTTracker {0}[3]> 12:37:15 Step    105 at   16.782 [mm] t=  1.060e-10 [s] E=   72.000 [MeV]
+ParallelTTracker {0}[3]> 12:37:16 Step    106 at   16.893 [mm] t=  1.070e-10 [s] E=   72.000 [MeV]
+ParallelTTracker {0}[3]> 12:37:16 Step    107 at   17.004 [mm] t=  1.080e-10 [s] E=   72.000 [MeV]
+ParallelTTracker {0}[3]> 12:37:16 Step    108 at   17.116 [mm] t=  1.090e-10 [s] E=   72.000 [MeV]
+ParallelTTracker {0}[3]> 12:37:16 Step    109 at   17.227 [mm] t=  1.100e-10 [s] E=   72.000 [MeV]
+ParallelTTracker {0}[3]> 12:37:16 Step    110 at   17.338 [mm] t=  1.110e-10 [s] E=   72.000 [MeV]
 OPAL {0}[3]> * Wrote beam phase space.
-OPAL {0}> 
-OPAL {0}> * ************** B U N C H ********************************************************* 
+OPAL {0}>
+OPAL {0}> * ************** B U N C H *********************************************************
 OPAL {0}> * NP              =   1000000
 OPAL {0}> * Qtot            =    3.95001e-02 [nC]       Qi    =  3.95001e-08 [nC]
 OPAL {0}> * Ekin            =    7.20000e+01 [MeV]      dEkin =  0.00000e+00 [MeV]
@@ -556,22 +556,22 @@ OPAL {0}> * hr              = (  4.75306e-04 ,  4.75675e-04 ,  4.76188e-05 ) [m]
 OPAL {0}> * dh              =    1.00000e-10 [%]
 OPAL {0}> * t               =    1.11000e-10 [s]        dT    =  1.00000e-12 [s]
 OPAL {0}> * spos            =    1.73379e-02 [m]
-OPAL {0}> * ********************************************************************************** 
-OPAL {0}> 
+OPAL {0}> * **********************************************************************************
+OPAL {0}>
 OPAL {0}[3]> * Wrote beam statistics.
-ParallelTTracker {0}[3]> 12:37:17 Step    111 at   17.449 [mm] t=  1.120e-10 [s] E=   72.000 [MeV] 
-ParallelTTracker {0}[3]> 12:37:17 Step    112 at   17.560 [mm] t=  1.130e-10 [s] E=   72.000 [MeV] 
-ParallelTTracker {0}[3]> 12:37:17 Step    113 at   17.671 [mm] t=  1.140e-10 [s] E=   72.000 [MeV] 
-ParallelTTracker {0}[3]> 12:37:18 Step    114 at   17.783 [mm] t=  1.150e-10 [s] E=   72.000 [MeV] 
-ParallelTTracker {0}[3]> 12:37:18 Step    115 at   17.894 [mm] t=  1.160e-10 [s] E=   72.000 [MeV] 
-ParallelTTracker {0}[3]> 12:37:18 Step    116 at   18.005 [mm] t=  1.170e-10 [s] E=   72.000 [MeV] 
-ParallelTTracker {0}[3]> 12:37:18 Step    117 at   18.116 [mm] t=  1.180e-10 [s] E=   72.000 [MeV] 
-ParallelTTracker {0}[3]> 12:37:18 Step    118 at   18.227 [mm] t=  1.190e-10 [s] E=   72.000 [MeV] 
-ParallelTTracker {0}[3]> 12:37:18 Step    119 at   18.338 [mm] t=  1.200e-10 [s] E=   72.000 [MeV] 
-ParallelTTracker {0}[3]> 12:37:18 Step    120 at   18.449 [mm] t=  1.210e-10 [s] E=   72.000 [MeV] 
+ParallelTTracker {0}[3]> 12:37:17 Step    111 at   17.449 [mm] t=  1.120e-10 [s] E=   72.000 [MeV]
+ParallelTTracker {0}[3]> 12:37:17 Step    112 at   17.560 [mm] t=  1.130e-10 [s] E=   72.000 [MeV]
+ParallelTTracker {0}[3]> 12:37:17 Step    113 at   17.671 [mm] t=  1.140e-10 [s] E=   72.000 [MeV]
+ParallelTTracker {0}[3]> 12:37:18 Step    114 at   17.783 [mm] t=  1.150e-10 [s] E=   72.000 [MeV]
+ParallelTTracker {0}[3]> 12:37:18 Step    115 at   17.894 [mm] t=  1.160e-10 [s] E=   72.000 [MeV]
+ParallelTTracker {0}[3]> 12:37:18 Step    116 at   18.005 [mm] t=  1.170e-10 [s] E=   72.000 [MeV]
+ParallelTTracker {0}[3]> 12:37:18 Step    117 at   18.116 [mm] t=  1.180e-10 [s] E=   72.000 [MeV]
+ParallelTTracker {0}[3]> 12:37:18 Step    118 at   18.227 [mm] t=  1.190e-10 [s] E=   72.000 [MeV]
+ParallelTTracker {0}[3]> 12:37:18 Step    119 at   18.338 [mm] t=  1.200e-10 [s] E=   72.000 [MeV]
+ParallelTTracker {0}[3]> 12:37:18 Step    120 at   18.449 [mm] t=  1.210e-10 [s] E=   72.000 [MeV]
 OPAL {0}[3]> * Wrote beam phase space.
-OPAL {0}> 
-OPAL {0}> * ************** B U N C H ********************************************************* 
+OPAL {0}>
+OPAL {0}> * ************** B U N C H *********************************************************
 OPAL {0}> * NP              =   1000000
 OPAL {0}> * Qtot            =    3.95001e-02 [nC]       Qi    =  3.95001e-08 [nC]
 OPAL {0}> * Ekin            =    7.20000e+01 [MeV]      dEkin =  0.00000e+00 [MeV]
@@ -587,54 +587,54 @@ OPAL {0}> * hr              = (  4.75306e-04 ,  4.75675e-04 ,  4.76188e-05 ) [m]
 OPAL {0}> * dh              =    1.00000e-10 [%]
 OPAL {0}> * t               =    1.21000e-10 [s]        dT    =  1.00000e-12 [s]
 OPAL {0}> * spos            =    1.84494e-02 [m]
-OPAL {0}> * ********************************************************************************** 
-OPAL {0}> 
+OPAL {0}> * **********************************************************************************
+OPAL {0}>
 OPAL {0}[3]> * Wrote beam statistics.
 Ippl{0}[3]> M1 gone live
 ParallelTTracker {0}[2]> ============== START SURFACE PHYSICS CALCULATION =============
 ParallelTTracker {0}> --- CollimatorPhysics - Type is DEGRADER Name DEG1 Material Graphite Particles in material 41
 ParallelTTracker {0}> Coll/Deg statistics:  bunch to material 41 redifused 0 stopped 0
 ParallelTTracker {0}> * Deleted 41 particles, remaining 999959 particles
-ParallelTTracker {0}[3]> 12:37:19 Step    121 at   18.561 [mm] t=  1.220e-10 [s] E=   72.000 [MeV] 
+ParallelTTracker {0}[3]> 12:37:19 Step    121 at   18.561 [mm] t=  1.220e-10 [s] E=   72.000 [MeV]
 ParallelTTracker {0}> --- CollimatorPhysics - Type is DEGRADER Name DEG1 Material Graphite Particles in material 1464
 ParallelTTracker {0}> Coll/Deg statistics:  bunch to material 1423 redifused 0 stopped 0
 ParallelTTracker {0}> * Deleted 1423 particles, remaining 998536 particles
-ParallelTTracker {0}[3]> 12:37:20 Step    122 at   18.670 [mm] t=  1.230e-10 [s] E=   72.000 [MeV] 
+ParallelTTracker {0}[3]> 12:37:20 Step    122 at   18.670 [mm] t=  1.230e-10 [s] E=   72.000 [MeV]
 ParallelTTracker {0}> --- CollimatorPhysics - Type is DEGRADER Name DEG1 Material Graphite Particles in material 4127
 ParallelTTracker {0}> Coll/Deg statistics:  bunch to material 2663 redifused 0 stopped 0
 ParallelTTracker {0}> * Deleted 2663 particles, remaining 995873 particles
-ParallelTTracker {0}[3]> 12:37:20 Step    123 at   18.777 [mm] t=  1.240e-10 [s] E=   72.000 [MeV] 
+ParallelTTracker {0}[3]> 12:37:20 Step    123 at   18.777 [mm] t=  1.240e-10 [s] E=   72.000 [MeV]
 ParallelTTracker {0}> --- CollimatorPhysics - Type is DEGRADER Name DEG1 Material Graphite Particles in material 8749
 ParallelTTracker {0}> Coll/Deg statistics:  bunch to material 4622 redifused 0 stopped 0
 ParallelTTracker {0}> * Deleted 4622 particles, remaining 991251 particles
-ParallelTTracker {0}[3]> 12:37:20 Step    124 at   18.883 [mm] t=  1.250e-10 [s] E=   72.000 [MeV] 
+ParallelTTracker {0}[3]> 12:37:20 Step    124 at   18.883 [mm] t=  1.250e-10 [s] E=   72.000 [MeV]
 ParallelTTracker {0}> --- CollimatorPhysics - Type is DEGRADER Name DEG1 Material Graphite Particles in material 16363
 ParallelTTracker {0}> Coll/Deg statistics:  bunch to material 7614 redifused 0 stopped 0
 ParallelTTracker {0}> * Deleted 7614 particles, remaining 983637 particles
-ParallelTTracker {0}[3]> 12:37:20 Step    125 at   18.985 [mm] t=  1.260e-10 [s] E=   72.000 [MeV] 
+ParallelTTracker {0}[3]> 12:37:20 Step    125 at   18.985 [mm] t=  1.260e-10 [s] E=   72.000 [MeV]
 ParallelTTracker {0}> --- CollimatorPhysics - Type is DEGRADER Name DEG1 Material Graphite Particles in material 28834
 ParallelTTracker {0}> Coll/Deg statistics:  bunch to material 12471 redifused 0 stopped 0
 ParallelTTracker {0}> * Deleted 12471 particles, remaining 971166 particles
-ParallelTTracker {0}[3]> 12:37:20 Step    126 at   19.083 [mm] t=  1.270e-10 [s] E=   72.000 [MeV] 
+ParallelTTracker {0}[3]> 12:37:20 Step    126 at   19.083 [mm] t=  1.270e-10 [s] E=   72.000 [MeV]
 ParallelTTracker {0}> --- CollimatorPhysics - Type is DEGRADER Name DEG1 Material Graphite Particles in material 47505
 ParallelTTracker {0}> Coll/Deg statistics:  bunch to material 18671 redifused 0 stopped 0
 ParallelTTracker {0}> * Deleted 18671 particles, remaining 952495 particles
-ParallelTTracker {0}[3]> 12:37:21 Step    127 at   19.177 [mm] t=  1.280e-10 [s] E=   72.000 [MeV] 
+ParallelTTracker {0}[3]> 12:37:21 Step    127 at   19.177 [mm] t=  1.280e-10 [s] E=   72.000 [MeV]
 ParallelTTracker {0}> --- CollimatorPhysics - Type is DEGRADER Name DEG1 Material Graphite Particles in material 74581
 ParallelTTracker {0}> Coll/Deg statistics:  bunch to material 27076 redifused 0 stopped 0
 ParallelTTracker {0}> * Deleted 27076 particles, remaining 925419 particles
-ParallelTTracker {0}[3]> 12:37:21 Step    128 at   19.264 [mm] t=  1.290e-10 [s] E=   72.000 [MeV] 
+ParallelTTracker {0}[3]> 12:37:21 Step    128 at   19.264 [mm] t=  1.290e-10 [s] E=   72.000 [MeV]
 ParallelTTracker {0}> --- CollimatorPhysics - Type is DEGRADER Name DEG1 Material Graphite Particles in material 111496
 ParallelTTracker {0}> Coll/Deg statistics:  bunch to material 36915 redifused 0 stopped 0
 ParallelTTracker {0}> * Deleted 36915 particles, remaining 888504 particles
-ParallelTTracker {0}[3]> 12:37:21 Step    129 at   19.344 [mm] t=  1.300e-10 [s] E=   72.000 [MeV] 
+ParallelTTracker {0}[3]> 12:37:21 Step    129 at   19.344 [mm] t=  1.300e-10 [s] E=   72.000 [MeV]
 ParallelTTracker {0}> --- CollimatorPhysics - Type is DEGRADER Name DEG1 Material Graphite Particles in material 160109
 ParallelTTracker {0}> Coll/Deg statistics:  bunch to material 48613 redifused 0 stopped 0
 ParallelTTracker {0}> * Deleted 48613 particles, remaining 839891 particles
-ParallelTTracker {0}[3]> 12:37:21 Step    130 at   19.418 [mm] t=  1.310e-10 [s] E=   72.000 [MeV] 
+ParallelTTracker {0}[3]> 12:37:21 Step    130 at   19.418 [mm] t=  1.310e-10 [s] E=   72.000 [MeV]
 OPAL {0}[3]> * Wrote beam phase space.
-OPAL {0}> 
-OPAL {0}> * ************** B U N C H ********************************************************* 
+OPAL {0}>
+OPAL {0}> * ************** B U N C H *********************************************************
 OPAL {0}> * NP              =   839891
 OPAL {0}> * Qtot            =    3.31758e-02 [nC]       Qi    =  3.95001e-08 [nC]
 OPAL {0}> * Ekin            =    7.20000e+01 [MeV]      dEkin =  0.00000e+00 [MeV]
@@ -650,52 +650,52 @@ OPAL {0}> * hr              = (  4.75258e-04 ,  4.75675e-04 ,  3.16683e-05 ) [m]
 OPAL {0}> * dh              =    1.00000e-10 [%]
 OPAL {0}> * t               =    1.31000e-10 [s]        dT    =  1.00000e-12 [s]
 OPAL {0}> * spos            =    1.94178e-02 [m]
-OPAL {0}> * ********************************************************************************** 
-OPAL {0}> 
+OPAL {0}> * **********************************************************************************
+OPAL {0}>
 OPAL {0}[3]> * Wrote beam statistics.
 ParallelTTracker {0}> --- CollimatorPhysics - Type is DEGRADER Name DEG1 Material Graphite Particles in material 220706
 ParallelTTracker {0}> Coll/Deg statistics:  bunch to material 60597 redifused 0 stopped 0
 ParallelTTracker {0}> * Deleted 60597 particles, remaining 779294 particles
-ParallelTTracker {0}[3]> 12:37:22 Step    131 at   19.484 [mm] t=  1.320e-10 [s] E=   72.000 [MeV] 
+ParallelTTracker {0}[3]> 12:37:22 Step    131 at   19.484 [mm] t=  1.320e-10 [s] E=   72.000 [MeV]
 ParallelTTracker {0}> --- CollimatorPhysics - Type is DEGRADER Name DEG1 Material Graphite Particles in material 291914
 ParallelTTracker {0}> Coll/Deg statistics:  bunch to material 71208 redifused 0 stopped 0
 ParallelTTracker {0}> * Deleted 71208 particles, remaining 708086 particles
-ParallelTTracker {0}[3]> 12:37:23 Step    132 at   19.543 [mm] t=  1.330e-10 [s] E=   72.000 [MeV] 
+ParallelTTracker {0}[3]> 12:37:23 Step    132 at   19.543 [mm] t=  1.330e-10 [s] E=   72.000 [MeV]
 ParallelTTracker {0}> --- CollimatorPhysics - Type is DEGRADER Name DEG1 Material Graphite Particles in material 372753
 ParallelTTracker {0}> Coll/Deg statistics:  bunch to material 80839 redifused 0 stopped 0
 ParallelTTracker {0}> * Deleted 80839 particles, remaining 627247 particles
-ParallelTTracker {0}[3]> 12:37:23 Step    133 at   19.596 [mm] t=  1.340e-10 [s] E=   72.000 [MeV] 
+ParallelTTracker {0}[3]> 12:37:23 Step    133 at   19.596 [mm] t=  1.340e-10 [s] E=   72.000 [MeV]
 ParallelTTracker {0}> --- CollimatorPhysics - Type is DEGRADER Name DEG1 Material Graphite Particles in material 459754
 ParallelTTracker {0}> Coll/Deg statistics:  bunch to material 87001 redifused 0 stopped 0
 ParallelTTracker {0}> * Deleted 87001 particles, remaining 540246 particles
-ParallelTTracker {0}[3]> 12:37:23 Step    134 at   19.642 [mm] t=  1.350e-10 [s] E=   72.000 [MeV] 
+ParallelTTracker {0}[3]> 12:37:23 Step    134 at   19.642 [mm] t=  1.350e-10 [s] E=   72.000 [MeV]
 ParallelTTracker {0}> --- CollimatorPhysics - Type is DEGRADER Name DEG1 Material Graphite Particles in material 548601
 ParallelTTracker {0}> Coll/Deg statistics:  bunch to material 88847 redifused 0 stopped 0
 ParallelTTracker {0}> * Deleted 88847 particles, remaining 451399 particles
-ParallelTTracker {0}[3]> 12:37:23 Step    135 at   19.682 [mm] t=  1.360e-10 [s] E=   72.000 [MeV] 
+ParallelTTracker {0}[3]> 12:37:23 Step    135 at   19.682 [mm] t=  1.360e-10 [s] E=   72.000 [MeV]
 ParallelTTracker {0}> --- CollimatorPhysics - Type is DEGRADER Name DEG1 Material Graphite Particles in material 635129
 ParallelTTracker {0}> Coll/Deg statistics:  bunch to material 86528 redifused 0 stopped 0
 ParallelTTracker {0}> * Deleted 86528 particles, remaining 364871 particles
-ParallelTTracker {0}[3]> 12:37:24 Step    136 at   19.718 [mm] t=  1.370e-10 [s] E=   72.000 [MeV] 
+ParallelTTracker {0}[3]> 12:37:24 Step    136 at   19.718 [mm] t=  1.370e-10 [s] E=   72.000 [MeV]
 ParallelTTracker {0}> --- CollimatorPhysics - Type is DEGRADER Name DEG1 Material Graphite Particles in material 715230
 ParallelTTracker {0}> Coll/Deg statistics:  bunch to material 80101 redifused 0 stopped 0
 ParallelTTracker {0}> * Deleted 80101 particles, remaining 284770 particles
-ParallelTTracker {0}[3]> 12:37:24 Step    137 at   19.750 [mm] t=  1.380e-10 [s] E=   72.000 [MeV] 
+ParallelTTracker {0}[3]> 12:37:24 Step    137 at   19.750 [mm] t=  1.380e-10 [s] E=   72.000 [MeV]
 ParallelTTracker {0}> --- CollimatorPhysics - Type is DEGRADER Name DEG1 Material Graphite Particles in material 786072
 ParallelTTracker {0}> Coll/Deg statistics:  bunch to material 70842 redifused 0 stopped 0
 ParallelTTracker {0}> * Deleted 70842 particles, remaining 213928 particles
-ParallelTTracker {0}[3]> 12:37:24 Step    138 at   19.777 [mm] t=  1.390e-10 [s] E=   72.000 [MeV] 
+ParallelTTracker {0}[3]> 12:37:24 Step    138 at   19.777 [mm] t=  1.390e-10 [s] E=   72.000 [MeV]
 ParallelTTracker {0}> --- CollimatorPhysics - Type is DEGRADER Name DEG1 Material Graphite Particles in material 845496
 ParallelTTracker {0}> Coll/Deg statistics:  bunch to material 59424 redifused 0 stopped 0
 ParallelTTracker {0}> * Deleted 59424 particles, remaining 154504 particles
-ParallelTTracker {0}[3]> 12:37:25 Step    139 at   19.802 [mm] t=  1.400e-10 [s] E=   72.000 [MeV] 
+ParallelTTracker {0}[3]> 12:37:25 Step    139 at   19.802 [mm] t=  1.400e-10 [s] E=   72.000 [MeV]
 ParallelTTracker {0}> --- CollimatorPhysics - Type is DEGRADER Name DEG1 Material Graphite Particles in material 892894
 ParallelTTracker {0}> Coll/Deg statistics:  bunch to material 47398 redifused 0 stopped 0
 ParallelTTracker {0}> * Deleted 47398 particles, remaining 107106 particles
-ParallelTTracker {0}[3]> 12:37:25 Step    140 at   19.825 [mm] t=  1.410e-10 [s] E=   72.000 [MeV] 
+ParallelTTracker {0}[3]> 12:37:25 Step    140 at   19.825 [mm] t=  1.410e-10 [s] E=   72.000 [MeV]
 OPAL {0}[3]> * Wrote beam phase space.
-OPAL {0}> 
-OPAL {0}> * ************** B U N C H ********************************************************* 
+OPAL {0}>
+OPAL {0}> * ************** B U N C H *********************************************************
 OPAL {0}> * NP              =   107106
 OPAL {0}> * Qtot            =    4.23070e-03 [nC]       Qi    =  3.95001e-08 [nC]
 OPAL {0}> * Ekin            =    7.20000e+01 [MeV]      dEkin =  1.58486e-04 [MeV]
@@ -711,52 +711,52 @@ OPAL {0}> * hr              = (  4.73329e-04 ,  4.74714e-04 ,  1.40257e-05 ) [m]
 OPAL {0}> * dh              =    1.00000e-10 [%]
 OPAL {0}> * t               =    1.41000e-10 [s]        dT    =  1.00000e-12 [s]
 OPAL {0}> * spos            =    1.98246e-02 [m]
-OPAL {0}> * ********************************************************************************** 
-OPAL {0}> 
+OPAL {0}> * **********************************************************************************
+OPAL {0}>
 OPAL {0}[3]> * Wrote beam statistics.
 ParallelTTracker {0}> --- CollimatorPhysics - Type is DEGRADER Name DEG1 Material Graphite Particles in material 928787
 ParallelTTracker {0}> Coll/Deg statistics:  bunch to material 35893 redifused 0 stopped 0
 ParallelTTracker {0}> * Deleted 35893 particles, remaining 71213 particles
-ParallelTTracker {0}[3]> 12:37:25 Step    141 at   19.846 [mm] t=  1.420e-10 [s] E=   72.000 [MeV] 
+ParallelTTracker {0}[3]> 12:37:25 Step    141 at   19.846 [mm] t=  1.420e-10 [s] E=   72.000 [MeV]
 ParallelTTracker {0}> --- CollimatorPhysics - Type is DEGRADER Name DEG1 Material Graphite Particles in material 954712
 ParallelTTracker {0}> Coll/Deg statistics:  bunch to material 25925 redifused 0 stopped 0
 ParallelTTracker {0}> * Deleted 25925 particles, remaining 45288 particles
-ParallelTTracker {0}[3]> 12:37:26 Step    142 at   19.867 [mm] t=  1.430e-10 [s] E=   72.000 [MeV] 
+ParallelTTracker {0}[3]> 12:37:26 Step    142 at   19.867 [mm] t=  1.430e-10 [s] E=   72.000 [MeV]
 ParallelTTracker {0}> --- CollimatorPhysics - Type is DEGRADER Name DEG1 Material Graphite Particles in material 972768
 ParallelTTracker {0}> Coll/Deg statistics:  bunch to material 18056 redifused 0 stopped 0
 ParallelTTracker {0}> * Deleted 18056 particles, remaining 27232 particles
-ParallelTTracker {0}[3]> 12:37:26 Step    143 at   19.888 [mm] t=  1.440e-10 [s] E=   72.000 [MeV] 
+ParallelTTracker {0}[3]> 12:37:26 Step    143 at   19.888 [mm] t=  1.440e-10 [s] E=   72.000 [MeV]
 ParallelTTracker {0}> --- CollimatorPhysics - Type is DEGRADER Name DEG1 Material Graphite Particles in material 984586
 ParallelTTracker {0}> Coll/Deg statistics:  bunch to material 11818 redifused 0 stopped 0
 ParallelTTracker {0}> * Deleted 11818 particles, remaining 15414 particles
-ParallelTTracker {0}[3]> 12:37:26 Step    144 at   19.910 [mm] t=  1.450e-10 [s] E=   72.000 [MeV] 
+ParallelTTracker {0}[3]> 12:37:26 Step    144 at   19.910 [mm] t=  1.450e-10 [s] E=   72.000 [MeV]
 ParallelTTracker {0}> --- CollimatorPhysics - Type is DEGRADER Name DEG1 Material Graphite Particles in material 991895
 ParallelTTracker {0}> Coll/Deg statistics:  bunch to material 7309 redifused 0 stopped 0
 ParallelTTracker {0}> * Deleted 7309 particles, remaining 8105 particles
-ParallelTTracker {0}[3]> 12:37:27 Step    145 at   19.935 [mm] t=  1.460e-10 [s] E=   72.000 [MeV] 
+ParallelTTracker {0}[3]> 12:37:27 Step    145 at   19.935 [mm] t=  1.460e-10 [s] E=   72.000 [MeV]
 ParallelTTracker {0}> --- CollimatorPhysics - Type is DEGRADER Name DEG1 Material Graphite Particles in material 996162
 ParallelTTracker {0}> Coll/Deg statistics:  bunch to material 4267 redifused 0 stopped 0
 ParallelTTracker {0}> * Deleted 4267 particles, remaining 3838 particles
-ParallelTTracker {0}[3]> 12:37:27 Step    146 at   19.969 [mm] t=  1.470e-10 [s] E=   72.000 [MeV] 
+ParallelTTracker {0}[3]> 12:37:27 Step    146 at   19.969 [mm] t=  1.470e-10 [s] E=   72.000 [MeV]
 ParallelTTracker {0}> --- CollimatorPhysics - Type is DEGRADER Name DEG1 Material Graphite Particles in material 998730
 ParallelTTracker {0}> Coll/Deg statistics:  bunch to material 2568 redifused 0 stopped 0
 ParallelTTracker {0}> * Deleted 2568 particles, remaining 1270 particles
-ParallelTTracker {0}[3]> 12:37:28 Step    147 at   20.008 [mm] t=  1.480e-10 [s] E=   72.000 [MeV] 
+ParallelTTracker {0}[3]> 12:37:28 Step    147 at   20.008 [mm] t=  1.480e-10 [s] E=   72.000 [MeV]
 ParallelTTracker {0}> --- CollimatorPhysics - Type is DEGRADER Name DEG1 Material Graphite Particles in material 1000000
 ParallelTTracker {0}> Coll/Deg statistics:  bunch to material 1270 redifused 0 stopped 0
 ParallelTTracker {0}> * Deleted 1266 particles, remaining 4 particles
-ParallelTTracker {0}[3]> 12:37:28 Step    148 at   20.101 [mm] t=  1.490e-10 [s] E=   72.000 [MeV] 
-CollimatorPhysics::apply {0}> All Particles are in the material ... 
+ParallelTTracker {0}[3]> 12:37:28 Step    148 at   20.101 [mm] t=  1.490e-10 [s] E=   72.000 [MeV]
+CollimatorPhysics::apply {0}> All Particles are in the material ...
 ParallelTTracker {0}> --- CollimatorPhysics - Type is DEGRADER Name DEG1 Material Graphite Particles in material 999435
 ParallelTTracker {0}> Coll/Deg statistics:  bunch to material 0 redifused 565 stopped 0
 ParallelTTracker {0}> * Deleted 4 particles, remaining 565 particles
-ParallelTTracker {0}[3]> 12:37:55 Step    149 at   30.170 [mm] t=  1.500e-10 [s] E=   51.394 [MeV] 
+ParallelTTracker {0}[3]> 12:37:55 Step    149 at   30.170 [mm] t=  1.500e-10 [s] E=   51.394 [MeV]
 ParallelTTracker {0}> --- CollimatorPhysics - Type is DEGRADER Name DEG1 Material Graphite Particles in material 997543
 ParallelTTracker {0}> Coll/Deg statistics:  bunch to material 0 redifused 1892 stopped 0
-ParallelTTracker {0}[3]> 12:37:55 Step    150 at   30.203 [mm] t=  1.510e-10 [s] E=   51.223 [MeV] 
+ParallelTTracker {0}[3]> 12:37:55 Step    150 at   30.203 [mm] t=  1.510e-10 [s] E=   51.223 [MeV]
 OPAL {0}[3]> * Wrote beam phase space.
-OPAL {0}> 
-OPAL {0}> * ************** B U N C H ********************************************************* 
+OPAL {0}>
+OPAL {0}> * ************** B U N C H *********************************************************
 OPAL {0}> * NP              =   2457
 OPAL {0}> * Qtot            =    9.70517e-05 [nC]       Qi    =  3.95001e-08 [nC]
 OPAL {0}> * Ekin            =    5.12233e+01 [MeV]      dEkin =  4.88760e-01 [MeV]
@@ -772,42 +772,42 @@ OPAL {0}> * hr              = (  4.48485e-04 ,  4.63170e-04 ,  3.05659e-06 ) [m]
 OPAL {0}> * dh              =    1.00000e-10 [%]
 OPAL {0}> * t               =    1.51000e-10 [s]        dT    =  1.00000e-12 [s]
 OPAL {0}> * spos            =    3.02028e-02 [m]
-OPAL {0}> * ********************************************************************************** 
-OPAL {0}> 
+OPAL {0}> * **********************************************************************************
+OPAL {0}>
 OPAL {0}[3]> * Wrote beam statistics.
 ParallelTTracker {0}> --- CollimatorPhysics - Type is DEGRADER Name DEG1 Material Graphite Particles in material 994130
 ParallelTTracker {0}> Coll/Deg statistics:  bunch to material 0 redifused 3413 stopped 0
-ParallelTTracker {0}[3]> 12:37:56 Step    151 at   30.233 [mm] t=  1.520e-10 [s] E=   51.203 [MeV] 
+ParallelTTracker {0}[3]> 12:37:56 Step    151 at   30.233 [mm] t=  1.520e-10 [s] E=   51.203 [MeV]
 ParallelTTracker {0}> --- CollimatorPhysics - Type is DEGRADER Name DEG1 Material Graphite Particles in material 988352
 ParallelTTracker {0}> Coll/Deg statistics:  bunch to material 0 redifused 5778 stopped 0
-ParallelTTracker {0}[3]> 12:37:56 Step    152 at   30.257 [mm] t=  1.530e-10 [s] E=   51.185 [MeV] 
+ParallelTTracker {0}[3]> 12:37:56 Step    152 at   30.257 [mm] t=  1.530e-10 [s] E=   51.185 [MeV]
 ParallelTTracker {0}> --- CollimatorPhysics - Type is DEGRADER Name DEG1 Material Graphite Particles in material 978791
 ParallelTTracker {0}> Coll/Deg statistics:  bunch to material 0 redifused 9561 stopped 0
-ParallelTTracker {0}[3]> 12:37:56 Step    153 at   30.277 [mm] t=  1.540e-10 [s] E=   51.176 [MeV] 
+ParallelTTracker {0}[3]> 12:37:56 Step    153 at   30.277 [mm] t=  1.540e-10 [s] E=   51.176 [MeV]
 ParallelTTracker {0}> --- CollimatorPhysics - Type is DEGRADER Name DEG1 Material Graphite Particles in material 963968
 ParallelTTracker {0}> Coll/Deg statistics:  bunch to material 0 redifused 14823 stopped 0
-ParallelTTracker {0}[3]> 12:37:57 Step    154 at   30.296 [mm] t=  1.550e-10 [s] E=   51.166 [MeV] 
+ParallelTTracker {0}[3]> 12:37:57 Step    154 at   30.296 [mm] t=  1.550e-10 [s] E=   51.166 [MeV]
 ParallelTTracker {0}> --- CollimatorPhysics - Type is DEGRADER Name DEG1 Material Graphite Particles in material 941920
 ParallelTTracker {0}> Coll/Deg statistics:  bunch to material 0 redifused 22048 stopped 0
-ParallelTTracker {0}[3]> 12:37:57 Step    155 at   30.313 [mm] t=  1.560e-10 [s] E=   51.158 [MeV] 
+ParallelTTracker {0}[3]> 12:37:57 Step    155 at   30.313 [mm] t=  1.560e-10 [s] E=   51.158 [MeV]
 ParallelTTracker {0}> --- CollimatorPhysics - Type is DEGRADER Name DEG1 Material Graphite Particles in material 910675
 ParallelTTracker {0}> Coll/Deg statistics:  bunch to material 0 redifused 31245 stopped 0
-ParallelTTracker {0}[3]> 12:37:57 Step    156 at   30.331 [mm] t=  1.570e-10 [s] E=   51.150 [MeV] 
+ParallelTTracker {0}[3]> 12:37:57 Step    156 at   30.331 [mm] t=  1.570e-10 [s] E=   51.150 [MeV]
 ParallelTTracker {0}> --- CollimatorPhysics - Type is DEGRADER Name DEG1 Material Graphite Particles in material 868982
 ParallelTTracker {0}> Coll/Deg statistics:  bunch to material 0 redifused 41693 stopped 0
-ParallelTTracker {0}[3]> 12:37:58 Step    157 at   30.350 [mm] t=  1.580e-10 [s] E=   51.147 [MeV] 
+ParallelTTracker {0}[3]> 12:37:58 Step    157 at   30.350 [mm] t=  1.580e-10 [s] E=   51.147 [MeV]
 ParallelTTracker {0}> --- CollimatorPhysics - Type is DEGRADER Name DEG1 Material Graphite Particles in material 815317
 ParallelTTracker {0}> Coll/Deg statistics:  bunch to material 0 redifused 53665 stopped 0
-ParallelTTracker {0}[3]> 12:37:58 Step    158 at   30.371 [mm] t=  1.590e-10 [s] E=   51.142 [MeV] 
+ParallelTTracker {0}[3]> 12:37:58 Step    158 at   30.371 [mm] t=  1.590e-10 [s] E=   51.142 [MeV]
 ParallelTTracker {0}> --- CollimatorPhysics - Type is DEGRADER Name DEG1 Material Graphite Particles in material 749852
 ParallelTTracker {0}> Coll/Deg statistics:  bunch to material 0 redifused 65465 stopped 0
-ParallelTTracker {0}[3]> 12:37:58 Step    159 at   30.393 [mm] t=  1.600e-10 [s] E=   51.138 [MeV] 
+ParallelTTracker {0}[3]> 12:37:58 Step    159 at   30.393 [mm] t=  1.600e-10 [s] E=   51.138 [MeV]
 ParallelTTracker {0}> --- CollimatorPhysics - Type is DEGRADER Name DEG1 Material Graphite Particles in material 674236
 ParallelTTracker {0}> Coll/Deg statistics:  bunch to material 0 redifused 75616 stopped 0
-ParallelTTracker {0}[3]> 12:37:59 Step    160 at   30.419 [mm] t=  1.610e-10 [s] E=   51.134 [MeV] 
+ParallelTTracker {0}[3]> 12:37:59 Step    160 at   30.419 [mm] t=  1.610e-10 [s] E=   51.134 [MeV]
 OPAL {0}[3]> * Wrote beam phase space.
-OPAL {0}> 
-OPAL {0}> * ************** B U N C H ********************************************************* 
+OPAL {0}>
+OPAL {0}> * ************** B U N C H *********************************************************
 OPAL {0}> * NP              =   325764
 OPAL {0}> * Qtot            =    1.28677e-02 [nC]       Qi    =  3.95001e-08 [nC]
 OPAL {0}> * Ekin            =    5.11335e+01 [MeV]      dEkin =  5.16440e-01 [MeV]
@@ -823,42 +823,42 @@ OPAL {0}> * hr              = (  4.80611e-04 ,  4.79215e-04 ,  1.83932e-05 ) [m]
 OPAL {0}> * dh              =    1.00000e-10 [%]
 OPAL {0}> * t               =    1.61000e-10 [s]        dT    =  1.00000e-12 [s]
 OPAL {0}> * spos            =    3.04186e-02 [m]
-OPAL {0}> * ********************************************************************************** 
-OPAL {0}> 
+OPAL {0}> * **********************************************************************************
+OPAL {0}>
 OPAL {0}[3]> * Wrote beam statistics.
 ParallelTTracker {0}> --- CollimatorPhysics - Type is DEGRADER Name DEG1 Material Graphite Particles in material 590287
 ParallelTTracker {0}> Coll/Deg statistics:  bunch to material 0 redifused 83949 stopped 0
-ParallelTTracker {0}[3]> 12:37:59 Step    161 at   30.447 [mm] t=  1.620e-10 [s] E=   51.130 [MeV] 
+ParallelTTracker {0}[3]> 12:37:59 Step    161 at   30.447 [mm] t=  1.620e-10 [s] E=   51.130 [MeV]
 ParallelTTracker {0}> --- CollimatorPhysics - Type is DEGRADER Name DEG1 Material Graphite Particles in material 501828
 ParallelTTracker {0}> Coll/Deg statistics:  bunch to material 0 redifused 88459 stopped 0
-ParallelTTracker {0}[3]> 12:38:00 Step    162 at   30.479 [mm] t=  1.630e-10 [s] E=   51.127 [MeV] 
+ParallelTTracker {0}[3]> 12:38:00 Step    162 at   30.479 [mm] t=  1.630e-10 [s] E=   51.127 [MeV]
 ParallelTTracker {0}> --- CollimatorPhysics - Type is DEGRADER Name DEG1 Material Graphite Particles in material 413282
 ParallelTTracker {0}> Coll/Deg statistics:  bunch to material 0 redifused 88546 stopped 0
-ParallelTTracker {0}[3]> 12:38:00 Step    163 at   30.516 [mm] t=  1.640e-10 [s] E=   51.124 [MeV] 
+ParallelTTracker {0}[3]> 12:38:00 Step    163 at   30.516 [mm] t=  1.640e-10 [s] E=   51.124 [MeV]
 ParallelTTracker {0}> --- CollimatorPhysics - Type is DEGRADER Name DEG1 Material Graphite Particles in material 329449
 ParallelTTracker {0}> Coll/Deg statistics:  bunch to material 0 redifused 83833 stopped 0
-ParallelTTracker {0}[3]> 12:38:00 Step    164 at   30.559 [mm] t=  1.650e-10 [s] E=   51.121 [MeV] 
+ParallelTTracker {0}[3]> 12:38:00 Step    164 at   30.559 [mm] t=  1.650e-10 [s] E=   51.121 [MeV]
 ParallelTTracker {0}> --- CollimatorPhysics - Type is DEGRADER Name DEG1 Material Graphite Particles in material 253093
 ParallelTTracker {0}> Coll/Deg statistics:  bunch to material 0 redifused 76356 stopped 0
-ParallelTTracker {0}[3]> 12:38:01 Step    165 at   30.606 [mm] t=  1.660e-10 [s] E=   51.119 [MeV] 
+ParallelTTracker {0}[3]> 12:38:01 Step    165 at   30.606 [mm] t=  1.660e-10 [s] E=   51.119 [MeV]
 ParallelTTracker {0}> --- CollimatorPhysics - Type is DEGRADER Name DEG1 Material Graphite Particles in material 187019
 ParallelTTracker {0}> Coll/Deg statistics:  bunch to material 0 redifused 66074 stopped 0
-ParallelTTracker {0}[3]> 12:38:01 Step    166 at   30.660 [mm] t=  1.670e-10 [s] E=   51.117 [MeV] 
+ParallelTTracker {0}[3]> 12:38:01 Step    166 at   30.660 [mm] t=  1.670e-10 [s] E=   51.117 [MeV]
 ParallelTTracker {0}> --- CollimatorPhysics - Type is DEGRADER Name DEG1 Material Graphite Particles in material 133196
 ParallelTTracker {0}> Coll/Deg statistics:  bunch to material 0 redifused 53823 stopped 0
-ParallelTTracker {0}[3]> 12:38:01 Step    167 at   30.720 [mm] t=  1.680e-10 [s] E=   51.115 [MeV] 
+ParallelTTracker {0}[3]> 12:38:01 Step    167 at   30.720 [mm] t=  1.680e-10 [s] E=   51.115 [MeV]
 ParallelTTracker {0}> --- CollimatorPhysics - Type is DEGRADER Name DEG1 Material Graphite Particles in material 90660
 ParallelTTracker {0}> Coll/Deg statistics:  bunch to material 0 redifused 42536 stopped 0
-ParallelTTracker {0}[3]> 12:38:01 Step    168 at   30.786 [mm] t=  1.690e-10 [s] E=   51.113 [MeV] 
+ParallelTTracker {0}[3]> 12:38:01 Step    168 at   30.786 [mm] t=  1.690e-10 [s] E=   51.113 [MeV]
 ParallelTTracker {0}> --- CollimatorPhysics - Type is DEGRADER Name DEG1 Material Graphite Particles in material 59233
 ParallelTTracker {0}> Coll/Deg statistics:  bunch to material 0 redifused 31427 stopped 0
-ParallelTTracker {0}[3]> 12:38:02 Step    169 at   30.858 [mm] t=  1.700e-10 [s] E=   51.111 [MeV] 
+ParallelTTracker {0}[3]> 12:38:02 Step    169 at   30.858 [mm] t=  1.700e-10 [s] E=   51.111 [MeV]
 ParallelTTracker {0}> --- CollimatorPhysics - Type is DEGRADER Name DEG1 Material Graphite Particles in material 36938
 ParallelTTracker {0}> Coll/Deg statistics:  bunch to material 0 redifused 22295 stopped 0
-ParallelTTracker {0}[3]> 12:38:02 Step    170 at   30.935 [mm] t=  1.710e-10 [s] E=   51.111 [MeV] 
+ParallelTTracker {0}[3]> 12:38:02 Step    170 at   30.935 [mm] t=  1.710e-10 [s] E=   51.111 [MeV]
 OPAL {0}[3]> * Wrote beam phase space.
-OPAL {0}> 
-OPAL {0}> * ************** B U N C H ********************************************************* 
+OPAL {0}>
+OPAL {0}> * ************** B U N C H *********************************************************
 OPAL {0}> * NP              =   963062
 OPAL {0}> * Qtot            =    3.80410e-02 [nC]       Qi    =  3.95001e-08 [nC]
 OPAL {0}> * Ekin            =    5.11106e+01 [MeV]      dEkin =  5.37276e-01 [MeV]
@@ -874,42 +874,42 @@ OPAL {0}> * hr              = (  5.02965e-04 ,  4.91862e-04 ,  3.39121e-05 ) [m]
 OPAL {0}> * dh              =    1.00000e-10 [%]
 OPAL {0}> * t               =    1.71000e-10 [s]        dT    =  1.00000e-12 [s]
 OPAL {0}> * spos            =    3.09353e-02 [m]
-OPAL {0}> * ********************************************************************************** 
-OPAL {0}> 
+OPAL {0}> * **********************************************************************************
+OPAL {0}>
 OPAL {0}[3]> * Wrote beam statistics.
 ParallelTTracker {0}> --- CollimatorPhysics - Type is DEGRADER Name DEG1 Material Graphite Particles in material 21780
 ParallelTTracker {0}> Coll/Deg statistics:  bunch to material 0 redifused 15158 stopped 0
-ParallelTTracker {0}[3]> 12:38:03 Step    171 at   31.017 [mm] t=  1.720e-10 [s] E=   51.110 [MeV] 
+ParallelTTracker {0}[3]> 12:38:03 Step    171 at   31.017 [mm] t=  1.720e-10 [s] E=   51.110 [MeV]
 ParallelTTracker {0}> --- CollimatorPhysics - Type is DEGRADER Name DEG1 Material Graphite Particles in material 11959
 ParallelTTracker {0}> Coll/Deg statistics:  bunch to material 0 redifused 9821 stopped 0
-ParallelTTracker {0}[3]> 12:38:03 Step    172 at   31.103 [mm] t=  1.730e-10 [s] E=   51.109 [MeV] 
+ParallelTTracker {0}[3]> 12:38:03 Step    172 at   31.103 [mm] t=  1.730e-10 [s] E=   51.109 [MeV]
 ParallelTTracker {0}> --- CollimatorPhysics - Type is DEGRADER Name DEG1 Material Graphite Particles in material 6081
 ParallelTTracker {0}> Coll/Deg statistics:  bunch to material 0 redifused 5878 stopped 0
-ParallelTTracker {0}[3]> 12:38:03 Step    173 at   31.192 [mm] t=  1.740e-10 [s] E=   51.109 [MeV] 
+ParallelTTracker {0}[3]> 12:38:03 Step    173 at   31.192 [mm] t=  1.740e-10 [s] E=   51.109 [MeV]
 ParallelTTracker {0}> --- CollimatorPhysics - Type is DEGRADER Name DEG1 Material Graphite Particles in material 2684
 ParallelTTracker {0}> Coll/Deg statistics:  bunch to material 0 redifused 3397 stopped 0
-ParallelTTracker {0}[3]> 12:38:04 Step    174 at   31.284 [mm] t=  1.750e-10 [s] E=   51.109 [MeV] 
+ParallelTTracker {0}[3]> 12:38:04 Step    174 at   31.284 [mm] t=  1.750e-10 [s] E=   51.109 [MeV]
 ParallelTTracker {0}> --- CollimatorPhysics - Type is DEGRADER Name DEG1 Material Graphite Particles in material 691
 ParallelTTracker {0}> Coll/Deg statistics:  bunch to material 0 redifused 1993 stopped 0
-ParallelTTracker {0}[3]> 12:38:04 Step    175 at   31.376 [mm] t=  1.760e-10 [s] E=   51.109 [MeV] 
+ParallelTTracker {0}[3]> 12:38:04 Step    175 at   31.376 [mm] t=  1.760e-10 [s] E=   51.109 [MeV]
 ParallelTTracker {0}> --- CollimatorPhysics - Type is DEGRADER Name DEG1 Material Graphite Particles in material 89
 ParallelTTracker {0}> Coll/Deg statistics:  bunch to material 0 redifused 602 stopped 0
-ParallelTTracker {0}[3]> 12:38:04 Step    176 at   31.471 [mm] t=  1.770e-10 [s] E=   51.108 [MeV] 
+ParallelTTracker {0}[3]> 12:38:04 Step    176 at   31.471 [mm] t=  1.770e-10 [s] E=   51.108 [MeV]
 ParallelTTracker {0}> --- CollimatorPhysics - Type is DEGRADER Name DEG1 Material Graphite Particles in material 81
 ParallelTTracker {0}> Coll/Deg statistics:  bunch to material 0 redifused 8 stopped 0
-ParallelTTracker {0}[3]> 12:38:04 Step    177 at   31.566 [mm] t=  1.780e-10 [s] E=   51.108 [MeV] 
+ParallelTTracker {0}[3]> 12:38:04 Step    177 at   31.566 [mm] t=  1.780e-10 [s] E=   51.108 [MeV]
 ParallelTTracker {0}> --- CollimatorPhysics - Type is DEGRADER Name DEG1 Material Graphite Particles in material 77
 ParallelTTracker {0}> Coll/Deg statistics:  bunch to material 0 redifused 4 stopped 0
-ParallelTTracker {0}[3]> 12:38:04 Step    178 at   31.661 [mm] t=  1.790e-10 [s] E=   51.108 [MeV] 
+ParallelTTracker {0}[3]> 12:38:04 Step    178 at   31.661 [mm] t=  1.790e-10 [s] E=   51.108 [MeV]
 ParallelTTracker {0}> --- CollimatorPhysics - Type is DEGRADER Name DEG1 Material Graphite Particles in material 74
 ParallelTTracker {0}> Coll/Deg statistics:  bunch to material 0 redifused 3 stopped 0
-ParallelTTracker {0}[3]> 12:38:05 Step    179 at   31.756 [mm] t=  1.800e-10 [s] E=   51.108 [MeV] 
+ParallelTTracker {0}[3]> 12:38:05 Step    179 at   31.756 [mm] t=  1.800e-10 [s] E=   51.108 [MeV]
 ParallelTTracker {0}> --- CollimatorPhysics - Type is DEGRADER Name DEG1 Material Graphite Particles in material 69
 ParallelTTracker {0}> Coll/Deg statistics:  bunch to material 0 redifused 5 stopped 0
-ParallelTTracker {0}[3]> 12:38:05 Step    180 at   31.851 [mm] t=  1.810e-10 [s] E=   51.108 [MeV] 
+ParallelTTracker {0}[3]> 12:38:05 Step    180 at   31.851 [mm] t=  1.810e-10 [s] E=   51.108 [MeV]
 OPAL {0}[3]> * Wrote beam phase space.
-OPAL {0}> 
-OPAL {0}> * ************** B U N C H ********************************************************* 
+OPAL {0}>
+OPAL {0}> * ************** B U N C H *********************************************************
 OPAL {0}> * NP              =   999931
 OPAL {0}> * Qtot            =    3.94974e-02 [nC]       Qi    =  3.95001e-08 [nC]
 OPAL {0}> * Ekin            =    5.11084e+01 [MeV]      dEkin =  5.58896e-01 [MeV]
@@ -925,42 +925,42 @@ OPAL {0}> * hr              = (  5.07891e-04 ,  4.95075e-04 ,  4.90327e-05 ) [m]
 OPAL {0}> * dh              =    1.00000e-10 [%]
 OPAL {0}> * t               =    1.81000e-10 [s]        dT    =  1.00000e-12 [s]
 OPAL {0}> * spos            =    3.18509e-02 [m]
-OPAL {0}> * ********************************************************************************** 
-OPAL {0}> 
+OPAL {0}> * **********************************************************************************
+OPAL {0}>
 OPAL {0}[3]> * Wrote beam statistics.
 ParallelTTracker {0}> --- CollimatorPhysics - Type is DEGRADER Name DEG1 Material Graphite Particles in material 65
 ParallelTTracker {0}> Coll/Deg statistics:  bunch to material 0 redifused 4 stopped 0
-ParallelTTracker {0}[3]> 12:38:06 Step    181 at   31.946 [mm] t=  1.820e-10 [s] E=   51.108 [MeV] 
+ParallelTTracker {0}[3]> 12:38:06 Step    181 at   31.946 [mm] t=  1.820e-10 [s] E=   51.108 [MeV]
 ParallelTTracker {0}> --- CollimatorPhysics - Type is DEGRADER Name DEG1 Material Graphite Particles in material 62
 ParallelTTracker {0}> Coll/Deg statistics:  bunch to material 0 redifused 3 stopped 0
-ParallelTTracker {0}[3]> 12:38:06 Step    182 at   32.041 [mm] t=  1.830e-10 [s] E=   51.108 [MeV] 
+ParallelTTracker {0}[3]> 12:38:06 Step    182 at   32.041 [mm] t=  1.830e-10 [s] E=   51.108 [MeV]
 ParallelTTracker {0}> --- CollimatorPhysics - Type is DEGRADER Name DEG1 Material Graphite Particles in material 58
 ParallelTTracker {0}> Coll/Deg statistics:  bunch to material 0 redifused 4 stopped 0
-ParallelTTracker {0}[3]> 12:38:07 Step    183 at   32.136 [mm] t=  1.840e-10 [s] E=   51.108 [MeV] 
+ParallelTTracker {0}[3]> 12:38:07 Step    183 at   32.136 [mm] t=  1.840e-10 [s] E=   51.108 [MeV]
 ParallelTTracker {0}> --- CollimatorPhysics - Type is DEGRADER Name DEG1 Material Graphite Particles in material 56
 ParallelTTracker {0}> Coll/Deg statistics:  bunch to material 0 redifused 2 stopped 0
-ParallelTTracker {0}[3]> 12:38:07 Step    184 at   32.231 [mm] t=  1.850e-10 [s] E=   51.108 [MeV] 
+ParallelTTracker {0}[3]> 12:38:07 Step    184 at   32.231 [mm] t=  1.850e-10 [s] E=   51.108 [MeV]
 ParallelTTracker {0}> --- CollimatorPhysics - Type is DEGRADER Name DEG1 Material Graphite Particles in material 56
 ParallelTTracker {0}> Coll/Deg statistics:  bunch to material 0 redifused 0 stopped 0
-ParallelTTracker {0}[3]> 12:38:07 Step    185 at   32.326 [mm] t=  1.860e-10 [s] E=   51.108 [MeV] 
+ParallelTTracker {0}[3]> 12:38:07 Step    185 at   32.326 [mm] t=  1.860e-10 [s] E=   51.108 [MeV]
 ParallelTTracker {0}> --- CollimatorPhysics - Type is DEGRADER Name DEG1 Material Graphite Particles in material 55
 ParallelTTracker {0}> Coll/Deg statistics:  bunch to material 0 redifused 1 stopped 0
-ParallelTTracker {0}[3]> 12:38:07 Step    186 at   32.421 [mm] t=  1.870e-10 [s] E=   51.108 [MeV] 
+ParallelTTracker {0}[3]> 12:38:07 Step    186 at   32.421 [mm] t=  1.870e-10 [s] E=   51.108 [MeV]
 ParallelTTracker {0}> --- CollimatorPhysics - Type is DEGRADER Name DEG1 Material Graphite Particles in material 53
 ParallelTTracker {0}> Coll/Deg statistics:  bunch to material 0 redifused 2 stopped 0
-ParallelTTracker {0}[3]> 12:38:07 Step    187 at   32.516 [mm] t=  1.880e-10 [s] E=   51.108 [MeV] 
+ParallelTTracker {0}[3]> 12:38:07 Step    187 at   32.516 [mm] t=  1.880e-10 [s] E=   51.108 [MeV]
 ParallelTTracker {0}> --- CollimatorPhysics - Type is DEGRADER Name DEG1 Material Graphite Particles in material 53
 ParallelTTracker {0}> Coll/Deg statistics:  bunch to material 0 redifused 0 stopped 0
-ParallelTTracker {0}[3]> 12:38:08 Step    188 at   32.611 [mm] t=  1.890e-10 [s] E=   51.108 [MeV] 
+ParallelTTracker {0}[3]> 12:38:08 Step    188 at   32.611 [mm] t=  1.890e-10 [s] E=   51.108 [MeV]
 ParallelTTracker {0}> --- CollimatorPhysics - Type is DEGRADER Name DEG1 Material Graphite Particles in material 52
 ParallelTTracker {0}> Coll/Deg statistics:  bunch to material 0 redifused 1 stopped 0
-ParallelTTracker {0}[3]> 12:38:08 Step    189 at   32.706 [mm] t=  1.900e-10 [s] E=   51.108 [MeV] 
+ParallelTTracker {0}[3]> 12:38:08 Step    189 at   32.706 [mm] t=  1.900e-10 [s] E=   51.108 [MeV]
 ParallelTTracker {0}> --- CollimatorPhysics - Type is DEGRADER Name DEG1 Material Graphite Particles in material 52
 ParallelTTracker {0}> Coll/Deg statistics:  bunch to material 0 redifused 0 stopped 0
-ParallelTTracker {0}[3]> 12:38:08 Step    190 at   32.801 [mm] t=  1.910e-10 [s] E=   51.108 [MeV] 
+ParallelTTracker {0}[3]> 12:38:08 Step    190 at   32.801 [mm] t=  1.910e-10 [s] E=   51.108 [MeV]
 OPAL {0}[3]> * Wrote beam phase space.
-OPAL {0}> 
-OPAL {0}> * ************** B U N C H ********************************************************* 
+OPAL {0}>
+OPAL {0}> * ************** B U N C H *********************************************************
 OPAL {0}> * NP              =   999948
 OPAL {0}> * Qtot            =    3.94980e-02 [nC]       Qi    =  3.95001e-08 [nC]
 OPAL {0}> * Ekin            =    5.11083e+01 [MeV]      dEkin =  5.71724e-01 [MeV]
@@ -976,42 +976,42 @@ OPAL {0}> * hr              = (  5.13646e-04 ,  5.01563e-04 ,  6.29029e-05 ) [m]
 OPAL {0}> * dh              =    1.00000e-10 [%]
 OPAL {0}> * t               =    1.91000e-10 [s]        dT    =  1.00000e-12 [s]
 OPAL {0}> * spos            =    3.28015e-02 [m]
-OPAL {0}> * ********************************************************************************** 
-OPAL {0}> 
+OPAL {0}> * **********************************************************************************
+OPAL {0}>
 OPAL {0}[3]> * Wrote beam statistics.
 ParallelTTracker {0}> --- CollimatorPhysics - Type is DEGRADER Name DEG1 Material Graphite Particles in material 50
 ParallelTTracker {0}> Coll/Deg statistics:  bunch to material 0 redifused 2 stopped 0
-ParallelTTracker {0}[3]> 12:38:10 Step    191 at   32.897 [mm] t=  1.920e-10 [s] E=   51.108 [MeV] 
+ParallelTTracker {0}[3]> 12:38:10 Step    191 at   32.897 [mm] t=  1.920e-10 [s] E=   51.108 [MeV]
 ParallelTTracker {0}> --- CollimatorPhysics - Type is DEGRADER Name DEG1 Material Graphite Particles in material 48
 ParallelTTracker {0}> Coll/Deg statistics:  bunch to material 0 redifused 2 stopped 0
-ParallelTTracker {0}[3]> 12:38:10 Step    192 at   32.992 [mm] t=  1.930e-10 [s] E=   51.108 [MeV] 
+ParallelTTracker {0}[3]> 12:38:10 Step    192 at   32.992 [mm] t=  1.930e-10 [s] E=   51.108 [MeV]
 ParallelTTracker {0}> --- CollimatorPhysics - Type is DEGRADER Name DEG1 Material Graphite Particles in material 47
 ParallelTTracker {0}> Coll/Deg statistics:  bunch to material 0 redifused 1 stopped 0
-ParallelTTracker {0}[3]> 12:38:10 Step    193 at   33.087 [mm] t=  1.940e-10 [s] E=   51.108 [MeV] 
+ParallelTTracker {0}[3]> 12:38:10 Step    193 at   33.087 [mm] t=  1.940e-10 [s] E=   51.108 [MeV]
 ParallelTTracker {0}> --- CollimatorPhysics - Type is DEGRADER Name DEG1 Material Graphite Particles in material 46
 ParallelTTracker {0}> Coll/Deg statistics:  bunch to material 0 redifused 1 stopped 0
-ParallelTTracker {0}[3]> 12:38:10 Step    194 at   33.182 [mm] t=  1.950e-10 [s] E=   51.108 [MeV] 
+ParallelTTracker {0}[3]> 12:38:10 Step    194 at   33.182 [mm] t=  1.950e-10 [s] E=   51.108 [MeV]
 ParallelTTracker {0}> --- CollimatorPhysics - Type is DEGRADER Name DEG1 Material Graphite Particles in material 46
 ParallelTTracker {0}> Coll/Deg statistics:  bunch to material 0 redifused 0 stopped 0
-ParallelTTracker {0}[3]> 12:38:10 Step    195 at   33.277 [mm] t=  1.960e-10 [s] E=   51.108 [MeV] 
+ParallelTTracker {0}[3]> 12:38:10 Step    195 at   33.277 [mm] t=  1.960e-10 [s] E=   51.108 [MeV]
 ParallelTTracker {0}> --- CollimatorPhysics - Type is DEGRADER Name DEG1 Material Graphite Particles in material 45
 ParallelTTracker {0}> Coll/Deg statistics:  bunch to material 0 redifused 1 stopped 0
-ParallelTTracker {0}[3]> 12:38:11 Step    196 at   33.372 [mm] t=  1.970e-10 [s] E=   51.108 [MeV] 
+ParallelTTracker {0}[3]> 12:38:11 Step    196 at   33.372 [mm] t=  1.970e-10 [s] E=   51.108 [MeV]
 ParallelTTracker {0}> --- CollimatorPhysics - Type is DEGRADER Name DEG1 Material Graphite Particles in material 45
 ParallelTTracker {0}> Coll/Deg statistics:  bunch to material 0 redifused 0 stopped 0
-ParallelTTracker {0}[3]> 12:38:11 Step    197 at   33.467 [mm] t=  1.980e-10 [s] E=   51.108 [MeV] 
+ParallelTTracker {0}[3]> 12:38:11 Step    197 at   33.467 [mm] t=  1.980e-10 [s] E=   51.108 [MeV]
 ParallelTTracker {0}> --- CollimatorPhysics - Type is DEGRADER Name DEG1 Material Graphite Particles in material 45
 ParallelTTracker {0}> Coll/Deg statistics:  bunch to material 0 redifused 0 stopped 0
-ParallelTTracker {0}[3]> 12:38:11 Step    198 at   33.562 [mm] t=  1.990e-10 [s] E=   51.108 [MeV] 
+ParallelTTracker {0}[3]> 12:38:11 Step    198 at   33.562 [mm] t=  1.990e-10 [s] E=   51.108 [MeV]
 ParallelTTracker {0}> --- CollimatorPhysics - Type is DEGRADER Name DEG1 Material Graphite Particles in material 44
 ParallelTTracker {0}> Coll/Deg statistics:  bunch to material 0 redifused 1 stopped 0
-ParallelTTracker {0}[2]> 12:38:11 Step    199 at   33.657 [mm] t=  2.000e-10 [s] E=   51.108 [MeV] 
+ParallelTTracker {0}[2]> 12:38:11 Step    199 at   33.657 [mm] t=  2.000e-10 [s] E=   51.108 [MeV]
 ParallelTTracker {0}> --- CollimatorPhysics - Type is DEGRADER Name DEG1 Material Graphite Particles in material 43
 ParallelTTracker {0}> Coll/Deg statistics:  bunch to material 0 redifused 1 stopped 0
-ParallelTTracker {0}[3]> 12:38:11 Step    200 at   33.752 [mm] t=  2.010e-10 [s] E=   51.108 [MeV] 
+ParallelTTracker {0}[3]> 12:38:11 Step    200 at   33.752 [mm] t=  2.010e-10 [s] E=   51.108 [MeV]
 OPAL {0}[3]> * Wrote beam phase space.
-OPAL {0}> 
-OPAL {0}> * ************** B U N C H ********************************************************* 
+OPAL {0}>
+OPAL {0}> * ************** B U N C H *********************************************************
 OPAL {0}> * NP              =   999957
 OPAL {0}> * Qtot            =    3.94984e-02 [nC]       Qi    =  3.95001e-08 [nC]
 OPAL {0}> * Ekin            =    5.11082e+01 [MeV]      dEkin =  5.87910e-01 [MeV]
@@ -1027,42 +1027,42 @@ OPAL {0}> * hr              = (  5.23318e-04 ,  5.10101e-04 ,  8.01292e-05 ) [m]
 OPAL {0}> * dh              =    1.00000e-10 [%]
 OPAL {0}> * t               =    2.01000e-10 [s]        dT    =  1.00000e-12 [s]
 OPAL {0}> * spos            =    3.37520e-02 [m]
-OPAL {0}> * ********************************************************************************** 
-OPAL {0}> 
+OPAL {0}> * **********************************************************************************
+OPAL {0}>
 OPAL {0}[3]> * Wrote beam statistics.
 ParallelTTracker {0}> --- CollimatorPhysics - Type is DEGRADER Name DEG1 Material Graphite Particles in material 43
 ParallelTTracker {0}> Coll/Deg statistics:  bunch to material 0 redifused 0 stopped 0
-ParallelTTracker {0}[3]> 12:38:13 Step    201 at   33.847 [mm] t=  2.020e-10 [s] E=   51.108 [MeV] 
+ParallelTTracker {0}[3]> 12:38:13 Step    201 at   33.847 [mm] t=  2.020e-10 [s] E=   51.108 [MeV]
 ParallelTTracker {0}> --- CollimatorPhysics - Type is DEGRADER Name DEG1 Material Graphite Particles in material 41
 ParallelTTracker {0}> Coll/Deg statistics:  bunch to material 0 redifused 2 stopped 0
-ParallelTTracker {0}[3]> 12:38:13 Step    202 at   33.942 [mm] t=  2.030e-10 [s] E=   51.108 [MeV] 
+ParallelTTracker {0}[3]> 12:38:13 Step    202 at   33.942 [mm] t=  2.030e-10 [s] E=   51.108 [MeV]
 ParallelTTracker {0}> --- CollimatorPhysics - Type is DEGRADER Name DEG1 Material Graphite Particles in material 41
 ParallelTTracker {0}> Coll/Deg statistics:  bunch to material 0 redifused 0 stopped 0
-ParallelTTracker {0}[3]> 12:38:13 Step    203 at   34.037 [mm] t=  2.040e-10 [s] E=   51.108 [MeV] 
+ParallelTTracker {0}[3]> 12:38:13 Step    203 at   34.037 [mm] t=  2.040e-10 [s] E=   51.108 [MeV]
 ParallelTTracker {0}> --- CollimatorPhysics - Type is DEGRADER Name DEG1 Material Graphite Particles in material 40
 ParallelTTracker {0}> Coll/Deg statistics:  bunch to material 0 redifused 1 stopped 0
-ParallelTTracker {0}[3]> 12:38:14 Step    204 at   34.132 [mm] t=  2.050e-10 [s] E=   51.108 [MeV] 
+ParallelTTracker {0}[3]> 12:38:14 Step    204 at   34.132 [mm] t=  2.050e-10 [s] E=   51.108 [MeV]
 ParallelTTracker {0}> --- CollimatorPhysics - Type is DEGRADER Name DEG1 Material Graphite Particles in material 40
 ParallelTTracker {0}> Coll/Deg statistics:  bunch to material 0 redifused 0 stopped 0
-ParallelTTracker {0}[3]> 12:38:14 Step    205 at   34.227 [mm] t=  2.060e-10 [s] E=   51.108 [MeV] 
+ParallelTTracker {0}[3]> 12:38:14 Step    205 at   34.227 [mm] t=  2.060e-10 [s] E=   51.108 [MeV]
 ParallelTTracker {0}> --- CollimatorPhysics - Type is DEGRADER Name DEG1 Material Graphite Particles in material 38
 ParallelTTracker {0}> Coll/Deg statistics:  bunch to material 0 redifused 2 stopped 0
-ParallelTTracker {0}[3]> 12:38:14 Step    206 at   34.322 [mm] t=  2.070e-10 [s] E=   51.108 [MeV] 
+ParallelTTracker {0}[3]> 12:38:14 Step    206 at   34.322 [mm] t=  2.070e-10 [s] E=   51.108 [MeV]
 ParallelTTracker {0}> --- CollimatorPhysics - Type is DEGRADER Name DEG1 Material Graphite Particles in material 37
 ParallelTTracker {0}> Coll/Deg statistics:  bunch to material 0 redifused 1 stopped 0
-ParallelTTracker {0}[3]> 12:38:14 Step    207 at   34.417 [mm] t=  2.080e-10 [s] E=   51.108 [MeV] 
+ParallelTTracker {0}[3]> 12:38:14 Step    207 at   34.417 [mm] t=  2.080e-10 [s] E=   51.108 [MeV]
 ParallelTTracker {0}> --- CollimatorPhysics - Type is DEGRADER Name DEG1 Material Graphite Particles in material 37
 ParallelTTracker {0}> Coll/Deg statistics:  bunch to material 0 redifused 0 stopped 0
-ParallelTTracker {0}[3]> 12:38:14 Step    208 at   34.512 [mm] t=  2.090e-10 [s] E=   51.108 [MeV] 
+ParallelTTracker {0}[3]> 12:38:14 Step    208 at   34.512 [mm] t=  2.090e-10 [s] E=   51.108 [MeV]
 ParallelTTracker {0}> --- CollimatorPhysics - Type is DEGRADER Name DEG1 Material Graphite Particles in material 35
 ParallelTTracker {0}> Coll/Deg statistics:  bunch to material 0 redifused 2 stopped 0
-ParallelTTracker {0}[3]> 12:38:15 Step    209 at   34.607 [mm] t=  2.100e-10 [s] E=   51.108 [MeV] 
+ParallelTTracker {0}[3]> 12:38:15 Step    209 at   34.607 [mm] t=  2.100e-10 [s] E=   51.108 [MeV]
 ParallelTTracker {0}> --- CollimatorPhysics - Type is DEGRADER Name DEG1 Material Graphite Particles in material 35
 ParallelTTracker {0}> Coll/Deg statistics:  bunch to material 0 redifused 0 stopped 0
-ParallelTTracker {0}[3]> 12:38:15 Step    210 at   34.703 [mm] t=  2.110e-10 [s] E=   51.108 [MeV] 
+ParallelTTracker {0}[3]> 12:38:15 Step    210 at   34.703 [mm] t=  2.110e-10 [s] E=   51.108 [MeV]
 OPAL {0}[3]> * Wrote beam phase space.
-OPAL {0}> 
-OPAL {0}> * ************** B U N C H ********************************************************* 
+OPAL {0}>
+OPAL {0}> * ************** B U N C H *********************************************************
 OPAL {0}> * NP              =   999965
 OPAL {0}> * Qtot            =    3.94987e-02 [nC]       Qi    =  3.95001e-08 [nC]
 OPAL {0}> * Ekin            =    5.11081e+01 [MeV]      dEkin =  6.01250e-01 [MeV]
@@ -1078,42 +1078,42 @@ OPAL {0}> * hr              = (  5.32989e-04 ,  5.18638e-04 ,  9.42718e-05 ) [m]
 OPAL {0}> * dh              =    1.00000e-10 [%]
 OPAL {0}> * t               =    2.11000e-10 [s]        dT    =  1.00000e-12 [s]
 OPAL {0}> * spos            =    3.47025e-02 [m]
-OPAL {0}> * ********************************************************************************** 
-OPAL {0}> 
+OPAL {0}> * **********************************************************************************
+OPAL {0}>
 OPAL {0}[3]> * Wrote beam statistics.
 ParallelTTracker {0}> --- CollimatorPhysics - Type is DEGRADER Name DEG1 Material Graphite Particles in material 34
 ParallelTTracker {0}> Coll/Deg statistics:  bunch to material 0 redifused 1 stopped 0
-ParallelTTracker {0}[3]> 12:38:16 Step    211 at   34.798 [mm] t=  2.120e-10 [s] E=   51.108 [MeV] 
+ParallelTTracker {0}[3]> 12:38:16 Step    211 at   34.798 [mm] t=  2.120e-10 [s] E=   51.108 [MeV]
 ParallelTTracker {0}> --- CollimatorPhysics - Type is DEGRADER Name DEG1 Material Graphite Particles in material 33
 ParallelTTracker {0}> Coll/Deg statistics:  bunch to material 0 redifused 1 stopped 0
-ParallelTTracker {0}[3]> 12:38:16 Step    212 at   34.893 [mm] t=  2.130e-10 [s] E=   51.108 [MeV] 
+ParallelTTracker {0}[3]> 12:38:16 Step    212 at   34.893 [mm] t=  2.130e-10 [s] E=   51.108 [MeV]
 ParallelTTracker {0}> --- CollimatorPhysics - Type is DEGRADER Name DEG1 Material Graphite Particles in material 33
 ParallelTTracker {0}> Coll/Deg statistics:  bunch to material 0 redifused 0 stopped 0
-ParallelTTracker {0}[3]> 12:38:16 Step    213 at   34.988 [mm] t=  2.140e-10 [s] E=   51.108 [MeV] 
+ParallelTTracker {0}[3]> 12:38:16 Step    213 at   34.988 [mm] t=  2.140e-10 [s] E=   51.108 [MeV]
 ParallelTTracker {0}> --- CollimatorPhysics - Type is DEGRADER Name DEG1 Material Graphite Particles in material 30
 ParallelTTracker {0}> Coll/Deg statistics:  bunch to material 0 redifused 3 stopped 0
-ParallelTTracker {0}[3]> 12:38:17 Step    214 at   35.083 [mm] t=  2.150e-10 [s] E=   51.108 [MeV] 
+ParallelTTracker {0}[3]> 12:38:17 Step    214 at   35.083 [mm] t=  2.150e-10 [s] E=   51.108 [MeV]
 ParallelTTracker {0}> --- CollimatorPhysics - Type is DEGRADER Name DEG1 Material Graphite Particles in material 29
 ParallelTTracker {0}> Coll/Deg statistics:  bunch to material 0 redifused 1 stopped 0
-ParallelTTracker {0}[3]> 12:38:17 Step    215 at   35.178 [mm] t=  2.160e-10 [s] E=   51.108 [MeV] 
+ParallelTTracker {0}[3]> 12:38:17 Step    215 at   35.178 [mm] t=  2.160e-10 [s] E=   51.108 [MeV]
 ParallelTTracker {0}> --- CollimatorPhysics - Type is DEGRADER Name DEG1 Material Graphite Particles in material 28
 ParallelTTracker {0}> Coll/Deg statistics:  bunch to material 0 redifused 1 stopped 0
-ParallelTTracker {0}[3]> 12:38:17 Step    216 at   35.273 [mm] t=  2.170e-10 [s] E=   51.108 [MeV] 
+ParallelTTracker {0}[3]> 12:38:17 Step    216 at   35.273 [mm] t=  2.170e-10 [s] E=   51.108 [MeV]
 ParallelTTracker {0}> --- CollimatorPhysics - Type is DEGRADER Name DEG1 Material Graphite Particles in material 28
 ParallelTTracker {0}> Coll/Deg statistics:  bunch to material 0 redifused 0 stopped 0
-ParallelTTracker {0}[3]> 12:38:17 Step    217 at   35.368 [mm] t=  2.180e-10 [s] E=   51.108 [MeV] 
+ParallelTTracker {0}[3]> 12:38:17 Step    217 at   35.368 [mm] t=  2.180e-10 [s] E=   51.108 [MeV]
 ParallelTTracker {0}> --- CollimatorPhysics - Type is DEGRADER Name DEG1 Material Graphite Particles in material 28
 ParallelTTracker {0}> Coll/Deg statistics:  bunch to material 0 redifused 0 stopped 0
-ParallelTTracker {0}[3]> 12:38:18 Step    218 at   35.463 [mm] t=  2.190e-10 [s] E=   51.108 [MeV] 
+ParallelTTracker {0}[3]> 12:38:18 Step    218 at   35.463 [mm] t=  2.190e-10 [s] E=   51.108 [MeV]
 ParallelTTracker {0}> --- CollimatorPhysics - Type is DEGRADER Name DEG1 Material Graphite Particles in material 28
 ParallelTTracker {0}> Coll/Deg statistics:  bunch to material 0 redifused 0 stopped 0
-ParallelTTracker {0}[3]> 12:38:18 Step    219 at   35.558 [mm] t=  2.200e-10 [s] E=   51.108 [MeV] 
+ParallelTTracker {0}[3]> 12:38:18 Step    219 at   35.558 [mm] t=  2.200e-10 [s] E=   51.108 [MeV]
 ParallelTTracker {0}> --- CollimatorPhysics - Type is DEGRADER Name DEG1 Material Graphite Particles in material 28
 ParallelTTracker {0}> Coll/Deg statistics:  bunch to material 0 redifused 0 stopped 0
-ParallelTTracker {0}[3]> 12:38:18 Step    220 at   35.653 [mm] t=  2.210e-10 [s] E=   51.108 [MeV] 
+ParallelTTracker {0}[3]> 12:38:18 Step    220 at   35.653 [mm] t=  2.210e-10 [s] E=   51.108 [MeV]
 OPAL {0}[3]> * Wrote beam phase space.
-OPAL {0}> 
-OPAL {0}> * ************** B U N C H ********************************************************* 
+OPAL {0}>
+OPAL {0}> * ************** B U N C H *********************************************************
 OPAL {0}> * NP              =   999972
 OPAL {0}> * Qtot            =    3.94990e-02 [nC]       Qi    =  3.95001e-08 [nC]
 OPAL {0}> * Ekin            =    5.11080e+01 [MeV]      dEkin =  6.22468e-01 [MeV]
@@ -1129,39 +1129,39 @@ OPAL {0}> * hr              = (  5.60528e-04 ,  5.27176e-04 ,  1.09602e-04 ) [m]
 OPAL {0}> * dh              =    1.00000e-10 [%]
 OPAL {0}> * t               =    2.21000e-10 [s]        dT    =  1.00000e-12 [s]
 OPAL {0}> * spos            =    3.56530e-02 [m]
-OPAL {0}> * ********************************************************************************** 
-OPAL {0}> 
+OPAL {0}> * **********************************************************************************
+OPAL {0}>
 OPAL {0}[3]> * Wrote beam statistics.
 ParallelTTracker {0}> --- CollimatorPhysics - Type is DEGRADER Name DEG1 Material Graphite Particles in material 28
 ParallelTTracker {0}> Coll/Deg statistics:  bunch to material 0 redifused 0 stopped 0
-ParallelTTracker {0}[3]> 12:38:19 Step    221 at   35.748 [mm] t=  2.220e-10 [s] E=   51.108 [MeV] 
+ParallelTTracker {0}[3]> 12:38:19 Step    221 at   35.748 [mm] t=  2.220e-10 [s] E=   51.108 [MeV]
 ParallelTTracker {0}> --- CollimatorPhysics - Type is DEGRADER Name DEG1 Material Graphite Particles in material 28
 ParallelTTracker {0}> Coll/Deg statistics:  bunch to material 0 redifused 0 stopped 0
-ParallelTTracker {0}[3]> 12:38:19 Step    222 at   35.843 [mm] t=  2.230e-10 [s] E=   51.108 [MeV] 
+ParallelTTracker {0}[3]> 12:38:19 Step    222 at   35.843 [mm] t=  2.230e-10 [s] E=   51.108 [MeV]
 ParallelTTracker {0}> --- CollimatorPhysics - Type is DEGRADER Name DEG1 Material Graphite Particles in material 28
 ParallelTTracker {0}> Coll/Deg statistics:  bunch to material 0 redifused 0 stopped 0
-ParallelTTracker {0}[3]> 12:38:19 Step    223 at   35.938 [mm] t=  2.240e-10 [s] E=   51.108 [MeV] 
+ParallelTTracker {0}[3]> 12:38:19 Step    223 at   35.938 [mm] t=  2.240e-10 [s] E=   51.108 [MeV]
 ParallelTTracker {0}> --- CollimatorPhysics - Type is DEGRADER Name DEG1 Material Graphite Particles in material 28
 ParallelTTracker {0}> Coll/Deg statistics:  bunch to material 0 redifused 0 stopped 0
-ParallelTTracker {0}[3]> 12:38:20 Step    224 at   36.033 [mm] t=  2.250e-10 [s] E=   51.108 [MeV] 
+ParallelTTracker {0}[3]> 12:38:20 Step    224 at   36.033 [mm] t=  2.250e-10 [s] E=   51.108 [MeV]
 ParallelTTracker {0}> --- CollimatorPhysics - Type is DEGRADER Name DEG1 Material Graphite Particles in material 28
 ParallelTTracker {0}> Coll/Deg statistics:  bunch to material 0 redifused 0 stopped 0
-ParallelTTracker {0}[3]> 12:38:20 Step    225 at   36.128 [mm] t=  2.260e-10 [s] E=   51.108 [MeV] 
+ParallelTTracker {0}[3]> 12:38:20 Step    225 at   36.128 [mm] t=  2.260e-10 [s] E=   51.108 [MeV]
 ParallelTTracker {0}> --- CollimatorPhysics - Type is DEGRADER Name DEG1 Material Graphite Particles in material 28
 ParallelTTracker {0}> Coll/Deg statistics:  bunch to material 0 redifused 0 stopped 0
-ParallelTTracker {0}[3]> 12:38:20 Step    226 at   36.223 [mm] t=  2.270e-10 [s] E=   51.108 [MeV] 
+ParallelTTracker {0}[3]> 12:38:20 Step    226 at   36.223 [mm] t=  2.270e-10 [s] E=   51.108 [MeV]
 ParallelTTracker {0}> --- CollimatorPhysics - Type is DEGRADER Name DEG1 Material Graphite Particles in material 28
 ParallelTTracker {0}> Coll/Deg statistics:  bunch to material 0 redifused 0 stopped 0
-ParallelTTracker {0}[3]> 12:38:20 Step    227 at   36.318 [mm] t=  2.280e-10 [s] E=   51.108 [MeV] 
+ParallelTTracker {0}[3]> 12:38:20 Step    227 at   36.318 [mm] t=  2.280e-10 [s] E=   51.108 [MeV]
 ParallelTTracker {0}> --- CollimatorPhysics - Type is DEGRADER Name DEG1 Material Graphite Particles in material 28
 ParallelTTracker {0}> Coll/Deg statistics:  bunch to material 0 redifused 0 stopped 0
-ParallelTTracker {0}[3]> 12:38:20 Step    228 at   36.413 [mm] t=  2.290e-10 [s] E=   51.108 [MeV] 
+ParallelTTracker {0}[3]> 12:38:20 Step    228 at   36.413 [mm] t=  2.290e-10 [s] E=   51.108 [MeV]
 ParallelTTracker {0}> --- CollimatorPhysics - Type is DEGRADER Name DEG1 Material Graphite Particles in material 28
 ParallelTTracker {0}> Coll/Deg statistics:  bunch to material 0 redifused 0 stopped 0
-ParallelTTracker {0}[3]> 12:38:21 Step    229 at   36.509 [mm] t=  2.300e-10 [s] E=   51.108 [MeV] 
+ParallelTTracker {0}[3]> 12:38:21 Step    229 at   36.509 [mm] t=  2.300e-10 [s] E=   51.108 [MeV]
 OPAL {0}[3]> * Wrote beam phase space.
-OPAL {0}> 
-OPAL {0}> * ************** B U N C H ********************************************************* 
+OPAL {0}>
+OPAL {0}> * ************** B U N C H *********************************************************
 OPAL {0}> * NP              =   999972
 OPAL {0}> * Qtot            =    3.94990e-02 [nC]       Qi    =  3.95001e-08 [nC]
 OPAL {0}> * Ekin            =    5.11080e+01 [MeV]      dEkin =  6.22468e-01 [MeV]
@@ -1177,8 +1177,8 @@ OPAL {0}> * hr              = (  5.73839e-04 ,  5.35287e-04 ,  1.21455e-04 ) [m]
 OPAL {0}> * dh              =    1.00000e-10 [%]
 OPAL {0}> * t               =    2.30000e-10 [s]        dT    =  1.00000e-12 [s]
 OPAL {0}> * spos            =    3.65085e-02 [m]
-OPAL {0}> * ********************************************************************************** 
-OPAL {0}> 
+OPAL {0}> * **********************************************************************************
+OPAL {0}>
 OPAL {0}[3]> * Wrote beam statistics.
 ParallelTTracker {0}[2]> Dump phase space of last step
 Degrader::goOffline {0}>  done...
@@ -1191,101 +1191,101 @@ Timings{0}> -----------------------------------------------------------------
 Timings{0}>      Timing results for 4 nodes:
 Timings{0}> -----------------------------------------------------------------
 Timings{0}> mainTimer........... Wall tot =    95.7303, CPU tot =      77.07
-Timings{0}> 
+Timings{0}>
 Timings{0}> Binaryrepart........ Wall max =   0.037663, CPU max =       0.04
 Timings{0}>                      Wall avg =    0.03752, CPU avg =     0.0375
 Timings{0}>                      Wall min =   0.037382, CPU min =       0.03
-Timings{0}> 
+Timings{0}>
 Timings{0}> Boundingbox......... Wall max =    6.23472, CPU max =       6.33
 Timings{0}>                      Wall avg =    5.71585, CPU avg =      5.755
 Timings{0}>                      Wall min =    4.75756, CPU min =       4.66
-Timings{0}> 
+Timings{0}>
 Timings{0}> CollPhysApply....... Wall max =    37.8172, CPU max =      37.82
 Timings{0}>                      Wall avg =    37.8086, CPU avg =    37.7825
 Timings{0}>                      Wall min =    37.8015, CPU min =      37.75
-Timings{0}> 
+Timings{0}>
 Timings{0}> CollPhysApplyLoop... Wall max =    36.4362, CPU max =      36.38
 Timings{0}>                      Wall avg =    35.4892, CPU avg =    35.4525
 Timings{0}>                      Wall min =    34.9205, CPU min =      34.85
-Timings{0}> 
+Timings{0}>
 Timings{0}> CreatDistr.......... Wall max =          0, CPU max =          0
 Timings{0}>                      Wall avg =          0, CPU avg =          0
 Timings{0}>                      Wall min =          0, CPU min =          0
-Timings{0}> 
+Timings{0}>
 Timings{0}> Fast inside test.... Wall max =          0, CPU max =          0
 Timings{0}>                      Wall avg =          0, CPU avg =          0
 Timings{0}>                      Wall min =          0, CPU min =          0
-Timings{0}> 
+Timings{0}>
 Timings{0}> Fieldeval........... Wall max =     3.4207, CPU max =       3.48
 Timings{0}>                      Wall avg =    3.17848, CPU avg =      3.215
 Timings{0}>                      Wall min =    2.99181, CPU min =       2.93
-Timings{0}> 
+Timings{0}>
 Timings{0}> H5PartTimer......... Wall max =    19.3926, CPU max =       1.59
 Timings{0}>                      Wall avg =    19.3913, CPU avg =     1.4725
 Timings{0}>                      Wall min =    19.3907, CPU min =       1.35
-Timings{0}> 
+Timings{0}>
 Timings{0}> Histogram........... Wall max =          0, CPU max =          0
 Timings{0}>                      Wall avg =          0, CPU avg =          0
 Timings{0}>                      Wall min =          0, CPU min =          0
-Timings{0}> 
+Timings{0}>
 Timings{0}> Initialize geometry. Wall max =          0, CPU max =          0
 Timings{0}>                      Wall avg =          0, CPU avg =          0
 Timings{0}>                      Wall min =          0, CPU min =          0
-Timings{0}> 
+Timings{0}>
 Timings{0}> Inside test......... Wall max =          0, CPU max =          0
 Timings{0}>                      Wall avg =          0, CPU avg =          0
 Timings{0}>                      Wall min =          0, CPU min =          0
-Timings{0}> 
+Timings{0}>
 Timings{0}> LoadDistr........... Wall max =          0, CPU max =          0
 Timings{0}>                      Wall avg =          0, CPU avg =          0
 Timings{0}>                      Wall min =          0, CPU min =          0
-Timings{0}> 
+Timings{0}>
 Timings{0}> Particle Inside..... Wall max =          0, CPU max =          0
 Timings{0}>                      Wall avg =          0, CPU avg =          0
 Timings{0}>                      Wall min =          0, CPU min =          0
-Timings{0}> 
+Timings{0}>
 Timings{0}> Ray tracing......... Wall max =          0, CPU max =          0
 Timings{0}>                      Wall avg =          0, CPU avg =          0
 Timings{0}>                      Wall min =          0, CPU min =          0
-Timings{0}> 
+Timings{0}>
 Timings{0}> Secondary emission.. Wall max =          0, CPU max =          0
 Timings{0}>                      Wall avg =          0, CPU avg =          0
 Timings{0}>                      Wall min =          0, CPU min =          0
-Timings{0}> 
+Timings{0}>
 Timings{0}> SelfField total..... Wall max =    0.17541, CPU max =       0.18
 Timings{0}>                      Wall avg =   0.133405, CPU avg =     0.1425
 Timings{0}>                      Wall min =   0.091363, CPU min =        0.1
-Timings{0}> 
+Timings{0}>
 Timings{0}> SF: Potential....... Wall max =          0, CPU max =          0
 Timings{0}>                      Wall avg =          0, CPU avg =          0
 Timings{0}>                      Wall min =          0, CPU min =          0
-Timings{0}> 
+Timings{0}>
 Timings{0}> Statistics.......... Wall max =    6.01078, CPU max =       5.92
 Timings{0}>                      Wall avg =    5.83922, CPU avg =      5.805
 Timings{0}>                      Wall min =    5.65561, CPU min =       5.56
-Timings{0}> 
+Timings{0}>
 Timings{0}> StatMarkerTimer..... Wall max =   0.277126, CPU max =       0.29
 Timings{0}>                      Wall avg =    0.27381, CPU avg =     0.2675
 Timings{0}>                      Wall min =   0.272665, CPU min =       0.25
-Timings{0}> 
+Timings{0}>
 Timings{0}> TIntegration1....... Wall max =    10.3606, CPU max =      10.42
 Timings{0}>                      Wall avg =    10.3605, CPU avg =      10.36
 Timings{0}>                      Wall min =    10.3604, CPU min =       10.3
-Timings{0}> 
+Timings{0}>
 Timings{0}> TIntegration1Push... Wall max =    8.30871, CPU max =       8.27
 Timings{0}>                      Wall avg =    8.25269, CPU avg =       8.19
 Timings{0}>                      Wall min =    8.20319, CPU min =       8.08
-Timings{0}> 
+Timings{0}>
 Timings{0}> TIntegration2....... Wall max =    14.4704, CPU max =      14.44
 Timings{0}>                      Wall avg =    14.3945, CPU avg =      14.37
 Timings{0}>                      Wall min =    14.3301, CPU min =      14.31
-Timings{0}> 
+Timings{0}>
 Timings{0}> TIntegration2Push... Wall max =    8.48729, CPU max =       8.48
 Timings{0}>                      Wall avg =    8.41278, CPU avg =       8.41
 Timings{0}>                      Wall min =    8.35276, CPU min =       8.28
-Timings{0}> 
+Timings{0}>
 Timings{0}> WakeField........... Wall max =          0, CPU max =          0
 Timings{0}>                      Wall avg =          0, CPU avg =          0
 Timings{0}>                      Wall min =          0, CPU min =          0
-Timings{0}> 
+Timings{0}>
 Timings{0}> -----------------------------------------------------------------
diff --git a/tests/Kollimator/Degrader/Degrader-1.in b/tests/Kollimator/Degrader/Degrader-1.in
index 008b6bb8df949dc3476a257099f66ec085a53e75..011243f6163ae8588f0809f23a21f5414b2aa658 100644
--- a/tests/Kollimator/Degrader/Degrader-1.in
+++ b/tests/Kollimator/Degrader/Degrader-1.in
@@ -27,12 +27,12 @@ DEGTEST: LINE=(M0,DEG1,M1);
 D1: DISTRIBUTION, DISTRIBUTION=GAUSS,
 SIGMAX=  5.0e-03,   SIGMAPX=0.0,  CORRX=0.0,
 SIGMAY=  5.0e-03,   SIGMAPY=0.0,  CORRY=0.0,
-T     =  0.005,     SIGMAT= 0.0005, 
+T     =  0.005,     SIGMAT= 0.0005,
 SIGMAPT=0.0, CORRT=0.0, R61=0.0, INPUTMOUNITS=EV;
 
-FS1:FIELDSOLVER, FSTYPE=NONE, MX=64, MY=64, MT=64, 
+FS1:FIELDSOLVER, FSTYPE=NONE, MX=64, MY=64, MT=64,
                  PARFFTX=true, PARFFTY=true, PARFFTT=true,
-                 BCFFTX=open, BCFFTY=open, BCFFTT=open, 
+                 BCFFTX=open, BCFFTY=open, BCFFTT=open,
                  BBOXINCR=1, GREENSF=STANDARD;
 
 BEAM1: BEAM, PARTICLE=PROTON, PC=P0, NPART=1E6, BCURRENT=2.0e-03, BFREQ=rf, CHARGE=1;
diff --git a/tests/Kollimator/Degrader/Degrader-1.sge b/tests/Kollimator/Degrader/Degrader-1.sge
index a1b8712c4b0d0be15f80a01e36bcc310a3ae47c0..4319260c6680227ee5f13d828f312d581534914b 100644
--- a/tests/Kollimator/Degrader/Degrader-1.sge
+++ b/tests/Kollimator/Degrader/Degrader-1.sge
@@ -6,7 +6,7 @@
 #$ -v LD_LIBRARY_PATH,OPAL_EXE_PATH,OPENMPI,REG_TEST_DIR
 
 MACHINE_FILE=$TMPDIR/machinefile
-awk '/^merlin/ {print $1" slots="$2}' $PE_HOSTFILE > $MACHINE_FILE 
+awk '/^merlin/ {print $1" slots="$2}' $PE_HOSTFILE > $MACHINE_FILE
 cp $MACHINE_FILE machinefile.last
 
 cd $REG_TEST_DIR
diff --git a/tests/Kollimator/Degrader/reference/Degrader-1.lbal b/tests/Kollimator/Degrader/reference/Degrader-1.lbal
index 6e1456d3a1b9e0a1793335e9a3298fdd62b88a36..4f9ea86257503789eb02165288084ec80bf05766 100644
--- a/tests/Kollimator/Degrader/reference/Degrader-1.lbal
+++ b/tests/Kollimator/Degrader/reference/Degrader-1.lbal
@@ -1,25 +1,25 @@
 # 4
-251711         	249251         	249803         	249235         	
-251711         	249251         	249803         	249235         	
-251711         	249251         	249803         	249235         	
-251711         	249251         	249803         	249235         	
-251711         	249251         	249803         	249235         	
-251711         	249251         	249803         	249235         	
-251711         	249251         	249803         	249235         	
-251711         	249251         	249803         	249235         	
-251711         	249251         	249803         	249235         	
-251711         	249251         	249803         	249235         	
-251711         	249251         	249803         	249235         	
-251711         	249251         	249803         	249235         	
-251711         	249251         	249803         	249235         	
-211380         	209328         	209973         	209210         	
-26696         	26630         	26738         	27042         	
-558         	619         	607         	670         	
-81700         	79779         	82478         	81679         	
-251772         	238260         	242227         	230729         	
-300494         	223378         	272346         	203712         	
-270454         	193007         	312186         	224302         	
-272891         	187145         	319390         	220531         	
-275103         	181469         	326711         	216684         	
-293715         	185933         	317812         	202512         	
-298958         	182042         	321731         	197243         	
+251711         	249251         	249803         	249235
+251711         	249251         	249803         	249235
+251711         	249251         	249803         	249235
+251711         	249251         	249803         	249235
+251711         	249251         	249803         	249235
+251711         	249251         	249803         	249235
+251711         	249251         	249803         	249235
+251711         	249251         	249803         	249235
+251711         	249251         	249803         	249235
+251711         	249251         	249803         	249235
+251711         	249251         	249803         	249235
+251711         	249251         	249803         	249235
+251711         	249251         	249803         	249235
+211380         	209328         	209973         	209210
+26696         	26630         	26738         	27042
+558         	619         	607         	670
+81700         	79779         	82478         	81679
+251772         	238260         	242227         	230729
+300494         	223378         	272346         	203712
+270454         	193007         	312186         	224302
+272891         	187145         	319390         	220531
+275103         	181469         	326711         	216684
+293715         	185933         	317812         	202512
+298958         	182042         	321731         	197243
diff --git a/tests/Kollimator/Degrader/reference/Degrader-1.out b/tests/Kollimator/Degrader/reference/Degrader-1.out
index 09b908eabdecdfe3bf89c9e6954b0237b054b708..fa699e10f6f46bc2c64e16a8bf83ac854ec921f4 100644
--- a/tests/Kollimator/Degrader/reference/Degrader-1.out
+++ b/tests/Kollimator/Degrader/reference/Degrader-1.out
@@ -6,46 +6,46 @@ Ippl> CommMPI: Child 1 ready.
 Ippl> CommMPI: Child 2 ready.
 Ippl> CommMPI: Child 3 ready.
 Ippl> CommMPI: Initialization complete.
-{0}>                ____  _____       ___ 
-{0}>               / __ \|  __ \ /\   | | 
+{0}>                ____  _____       ___
+{0}>               / __ \|  __ \ /\   | |
 {0}>              | |  | | |__) /  \  | |
 {0}>              | |  | |  ___/ /\ \ | |
 {0}>              | |__| | |  / ____ \| |____
 {0}>               \____/|_| /_/    \_\______|
-OPAL{0}> 
+OPAL{0}>
 OPAL{0}> This is OPAL (Object Oriented Parallel Accelerator Library) Version 1.3.99.1
-OPAL{0}> 
+OPAL{0}>
 OPAL{0}>                 (c) PSI, http://amas.web.psi.ch
-OPAL{0}> 
-OPAL{0}> Please send cookies, goodies or other motivations (wine and beer ... ) 
+OPAL{0}>
+OPAL{0}> Please send cookies, goodies or other motivations (wine and beer ... )
 OPAL{0}> to the OPAL developers opal@lists.psi.ch
-OPAL{0}> 
+OPAL{0}>
 OPAL{0}> Time: 12:36:50 date: 24/09/2015
-OPAL{0}> 
+OPAL{0}>
 OPAL{0}> Couldn't find startup file "/Users/adelmann/init.opal".
 OPAL{0}> Note: this is not mandatory for an OPAL simulation!
-OPAL{0}> 
+OPAL{0}>
 OPAL{0}> * Reading input stream "Degrader-1.in".
-OPAL{0}> 
+OPAL{0}>
 OPAL{0}> value: {GAMMA,BRHO,EDES,BETA,GAMBET}={1.07674,1.2494,0.072,0.370752,0.399202}
-OPAL{0}> 
-OPAL{0}> * ************* S U R F A C E P H Y S I C S **************************************** 
-OPAL{0}> * SurfacePhysics::initSurfacePhysicsHandler 
-OPAL{0}> * ********************************************************************************** 
-OPAL{0}> * ************* S U R F A C E P H Y S I C S **************************************** 
+OPAL{0}>
+OPAL{0}> * ************* S U R F A C E P H Y S I C S ****************************************
+OPAL{0}> * SurfacePhysics::initSurfacePhysicsHandler
+OPAL{0}> * **********************************************************************************
+OPAL{0}> * ************* S U R F A C E P H Y S I C S ****************************************
 OPAL{0}> * SURFACEPHYSICS DEG1_sphys
 OPAL{0}> * MATERIAL       Graphite
 OPAL{0}> * RADIUS         0
 OPAL{0}> * SIGMA          0
 OPAL{0}> * TAU            0
-OPAL{0}> * ********************************************************************************** 
-OPAL{0}> 
-OPAL{0}[3]> 
+OPAL{0}> * **********************************************************************************
+OPAL{0}>
+OPAL{0}[3]>
 OPAL{0}[3]> 5 elements selected.
-OPAL{0}[3]> 
-OPAL{0}> * ********************************************************************************** 
+OPAL{0}[3]>
+OPAL{0}> * **********************************************************************************
 OPAL{0}> * Selected Tracking Method == PARALLEL-T, NEW TRACK
-OPAL{0}> * ********************************************************************************** 
+OPAL{0}> * **********************************************************************************
 Ippl{0}> no solver attached
 Ippl{0}[3]> BC set for normal Beam
 OPAL{0}> * m before gsl_linalg_cholesky_decomp
@@ -63,11 +63,11 @@ OPAL{0}> * r(3, : ) =          0 &          0 &          0 &          1 &
 OPAL{0}> * r(4, : ) =          0 &          0 &          0 &          0 &          1 &          0 \\
 OPAL{0}> * r(5, : ) =          0 &          0 &          0 &          0 &          0 &          1 \\
 OPAL{0}> * ************* D I S T R I B U T I O N ********************************************
-OPAL{0}> * 
+OPAL{0}> *
 OPAL{0}> * Number of particles: 1000000
-OPAL{0}> * 
+OPAL{0}> *
 OPAL{0}> * Distribution type: GAUSS
-OPAL{0}> * 
+OPAL{0}> *
 OPAL{0}> * SIGMAX   = 0.005 [m]
 OPAL{0}> * SIGMAY   = 0.005 [m]
 OPAL{0}> * SIGMAZ   = 0.0005 [m]
@@ -88,23 +88,23 @@ OPAL{0}> * CUTOFFZ  = 3 [units of SIGMAZ]
 OPAL{0}> * CUTOFFPX = 3 [units of SIGMAPX]
 OPAL{0}> * CUTOFFPY = 3 [units of SIGMAPY]
 OPAL{0}> * CUTOFFPZ = 3 [units of SIGMAPY]
-OPAL{0}> * 
+OPAL{0}> *
 OPAL{0}> * Distribution is injected.
-OPAL{0}> * 
+OPAL{0}> *
 OPAL{0}> * **********************************************************************************
-OPAL{0}> 
-OPAL{0}> * ************* B E A M ************************************************************ 
+OPAL{0}>
+OPAL{0}> * ************* B E A M ************************************************************
 OPAL{0}> * BEAM        BEAM1
 OPAL{0}> * PARTICLE    PROTON
 OPAL{0}> * CURRENT     0.002 A
 OPAL{0}> * FREQUENCY   5.063e+07 Hz
-OPAL{0}> * CHARGE      +e * 1 
+OPAL{0}> * CHARGE      +e * 1
 OPAL{0}> * REST MASS   0.9383 GeV
 OPAL{0}> * MOMENTUM    0.3746
 OPAL{0}> * NPART       1e+06
-OPAL{0}> * ********************************************************************************** 
-OPAL{0}> 
-OPAL{0}> * ************* F I E L D S O L V E R ********************************************** 
+OPAL{0}> * **********************************************************************************
+OPAL{0}>
+OPAL{0}> * ************* F I E L D S O L V E R **********************************************
 OPAL{0}> * FIELDSOLVER  FS1
 OPAL{0}> * TYPE         NONE
 OPAL{0}> * N-PROCESSORS 4
@@ -112,9 +112,9 @@ OPAL{0}> * MX           64
 OPAL{0}> * MY           64
 OPAL{0}> * MT           64
 OPAL{0}> * BBOXINCR     1
-OPAL{0}> * XDIM         parallel  
-OPAL{0}> * YDIM         parallel  
-OPAL{0}> * Z(T)DIM      parallel  
+OPAL{0}> * XDIM         parallel
+OPAL{0}> * YDIM         parallel
+OPAL{0}> * Z(T)DIM      parallel
 Ippl{0}[3]> ======UniformCartesian<3,MFLOAT>==begin======
 Ippl{0}[3]> gridSizes[0] = 65
 Ippl{0}[3]> gridSizes[1] = 65
@@ -133,9 +133,9 @@ Ippl{0}[3]> Dvc[6] = ( -525.977 , 525.569 , 5250.03 )
 Ippl{0}[3]> Dvc[7] = ( 525.977 , 525.569 , 5250.03 )
 Ippl{0}[3]> cell volume = 1.07662e-11
 Ippl{0}[3]> ======UniformCartesian<3,MFLOAT>==end========
-Ippl{0}[3]> 
+Ippl{0}[3]>
 Ippl{0}[3]> ParticleSpatialLayout, with particle distribution:
-Ippl{0}[3]>     Number of particles 251711  Number of particles 249251  Number of particles 249803  Number of particles 249235  
+Ippl{0}[3]>     Number of particles 251711  Number of particles 249251  Number of particles 249803  Number of particles 249235
 Ippl{0}[3]> SpatialLayout decomposition = Total Domain = {[-0.0152028,0.0152168),[-0.0152151,0.0152281),[0.0034762,0.00652381)}
 Ippl{0}[3]> Local Rnodes = 1
 Ippl{0}[3]>  rnode 0 : {[-0.0152028,6.99247e-06),[-0.0152151,6.53305e-06),[0.0034762,0.00652381)}
@@ -152,11 +152,11 @@ Ippl{0}[3]> Remote Vnodes = 3
 Ippl{0}[3]>  vnode 0 : Node = 1 ; vnode_m = 1 ; Domain = {[0:31:1],[32:63:1],[0:63:1]}
 Ippl{0}[3]>  vnode 1 : Node = 2 ; vnode_m = 2 ; Domain = {[32:63:1],[0:31:1],[0:63:1]}
 Ippl{0}[3]>  vnode 2 : Node = 3 ; vnode_m = 3 ; Domain = {[32:63:1],[32:63:1],[0:63:1]}
-Ippl{0}[3]> 
-OPAL{0}> * ********************************************************************************** 
-OPAL{0}> 
-OPAL{0}> 
-OPAL{0}> * ************** B U N C H ********************************************************* 
+Ippl{0}[3]>
+OPAL{0}> * **********************************************************************************
+OPAL{0}>
+OPAL{0}>
+OPAL{0}> * ************** B U N C H *********************************************************
 OPAL{0}> * NP              =   1000000
 OPAL{0}> * Qtot            =    3.95001e-02 [nC]       Qi    =  3.95001e-08 [nC]
 OPAL{0}> * Ekin            =    7.20000e+01 [MeV]      dEkin =  0.00000e+00 [MeV]
@@ -172,33 +172,33 @@ OPAL{0}> * hr              = (  4.75306e-04 ,  4.75675e-04 ,  4.76188e-05 ) [m]
 OPAL{0}> * dh              =    1.00000e-10 [%]
 OPAL{0}> * t               =    0.00000e+00 [s]        dT    =  1.00000e-12 [s]
 OPAL{0}> * spos            =    5.00044e-03 [m]
-OPAL{0}> * ********************************************************************************** 
-OPAL{0}> 
+OPAL{0}> * **********************************************************************************
+OPAL{0}>
 OPAL{0}[2]> Phase space dump frequency 10 and statistics dump frequency 10 w.r.t. the time step.
 OPAL{0}> Track start at: 12:36:52, t= 0; zstop at: 1e+06 [m]
 OPAL{0}> Executing ParallelTTracker, initial DT 1e-12 [s];
 OPAL{0}> max integration steps 230, next step= 0
 OPAL{0}> Using default (Boris-Buneman) integrator
-OPAL{0}> 
+OPAL{0}>
 OPAL{0}> --- BEGIN FIELD LIST ---------------------------------------------------------------
-OPAL{0}> 
+OPAL{0}>
 OPAL{0}> --- 0.005 m -- 0.015 m -- ----------------------------------------------------------
 OPAL{0}> M0
 OPAL{0}> --- 0.02 m -- 0.03 m --  has surface physics ---------------------------------------
 OPAL{0}> DEG1
 OPAL{0}> --- 0.03 m -- 0.04 m -- ------------------------------------------------------------
 OPAL{0}> M1
-OPAL{0}> 
+OPAL{0}>
 OPAL{0}> --- END FIELD LIST -----------------------------------------------------------------
-OPAL{0}> 
+OPAL{0}>
 ParallelTTracker {0}[2]> MINBINEMITTED 1
 ParallelTTracker {0}[2]> MINSTEPFORREBIN 200
 ParallelTTracker {0}[2]> SURFACEEMISSIONSTOP after 1000 seconds
 ParallelTTracker {0}[2]> REPARTFREQ 1000
-ParallelTTracker {0}[3]> 12:36:52 Step      0 at    5.112 [mm] t=  1.000e-12 [s] E=   72.000 [MeV] 
+ParallelTTracker {0}[3]> 12:36:52 Step      0 at    5.112 [mm] t=  1.000e-12 [s] E=   72.000 [MeV]
 OPAL {0}[3]> * Wrote beam phase space.
-OPAL {0}> 
-OPAL {0}> * ************** B U N C H ********************************************************* 
+OPAL {0}>
+OPAL {0}> * ************** B U N C H *********************************************************
 OPAL {0}> * NP              =   1000000
 OPAL {0}> * Qtot            =    3.95001e-02 [nC]       Qi    =  3.95001e-08 [nC]
 OPAL {0}> * Ekin            =    7.20000e+01 [MeV]      dEkin =  0.00000e+00 [MeV]
@@ -214,22 +214,22 @@ OPAL {0}> * hr              = (  4.75306e-04 ,  4.75675e-04 ,  4.76188e-05 ) [m]
 OPAL {0}> * dh              =    1.00000e-10 [%]
 OPAL {0}> * t               =    1.00000e-12 [s]        dT    =  1.00000e-12 [s]
 OPAL {0}> * spos            =    5.11159e-03 [m]
-OPAL {0}> * ********************************************************************************** 
-OPAL {0}> 
+OPAL {0}> * **********************************************************************************
+OPAL {0}>
 OPAL {0}[3]> * Wrote beam statistics.
-ParallelTTracker {0}[3]> 12:36:53 Step      1 at    5.223 [mm] t=  2.000e-12 [s] E=   72.000 [MeV] 
-ParallelTTracker {0}[3]> 12:36:53 Step      2 at    5.334 [mm] t=  3.000e-12 [s] E=   72.000 [MeV] 
-ParallelTTracker {0}[3]> 12:36:53 Step      3 at    5.445 [mm] t=  4.000e-12 [s] E=   72.000 [MeV] 
-ParallelTTracker {0}[3]> 12:36:54 Step      4 at    5.556 [mm] t=  5.000e-12 [s] E=   72.000 [MeV] 
-ParallelTTracker {0}[3]> 12:36:54 Step      5 at    5.667 [mm] t=  6.000e-12 [s] E=   72.000 [MeV] 
-ParallelTTracker {0}[3]> 12:36:54 Step      6 at    5.778 [mm] t=  7.000e-12 [s] E=   72.000 [MeV] 
-ParallelTTracker {0}[3]> 12:36:54 Step      7 at    5.890 [mm] t=  8.000e-12 [s] E=   72.000 [MeV] 
-ParallelTTracker {0}[3]> 12:36:54 Step      8 at    6.001 [mm] t=  9.000e-12 [s] E=   72.000 [MeV] 
-ParallelTTracker {0}[3]> 12:36:55 Step      9 at    6.112 [mm] t=  1.000e-11 [s] E=   72.000 [MeV] 
-ParallelTTracker {0}[3]> 12:36:55 Step     10 at    6.223 [mm] t=  1.100e-11 [s] E=   72.000 [MeV] 
+ParallelTTracker {0}[3]> 12:36:53 Step      1 at    5.223 [mm] t=  2.000e-12 [s] E=   72.000 [MeV]
+ParallelTTracker {0}[3]> 12:36:53 Step      2 at    5.334 [mm] t=  3.000e-12 [s] E=   72.000 [MeV]
+ParallelTTracker {0}[3]> 12:36:53 Step      3 at    5.445 [mm] t=  4.000e-12 [s] E=   72.000 [MeV]
+ParallelTTracker {0}[3]> 12:36:54 Step      4 at    5.556 [mm] t=  5.000e-12 [s] E=   72.000 [MeV]
+ParallelTTracker {0}[3]> 12:36:54 Step      5 at    5.667 [mm] t=  6.000e-12 [s] E=   72.000 [MeV]
+ParallelTTracker {0}[3]> 12:36:54 Step      6 at    5.778 [mm] t=  7.000e-12 [s] E=   72.000 [MeV]
+ParallelTTracker {0}[3]> 12:36:54 Step      7 at    5.890 [mm] t=  8.000e-12 [s] E=   72.000 [MeV]
+ParallelTTracker {0}[3]> 12:36:54 Step      8 at    6.001 [mm] t=  9.000e-12 [s] E=   72.000 [MeV]
+ParallelTTracker {0}[3]> 12:36:55 Step      9 at    6.112 [mm] t=  1.000e-11 [s] E=   72.000 [MeV]
+ParallelTTracker {0}[3]> 12:36:55 Step     10 at    6.223 [mm] t=  1.100e-11 [s] E=   72.000 [MeV]
 OPAL {0}[3]> * Wrote beam phase space.
-OPAL {0}> 
-OPAL {0}> * ************** B U N C H ********************************************************* 
+OPAL {0}>
+OPAL {0}> * ************** B U N C H *********************************************************
 OPAL {0}> * NP              =   1000000
 OPAL {0}> * Qtot            =    3.95001e-02 [nC]       Qi    =  3.95001e-08 [nC]
 OPAL {0}> * Ekin            =    7.20000e+01 [MeV]      dEkin =  0.00000e+00 [MeV]
@@ -245,22 +245,22 @@ OPAL {0}> * hr              = (  4.75306e-04 ,  4.75675e-04 ,  4.76188e-05 ) [m]
 OPAL {0}> * dh              =    1.00000e-10 [%]
 OPAL {0}> * t               =    1.10000e-11 [s]        dT    =  1.00000e-12 [s]
 OPAL {0}> * spos            =    6.22308e-03 [m]
-OPAL {0}> * ********************************************************************************** 
-OPAL {0}> 
+OPAL {0}> * **********************************************************************************
+OPAL {0}>
 OPAL {0}[3]> * Wrote beam statistics.
-ParallelTTracker {0}[3]> 12:36:56 Step     11 at    6.334 [mm] t=  1.200e-11 [s] E=   72.000 [MeV] 
-ParallelTTracker {0}[3]> 12:36:56 Step     12 at    6.445 [mm] t=  1.300e-11 [s] E=   72.000 [MeV] 
-ParallelTTracker {0}[3]> 12:36:56 Step     13 at    6.557 [mm] t=  1.400e-11 [s] E=   72.000 [MeV] 
-ParallelTTracker {0}[3]> 12:36:56 Step     14 at    6.668 [mm] t=  1.500e-11 [s] E=   72.000 [MeV] 
-ParallelTTracker {0}[3]> 12:36:57 Step     15 at    6.779 [mm] t=  1.600e-11 [s] E=   72.000 [MeV] 
-ParallelTTracker {0}[3]> 12:36:57 Step     16 at    6.890 [mm] t=  1.700e-11 [s] E=   72.000 [MeV] 
-ParallelTTracker {0}[3]> 12:36:57 Step     17 at    7.001 [mm] t=  1.800e-11 [s] E=   72.000 [MeV] 
-ParallelTTracker {0}[3]> 12:36:57 Step     18 at    7.112 [mm] t=  1.900e-11 [s] E=   72.000 [MeV] 
-ParallelTTracker {0}[3]> 12:36:57 Step     19 at    7.223 [mm] t=  2.000e-11 [s] E=   72.000 [MeV] 
-ParallelTTracker {0}[3]> 12:36:57 Step     20 at    7.335 [mm] t=  2.100e-11 [s] E=   72.000 [MeV] 
+ParallelTTracker {0}[3]> 12:36:56 Step     11 at    6.334 [mm] t=  1.200e-11 [s] E=   72.000 [MeV]
+ParallelTTracker {0}[3]> 12:36:56 Step     12 at    6.445 [mm] t=  1.300e-11 [s] E=   72.000 [MeV]
+ParallelTTracker {0}[3]> 12:36:56 Step     13 at    6.557 [mm] t=  1.400e-11 [s] E=   72.000 [MeV]
+ParallelTTracker {0}[3]> 12:36:56 Step     14 at    6.668 [mm] t=  1.500e-11 [s] E=   72.000 [MeV]
+ParallelTTracker {0}[3]> 12:36:57 Step     15 at    6.779 [mm] t=  1.600e-11 [s] E=   72.000 [MeV]
+ParallelTTracker {0}[3]> 12:36:57 Step     16 at    6.890 [mm] t=  1.700e-11 [s] E=   72.000 [MeV]
+ParallelTTracker {0}[3]> 12:36:57 Step     17 at    7.001 [mm] t=  1.800e-11 [s] E=   72.000 [MeV]
+ParallelTTracker {0}[3]> 12:36:57 Step     18 at    7.112 [mm] t=  1.900e-11 [s] E=   72.000 [MeV]
+ParallelTTracker {0}[3]> 12:36:57 Step     19 at    7.223 [mm] t=  2.000e-11 [s] E=   72.000 [MeV]
+ParallelTTracker {0}[3]> 12:36:57 Step     20 at    7.335 [mm] t=  2.100e-11 [s] E=   72.000 [MeV]
 OPAL {0}[3]> * Wrote beam phase space.
-OPAL {0}> 
-OPAL {0}> * ************** B U N C H ********************************************************* 
+OPAL {0}>
+OPAL {0}> * ************** B U N C H *********************************************************
 OPAL {0}> * NP              =   1000000
 OPAL {0}> * Qtot            =    3.95001e-02 [nC]       Qi    =  3.95001e-08 [nC]
 OPAL {0}> * Ekin            =    7.20000e+01 [MeV]      dEkin =  0.00000e+00 [MeV]
@@ -276,22 +276,22 @@ OPAL {0}> * hr              = (  4.75306e-04 ,  4.75675e-04 ,  4.76188e-05 ) [m]
 OPAL {0}> * dh              =    1.00000e-10 [%]
 OPAL {0}> * t               =    2.10000e-11 [s]        dT    =  1.00000e-12 [s]
 OPAL {0}> * spos            =    7.33456e-03 [m]
-OPAL {0}> * ********************************************************************************** 
-OPAL {0}> 
+OPAL {0}> * **********************************************************************************
+OPAL {0}>
 OPAL {0}[3]> * Wrote beam statistics.
-ParallelTTracker {0}[3]> 12:36:59 Step     21 at    7.446 [mm] t=  2.200e-11 [s] E=   72.000 [MeV] 
-ParallelTTracker {0}[3]> 12:36:59 Step     22 at    7.557 [mm] t=  2.300e-11 [s] E=   72.000 [MeV] 
-ParallelTTracker {0}[3]> 12:36:59 Step     23 at    7.668 [mm] t=  2.400e-11 [s] E=   72.000 [MeV] 
-ParallelTTracker {0}[3]> 12:36:59 Step     24 at    7.779 [mm] t=  2.500e-11 [s] E=   72.000 [MeV] 
-ParallelTTracker {0}[3]> 12:36:59 Step     25 at    7.890 [mm] t=  2.600e-11 [s] E=   72.000 [MeV] 
-ParallelTTracker {0}[3]> 12:37:00 Step     26 at    8.001 [mm] t=  2.700e-11 [s] E=   72.000 [MeV] 
-ParallelTTracker {0}[3]> 12:37:00 Step     27 at    8.113 [mm] t=  2.800e-11 [s] E=   72.000 [MeV] 
-ParallelTTracker {0}[3]> 12:37:00 Step     28 at    8.224 [mm] t=  2.900e-11 [s] E=   72.000 [MeV] 
-ParallelTTracker {0}[3]> 12:37:00 Step     29 at    8.335 [mm] t=  3.000e-11 [s] E=   72.000 [MeV] 
-ParallelTTracker {0}[3]> 12:37:00 Step     30 at    8.446 [mm] t=  3.100e-11 [s] E=   72.000 [MeV] 
+ParallelTTracker {0}[3]> 12:36:59 Step     21 at    7.446 [mm] t=  2.200e-11 [s] E=   72.000 [MeV]
+ParallelTTracker {0}[3]> 12:36:59 Step     22 at    7.557 [mm] t=  2.300e-11 [s] E=   72.000 [MeV]
+ParallelTTracker {0}[3]> 12:36:59 Step     23 at    7.668 [mm] t=  2.400e-11 [s] E=   72.000 [MeV]
+ParallelTTracker {0}[3]> 12:36:59 Step     24 at    7.779 [mm] t=  2.500e-11 [s] E=   72.000 [MeV]
+ParallelTTracker {0}[3]> 12:36:59 Step     25 at    7.890 [mm] t=  2.600e-11 [s] E=   72.000 [MeV]
+ParallelTTracker {0}[3]> 12:37:00 Step     26 at    8.001 [mm] t=  2.700e-11 [s] E=   72.000 [MeV]
+ParallelTTracker {0}[3]> 12:37:00 Step     27 at    8.113 [mm] t=  2.800e-11 [s] E=   72.000 [MeV]
+ParallelTTracker {0}[3]> 12:37:00 Step     28 at    8.224 [mm] t=  2.900e-11 [s] E=   72.000 [MeV]
+ParallelTTracker {0}[3]> 12:37:00 Step     29 at    8.335 [mm] t=  3.000e-11 [s] E=   72.000 [MeV]
+ParallelTTracker {0}[3]> 12:37:00 Step     30 at    8.446 [mm] t=  3.100e-11 [s] E=   72.000 [MeV]
 OPAL {0}[3]> * Wrote beam phase space.
-OPAL {0}> 
-OPAL {0}> * ************** B U N C H ********************************************************* 
+OPAL {0}>
+OPAL {0}> * ************** B U N C H *********************************************************
 OPAL {0}> * NP              =   1000000
 OPAL {0}> * Qtot            =    3.95001e-02 [nC]       Qi    =  3.95001e-08 [nC]
 OPAL {0}> * Ekin            =    7.20000e+01 [MeV]      dEkin =  0.00000e+00 [MeV]
@@ -307,23 +307,23 @@ OPAL {0}> * hr              = (  4.75306e-04 ,  4.75675e-04 ,  4.76188e-05 ) [m]
 OPAL {0}> * dh              =    1.00000e-10 [%]
 OPAL {0}> * t               =    3.10000e-11 [s]        dT    =  1.00000e-12 [s]
 OPAL {0}> * spos            =    8.44605e-03 [m]
-OPAL {0}> * ********************************************************************************** 
-OPAL {0}> 
+OPAL {0}> * **********************************************************************************
+OPAL {0}>
 OPAL {0}[3]> * Wrote beam statistics.
 Ippl{0}[3]> DEG1 gone live
-ParallelTTracker {0}[3]> 12:37:03 Step     31 at    8.557 [mm] t=  3.200e-11 [s] E=   72.000 [MeV] 
-ParallelTTracker {0}[3]> 12:37:04 Step     32 at    8.668 [mm] t=  3.300e-11 [s] E=   72.000 [MeV] 
-ParallelTTracker {0}[3]> 12:37:04 Step     33 at    8.779 [mm] t=  3.400e-11 [s] E=   72.000 [MeV] 
-ParallelTTracker {0}[3]> 12:37:04 Step     34 at    8.891 [mm] t=  3.500e-11 [s] E=   72.000 [MeV] 
-ParallelTTracker {0}[3]> 12:37:04 Step     35 at    9.002 [mm] t=  3.600e-11 [s] E=   72.000 [MeV] 
-ParallelTTracker {0}[3]> 12:37:04 Step     36 at    9.113 [mm] t=  3.700e-11 [s] E=   72.000 [MeV] 
-ParallelTTracker {0}[3]> 12:37:04 Step     37 at    9.224 [mm] t=  3.800e-11 [s] E=   72.000 [MeV] 
-ParallelTTracker {0}[3]> 12:37:04 Step     38 at    9.335 [mm] t=  3.900e-11 [s] E=   72.000 [MeV] 
-ParallelTTracker {0}[3]> 12:37:05 Step     39 at    9.446 [mm] t=  4.000e-11 [s] E=   72.000 [MeV] 
-ParallelTTracker {0}[3]> 12:37:05 Step     40 at    9.558 [mm] t=  4.100e-11 [s] E=   72.000 [MeV] 
+ParallelTTracker {0}[3]> 12:37:03 Step     31 at    8.557 [mm] t=  3.200e-11 [s] E=   72.000 [MeV]
+ParallelTTracker {0}[3]> 12:37:04 Step     32 at    8.668 [mm] t=  3.300e-11 [s] E=   72.000 [MeV]
+ParallelTTracker {0}[3]> 12:37:04 Step     33 at    8.779 [mm] t=  3.400e-11 [s] E=   72.000 [MeV]
+ParallelTTracker {0}[3]> 12:37:04 Step     34 at    8.891 [mm] t=  3.500e-11 [s] E=   72.000 [MeV]
+ParallelTTracker {0}[3]> 12:37:04 Step     35 at    9.002 [mm] t=  3.600e-11 [s] E=   72.000 [MeV]
+ParallelTTracker {0}[3]> 12:37:04 Step     36 at    9.113 [mm] t=  3.700e-11 [s] E=   72.000 [MeV]
+ParallelTTracker {0}[3]> 12:37:04 Step     37 at    9.224 [mm] t=  3.800e-11 [s] E=   72.000 [MeV]
+ParallelTTracker {0}[3]> 12:37:04 Step     38 at    9.335 [mm] t=  3.900e-11 [s] E=   72.000 [MeV]
+ParallelTTracker {0}[3]> 12:37:05 Step     39 at    9.446 [mm] t=  4.000e-11 [s] E=   72.000 [MeV]
+ParallelTTracker {0}[3]> 12:37:05 Step     40 at    9.558 [mm] t=  4.100e-11 [s] E=   72.000 [MeV]
 OPAL {0}[3]> * Wrote beam phase space.
-OPAL {0}> 
-OPAL {0}> * ************** B U N C H ********************************************************* 
+OPAL {0}>
+OPAL {0}> * ************** B U N C H *********************************************************
 OPAL {0}> * NP              =   1000000
 OPAL {0}> * Qtot            =    3.95001e-02 [nC]       Qi    =  3.95001e-08 [nC]
 OPAL {0}> * Ekin            =    7.20000e+01 [MeV]      dEkin =  0.00000e+00 [MeV]
@@ -339,22 +339,22 @@ OPAL {0}> * hr              = (  4.75306e-04 ,  4.75675e-04 ,  4.76188e-05 ) [m]
 OPAL {0}> * dh              =    1.00000e-10 [%]
 OPAL {0}> * t               =    4.10000e-11 [s]        dT    =  1.00000e-12 [s]
 OPAL {0}> * spos            =    9.55753e-03 [m]
-OPAL {0}> * ********************************************************************************** 
-OPAL {0}> 
+OPAL {0}> * **********************************************************************************
+OPAL {0}>
 OPAL {0}[3]> * Wrote beam statistics.
-ParallelTTracker {0}[3]> 12:37:06 Step     41 at    9.669 [mm] t=  4.200e-11 [s] E=   72.000 [MeV] 
-ParallelTTracker {0}[3]> 12:37:06 Step     42 at    9.780 [mm] t=  4.300e-11 [s] E=   72.000 [MeV] 
-ParallelTTracker {0}[3]> 12:37:06 Step     43 at    9.891 [mm] t=  4.400e-11 [s] E=   72.000 [MeV] 
-ParallelTTracker {0}[3]> 12:37:06 Step     44 at   10.002 [mm] t=  4.500e-11 [s] E=   72.000 [MeV] 
-ParallelTTracker {0}[3]> 12:37:07 Step     45 at   10.113 [mm] t=  4.600e-11 [s] E=   72.000 [MeV] 
-ParallelTTracker {0}[3]> 12:37:07 Step     46 at   10.224 [mm] t=  4.700e-11 [s] E=   72.000 [MeV] 
-ParallelTTracker {0}[3]> 12:37:07 Step     47 at   10.336 [mm] t=  4.800e-11 [s] E=   72.000 [MeV] 
-ParallelTTracker {0}[3]> 12:37:07 Step     48 at   10.447 [mm] t=  4.900e-11 [s] E=   72.000 [MeV] 
-ParallelTTracker {0}[3]> 12:37:07 Step     49 at   10.558 [mm] t=  5.000e-11 [s] E=   72.000 [MeV] 
-ParallelTTracker {0}[3]> 12:37:07 Step     50 at   10.669 [mm] t=  5.100e-11 [s] E=   72.000 [MeV] 
+ParallelTTracker {0}[3]> 12:37:06 Step     41 at    9.669 [mm] t=  4.200e-11 [s] E=   72.000 [MeV]
+ParallelTTracker {0}[3]> 12:37:06 Step     42 at    9.780 [mm] t=  4.300e-11 [s] E=   72.000 [MeV]
+ParallelTTracker {0}[3]> 12:37:06 Step     43 at    9.891 [mm] t=  4.400e-11 [s] E=   72.000 [MeV]
+ParallelTTracker {0}[3]> 12:37:06 Step     44 at   10.002 [mm] t=  4.500e-11 [s] E=   72.000 [MeV]
+ParallelTTracker {0}[3]> 12:37:07 Step     45 at   10.113 [mm] t=  4.600e-11 [s] E=   72.000 [MeV]
+ParallelTTracker {0}[3]> 12:37:07 Step     46 at   10.224 [mm] t=  4.700e-11 [s] E=   72.000 [MeV]
+ParallelTTracker {0}[3]> 12:37:07 Step     47 at   10.336 [mm] t=  4.800e-11 [s] E=   72.000 [MeV]
+ParallelTTracker {0}[3]> 12:37:07 Step     48 at   10.447 [mm] t=  4.900e-11 [s] E=   72.000 [MeV]
+ParallelTTracker {0}[3]> 12:37:07 Step     49 at   10.558 [mm] t=  5.000e-11 [s] E=   72.000 [MeV]
+ParallelTTracker {0}[3]> 12:37:07 Step     50 at   10.669 [mm] t=  5.100e-11 [s] E=   72.000 [MeV]
 OPAL {0}[3]> * Wrote beam phase space.
-OPAL {0}> 
-OPAL {0}> * ************** B U N C H ********************************************************* 
+OPAL {0}>
+OPAL {0}> * ************** B U N C H *********************************************************
 OPAL {0}> * NP              =   1000000
 OPAL {0}> * Qtot            =    3.95001e-02 [nC]       Qi    =  3.95001e-08 [nC]
 OPAL {0}> * Ekin            =    7.20000e+01 [MeV]      dEkin =  0.00000e+00 [MeV]
@@ -370,22 +370,22 @@ OPAL {0}> * hr              = (  4.75306e-04 ,  4.75675e-04 ,  4.76188e-05 ) [m]
 OPAL {0}> * dh              =    1.00000e-10 [%]
 OPAL {0}> * t               =    5.10000e-11 [s]        dT    =  1.00000e-12 [s]
 OPAL {0}> * spos            =    1.06690e-02 [m]
-OPAL {0}> * ********************************************************************************** 
-OPAL {0}> 
+OPAL {0}> * **********************************************************************************
+OPAL {0}>
 OPAL {0}[3]> * Wrote beam statistics.
-ParallelTTracker {0}[3]> 12:37:09 Step     51 at   10.780 [mm] t=  5.200e-11 [s] E=   72.000 [MeV] 
-ParallelTTracker {0}[3]> 12:37:09 Step     52 at   10.891 [mm] t=  5.300e-11 [s] E=   72.000 [MeV] 
-ParallelTTracker {0}[3]> 12:37:09 Step     53 at   11.002 [mm] t=  5.400e-11 [s] E=   72.000 [MeV] 
-ParallelTTracker {0}[3]> 12:37:09 Step     54 at   11.114 [mm] t=  5.500e-11 [s] E=   72.000 [MeV] 
-ParallelTTracker {0}[3]> 12:37:10 Step     55 at   11.225 [mm] t=  5.600e-11 [s] E=   72.000 [MeV] 
-ParallelTTracker {0}[3]> 12:37:10 Step     56 at   11.336 [mm] t=  5.700e-11 [s] E=   72.000 [MeV] 
-ParallelTTracker {0}[3]> 12:37:10 Step     57 at   11.447 [mm] t=  5.800e-11 [s] E=   72.000 [MeV] 
-ParallelTTracker {0}[3]> 12:37:10 Step     58 at   11.558 [mm] t=  5.900e-11 [s] E=   72.000 [MeV] 
-ParallelTTracker {0}[3]> 12:37:10 Step     59 at   11.669 [mm] t=  6.000e-11 [s] E=   72.000 [MeV] 
-ParallelTTracker {0}[3]> 12:37:10 Step     60 at   11.781 [mm] t=  6.100e-11 [s] E=   72.000 [MeV] 
+ParallelTTracker {0}[3]> 12:37:09 Step     51 at   10.780 [mm] t=  5.200e-11 [s] E=   72.000 [MeV]
+ParallelTTracker {0}[3]> 12:37:09 Step     52 at   10.891 [mm] t=  5.300e-11 [s] E=   72.000 [MeV]
+ParallelTTracker {0}[3]> 12:37:09 Step     53 at   11.002 [mm] t=  5.400e-11 [s] E=   72.000 [MeV]
+ParallelTTracker {0}[3]> 12:37:09 Step     54 at   11.114 [mm] t=  5.500e-11 [s] E=   72.000 [MeV]
+ParallelTTracker {0}[3]> 12:37:10 Step     55 at   11.225 [mm] t=  5.600e-11 [s] E=   72.000 [MeV]
+ParallelTTracker {0}[3]> 12:37:10 Step     56 at   11.336 [mm] t=  5.700e-11 [s] E=   72.000 [MeV]
+ParallelTTracker {0}[3]> 12:37:10 Step     57 at   11.447 [mm] t=  5.800e-11 [s] E=   72.000 [MeV]
+ParallelTTracker {0}[3]> 12:37:10 Step     58 at   11.558 [mm] t=  5.900e-11 [s] E=   72.000 [MeV]
+ParallelTTracker {0}[3]> 12:37:10 Step     59 at   11.669 [mm] t=  6.000e-11 [s] E=   72.000 [MeV]
+ParallelTTracker {0}[3]> 12:37:10 Step     60 at   11.781 [mm] t=  6.100e-11 [s] E=   72.000 [MeV]
 OPAL {0}[3]> * Wrote beam phase space.
-OPAL {0}> 
-OPAL {0}> * ************** B U N C H ********************************************************* 
+OPAL {0}>
+OPAL {0}> * ************** B U N C H *********************************************************
 OPAL {0}> * NP              =   1000000
 OPAL {0}> * Qtot            =    3.95001e-02 [nC]       Qi    =  3.95001e-08 [nC]
 OPAL {0}> * Ekin            =    7.20000e+01 [MeV]      dEkin =  0.00000e+00 [MeV]
@@ -401,22 +401,22 @@ OPAL {0}> * hr              = (  4.75306e-04 ,  4.75675e-04 ,  4.76188e-05 ) [m]
 OPAL {0}> * dh              =    1.00000e-10 [%]
 OPAL {0}> * t               =    6.10000e-11 [s]        dT    =  1.00000e-12 [s]
 OPAL {0}> * spos            =    1.17805e-02 [m]
-OPAL {0}> * ********************************************************************************** 
-OPAL {0}> 
+OPAL {0}> * **********************************************************************************
+OPAL {0}>
 OPAL {0}[3]> * Wrote beam statistics.
-ParallelTTracker {0}[3]> 12:37:12 Step     61 at   11.892 [mm] t=  6.200e-11 [s] E=   72.000 [MeV] 
-ParallelTTracker {0}[3]> 12:37:12 Step     62 at   12.003 [mm] t=  6.300e-11 [s] E=   72.000 [MeV] 
-ParallelTTracker {0}[3]> 12:37:12 Step     63 at   12.114 [mm] t=  6.400e-11 [s] E=   72.000 [MeV] 
-ParallelTTracker {0}[3]> 12:37:12 Step     64 at   12.225 [mm] t=  6.500e-11 [s] E=   72.000 [MeV] 
-ParallelTTracker {0}[3]> 12:37:12 Step     65 at   12.336 [mm] t=  6.600e-11 [s] E=   72.000 [MeV] 
-ParallelTTracker {0}[3]> 12:37:12 Step     66 at   12.447 [mm] t=  6.700e-11 [s] E=   72.000 [MeV] 
-ParallelTTracker {0}[3]> 12:37:13 Step     67 at   12.559 [mm] t=  6.800e-11 [s] E=   72.000 [MeV] 
-ParallelTTracker {0}[3]> 12:37:13 Step     68 at   12.670 [mm] t=  6.900e-11 [s] E=   72.000 [MeV] 
-ParallelTTracker {0}[3]> 12:37:13 Step     69 at   12.781 [mm] t=  7.000e-11 [s] E=   72.000 [MeV] 
-ParallelTTracker {0}[3]> 12:37:13 Step     70 at   12.892 [mm] t=  7.100e-11 [s] E=   72.000 [MeV] 
+ParallelTTracker {0}[3]> 12:37:12 Step     61 at   11.892 [mm] t=  6.200e-11 [s] E=   72.000 [MeV]
+ParallelTTracker {0}[3]> 12:37:12 Step     62 at   12.003 [mm] t=  6.300e-11 [s] E=   72.000 [MeV]
+ParallelTTracker {0}[3]> 12:37:12 Step     63 at   12.114 [mm] t=  6.400e-11 [s] E=   72.000 [MeV]
+ParallelTTracker {0}[3]> 12:37:12 Step     64 at   12.225 [mm] t=  6.500e-11 [s] E=   72.000 [MeV]
+ParallelTTracker {0}[3]> 12:37:12 Step     65 at   12.336 [mm] t=  6.600e-11 [s] E=   72.000 [MeV]
+ParallelTTracker {0}[3]> 12:37:12 Step     66 at   12.447 [mm] t=  6.700e-11 [s] E=   72.000 [MeV]
+ParallelTTracker {0}[3]> 12:37:13 Step     67 at   12.559 [mm] t=  6.800e-11 [s] E=   72.000 [MeV]
+ParallelTTracker {0}[3]> 12:37:13 Step     68 at   12.670 [mm] t=  6.900e-11 [s] E=   72.000 [MeV]
+ParallelTTracker {0}[3]> 12:37:13 Step     69 at   12.781 [mm] t=  7.000e-11 [s] E=   72.000 [MeV]
+ParallelTTracker {0}[3]> 12:37:13 Step     70 at   12.892 [mm] t=  7.100e-11 [s] E=   72.000 [MeV]
 OPAL {0}[3]> * Wrote beam phase space.
-OPAL {0}> 
-OPAL {0}> * ************** B U N C H ********************************************************* 
+OPAL {0}>
+OPAL {0}> * ************** B U N C H *********************************************************
 OPAL {0}> * NP              =   1000000
 OPAL {0}> * Qtot            =    3.95001e-02 [nC]       Qi    =  3.95001e-08 [nC]
 OPAL {0}> * Ekin            =    7.20000e+01 [MeV]      dEkin =  0.00000e+00 [MeV]
@@ -432,22 +432,22 @@ OPAL {0}> * hr              = (  4.75306e-04 ,  4.75675e-04 ,  4.76188e-05 ) [m]
 OPAL {0}> * dh              =    1.00000e-10 [%]
 OPAL {0}> * t               =    7.10000e-11 [s]        dT    =  1.00000e-12 [s]
 OPAL {0}> * spos            =    1.28920e-02 [m]
-OPAL {0}> * ********************************************************************************** 
-OPAL {0}> 
+OPAL {0}> * **********************************************************************************
+OPAL {0}>
 OPAL {0}[3]> * Wrote beam statistics.
-ParallelTTracker {0}[3]> 12:37:14 Step     71 at   13.003 [mm] t=  7.200e-11 [s] E=   72.000 [MeV] 
-ParallelTTracker {0}[3]> 12:37:15 Step     72 at   13.114 [mm] t=  7.300e-11 [s] E=   72.000 [MeV] 
-ParallelTTracker {0}[3]> 12:37:15 Step     73 at   13.225 [mm] t=  7.400e-11 [s] E=   72.000 [MeV] 
-ParallelTTracker {0}[3]> 12:37:15 Step     74 at   13.337 [mm] t=  7.500e-11 [s] E=   72.000 [MeV] 
-ParallelTTracker {0}[3]> 12:37:15 Step     75 at   13.448 [mm] t=  7.600e-11 [s] E=   72.000 [MeV] 
-ParallelTTracker {0}[3]> 12:37:15 Step     76 at   13.559 [mm] t=  7.700e-11 [s] E=   72.000 [MeV] 
-ParallelTTracker {0}[3]> 12:37:15 Step     77 at   13.670 [mm] t=  7.800e-11 [s] E=   72.000 [MeV] 
-ParallelTTracker {0}[3]> 12:37:16 Step     78 at   13.781 [mm] t=  7.900e-11 [s] E=   72.000 [MeV] 
-ParallelTTracker {0}[3]> 12:37:16 Step     79 at   13.892 [mm] t=  8.000e-11 [s] E=   72.000 [MeV] 
-ParallelTTracker {0}[3]> 12:37:16 Step     80 at   14.003 [mm] t=  8.100e-11 [s] E=   72.000 [MeV] 
+ParallelTTracker {0}[3]> 12:37:14 Step     71 at   13.003 [mm] t=  7.200e-11 [s] E=   72.000 [MeV]
+ParallelTTracker {0}[3]> 12:37:15 Step     72 at   13.114 [mm] t=  7.300e-11 [s] E=   72.000 [MeV]
+ParallelTTracker {0}[3]> 12:37:15 Step     73 at   13.225 [mm] t=  7.400e-11 [s] E=   72.000 [MeV]
+ParallelTTracker {0}[3]> 12:37:15 Step     74 at   13.337 [mm] t=  7.500e-11 [s] E=   72.000 [MeV]
+ParallelTTracker {0}[3]> 12:37:15 Step     75 at   13.448 [mm] t=  7.600e-11 [s] E=   72.000 [MeV]
+ParallelTTracker {0}[3]> 12:37:15 Step     76 at   13.559 [mm] t=  7.700e-11 [s] E=   72.000 [MeV]
+ParallelTTracker {0}[3]> 12:37:15 Step     77 at   13.670 [mm] t=  7.800e-11 [s] E=   72.000 [MeV]
+ParallelTTracker {0}[3]> 12:37:16 Step     78 at   13.781 [mm] t=  7.900e-11 [s] E=   72.000 [MeV]
+ParallelTTracker {0}[3]> 12:37:16 Step     79 at   13.892 [mm] t=  8.000e-11 [s] E=   72.000 [MeV]
+ParallelTTracker {0}[3]> 12:37:16 Step     80 at   14.003 [mm] t=  8.100e-11 [s] E=   72.000 [MeV]
 OPAL {0}[3]> * Wrote beam phase space.
-OPAL {0}> 
-OPAL {0}> * ************** B U N C H ********************************************************* 
+OPAL {0}>
+OPAL {0}> * ************** B U N C H *********************************************************
 OPAL {0}> * NP              =   1000000
 OPAL {0}> * Qtot            =    3.95001e-02 [nC]       Qi    =  3.95001e-08 [nC]
 OPAL {0}> * Ekin            =    7.20000e+01 [MeV]      dEkin =  0.00000e+00 [MeV]
@@ -463,22 +463,22 @@ OPAL {0}> * hr              = (  4.75306e-04 ,  4.75675e-04 ,  4.76188e-05 ) [m]
 OPAL {0}> * dh              =    1.00000e-10 [%]
 OPAL {0}> * t               =    8.10000e-11 [s]        dT    =  1.00000e-12 [s]
 OPAL {0}> * spos            =    1.40035e-02 [m]
-OPAL {0}> * ********************************************************************************** 
-OPAL {0}> 
+OPAL {0}> * **********************************************************************************
+OPAL {0}>
 OPAL {0}[3]> * Wrote beam statistics.
-ParallelTTracker {0}[3]> 12:37:17 Step     81 at   14.115 [mm] t=  8.200e-11 [s] E=   72.000 [MeV] 
-ParallelTTracker {0}[3]> 12:37:17 Step     82 at   14.226 [mm] t=  8.300e-11 [s] E=   72.000 [MeV] 
-ParallelTTracker {0}[3]> 12:37:17 Step     83 at   14.337 [mm] t=  8.400e-11 [s] E=   72.000 [MeV] 
-ParallelTTracker {0}[3]> 12:37:18 Step     84 at   14.448 [mm] t=  8.500e-11 [s] E=   72.000 [MeV] 
-ParallelTTracker {0}[3]> 12:37:18 Step     85 at   14.559 [mm] t=  8.600e-11 [s] E=   72.000 [MeV] 
-ParallelTTracker {0}[3]> 12:37:18 Step     86 at   14.670 [mm] t=  8.700e-11 [s] E=   72.000 [MeV] 
-ParallelTTracker {0}[3]> 12:37:18 Step     87 at   14.782 [mm] t=  8.800e-11 [s] E=   72.000 [MeV] 
-ParallelTTracker {0}[3]> 12:37:18 Step     88 at   14.893 [mm] t=  8.900e-11 [s] E=   72.000 [MeV] 
-ParallelTTracker {0}[3]> 12:37:18 Step     89 at   15.004 [mm] t=  9.000e-11 [s] E=   72.000 [MeV] 
-ParallelTTracker {0}[3]> 12:37:19 Step     90 at   15.115 [mm] t=  9.100e-11 [s] E=   72.000 [MeV] 
+ParallelTTracker {0}[3]> 12:37:17 Step     81 at   14.115 [mm] t=  8.200e-11 [s] E=   72.000 [MeV]
+ParallelTTracker {0}[3]> 12:37:17 Step     82 at   14.226 [mm] t=  8.300e-11 [s] E=   72.000 [MeV]
+ParallelTTracker {0}[3]> 12:37:17 Step     83 at   14.337 [mm] t=  8.400e-11 [s] E=   72.000 [MeV]
+ParallelTTracker {0}[3]> 12:37:18 Step     84 at   14.448 [mm] t=  8.500e-11 [s] E=   72.000 [MeV]
+ParallelTTracker {0}[3]> 12:37:18 Step     85 at   14.559 [mm] t=  8.600e-11 [s] E=   72.000 [MeV]
+ParallelTTracker {0}[3]> 12:37:18 Step     86 at   14.670 [mm] t=  8.700e-11 [s] E=   72.000 [MeV]
+ParallelTTracker {0}[3]> 12:37:18 Step     87 at   14.782 [mm] t=  8.800e-11 [s] E=   72.000 [MeV]
+ParallelTTracker {0}[3]> 12:37:18 Step     88 at   14.893 [mm] t=  8.900e-11 [s] E=   72.000 [MeV]
+ParallelTTracker {0}[3]> 12:37:18 Step     89 at   15.004 [mm] t=  9.000e-11 [s] E=   72.000 [MeV]
+ParallelTTracker {0}[3]> 12:37:19 Step     90 at   15.115 [mm] t=  9.100e-11 [s] E=   72.000 [MeV]
 OPAL {0}[3]> * Wrote beam phase space.
-OPAL {0}> 
-OPAL {0}> * ************** B U N C H ********************************************************* 
+OPAL {0}>
+OPAL {0}> * ************** B U N C H *********************************************************
 OPAL {0}> * NP              =   1000000
 OPAL {0}> * Qtot            =    3.95001e-02 [nC]       Qi    =  3.95001e-08 [nC]
 OPAL {0}> * Ekin            =    7.20000e+01 [MeV]      dEkin =  0.00000e+00 [MeV]
@@ -494,22 +494,22 @@ OPAL {0}> * hr              = (  4.75306e-04 ,  4.75675e-04 ,  4.76188e-05 ) [m]
 OPAL {0}> * dh              =    1.00000e-10 [%]
 OPAL {0}> * t               =    9.10000e-11 [s]        dT    =  1.00000e-12 [s]
 OPAL {0}> * spos            =    1.51150e-02 [m]
-OPAL {0}> * ********************************************************************************** 
-OPAL {0}> 
+OPAL {0}> * **********************************************************************************
+OPAL {0}>
 OPAL {0}[3]> * Wrote beam statistics.
-ParallelTTracker {0}[3]> 12:37:20 Step     91 at   15.226 [mm] t=  9.200e-11 [s] E=   72.000 [MeV] 
-ParallelTTracker {0}[3]> 12:37:20 Step     92 at   15.337 [mm] t=  9.300e-11 [s] E=   72.000 [MeV] 
-ParallelTTracker {0}[3]> 12:37:20 Step     93 at   15.448 [mm] t=  9.400e-11 [s] E=   72.000 [MeV] 
-ParallelTTracker {0}[3]> 12:37:20 Step     94 at   15.560 [mm] t=  9.500e-11 [s] E=   72.000 [MeV] 
-ParallelTTracker {0}[3]> 12:37:21 Step     95 at   15.671 [mm] t=  9.600e-11 [s] E=   72.000 [MeV] 
-ParallelTTracker {0}[3]> 12:37:21 Step     96 at   15.782 [mm] t=  9.700e-11 [s] E=   72.000 [MeV] 
-ParallelTTracker {0}[3]> 12:37:21 Step     97 at   15.893 [mm] t=  9.800e-11 [s] E=   72.000 [MeV] 
-ParallelTTracker {0}[3]> 12:37:21 Step     98 at   16.004 [mm] t=  9.900e-11 [s] E=   72.000 [MeV] 
-ParallelTTracker {0}[2]> 12:37:21 Step     99 at   16.115 [mm] t=  1.000e-10 [s] E=   72.000 [MeV] 
-ParallelTTracker {0}[3]> 12:37:21 Step    100 at   16.226 [mm] t=  1.010e-10 [s] E=   72.000 [MeV] 
+ParallelTTracker {0}[3]> 12:37:20 Step     91 at   15.226 [mm] t=  9.200e-11 [s] E=   72.000 [MeV]
+ParallelTTracker {0}[3]> 12:37:20 Step     92 at   15.337 [mm] t=  9.300e-11 [s] E=   72.000 [MeV]
+ParallelTTracker {0}[3]> 12:37:20 Step     93 at   15.448 [mm] t=  9.400e-11 [s] E=   72.000 [MeV]
+ParallelTTracker {0}[3]> 12:37:20 Step     94 at   15.560 [mm] t=  9.500e-11 [s] E=   72.000 [MeV]
+ParallelTTracker {0}[3]> 12:37:21 Step     95 at   15.671 [mm] t=  9.600e-11 [s] E=   72.000 [MeV]
+ParallelTTracker {0}[3]> 12:37:21 Step     96 at   15.782 [mm] t=  9.700e-11 [s] E=   72.000 [MeV]
+ParallelTTracker {0}[3]> 12:37:21 Step     97 at   15.893 [mm] t=  9.800e-11 [s] E=   72.000 [MeV]
+ParallelTTracker {0}[3]> 12:37:21 Step     98 at   16.004 [mm] t=  9.900e-11 [s] E=   72.000 [MeV]
+ParallelTTracker {0}[2]> 12:37:21 Step     99 at   16.115 [mm] t=  1.000e-10 [s] E=   72.000 [MeV]
+ParallelTTracker {0}[3]> 12:37:21 Step    100 at   16.226 [mm] t=  1.010e-10 [s] E=   72.000 [MeV]
 OPAL {0}[3]> * Wrote beam phase space.
-OPAL {0}> 
-OPAL {0}> * ************** B U N C H ********************************************************* 
+OPAL {0}>
+OPAL {0}> * ************** B U N C H *********************************************************
 OPAL {0}> * NP              =   1000000
 OPAL {0}> * Qtot            =    3.95001e-02 [nC]       Qi    =  3.95001e-08 [nC]
 OPAL {0}> * Ekin            =    7.20000e+01 [MeV]      dEkin =  0.00000e+00 [MeV]
@@ -525,22 +525,22 @@ OPAL {0}> * hr              = (  4.75306e-04 ,  4.75675e-04 ,  4.76188e-05 ) [m]
 OPAL {0}> * dh              =    1.00000e-10 [%]
 OPAL {0}> * t               =    1.01000e-10 [s]        dT    =  1.00000e-12 [s]
 OPAL {0}> * spos            =    1.62264e-02 [m]
-OPAL {0}> * ********************************************************************************** 
-OPAL {0}> 
+OPAL {0}> * **********************************************************************************
+OPAL {0}>
 OPAL {0}[3]> * Wrote beam statistics.
-ParallelTTracker {0}[3]> 12:37:23 Step    101 at   16.338 [mm] t=  1.020e-10 [s] E=   72.000 [MeV] 
-ParallelTTracker {0}[3]> 12:37:23 Step    102 at   16.449 [mm] t=  1.030e-10 [s] E=   72.000 [MeV] 
-ParallelTTracker {0}[3]> 12:37:23 Step    103 at   16.560 [mm] t=  1.040e-10 [s] E=   72.000 [MeV] 
-ParallelTTracker {0}[3]> 12:37:23 Step    104 at   16.671 [mm] t=  1.050e-10 [s] E=   72.000 [MeV] 
-ParallelTTracker {0}[3]> 12:37:23 Step    105 at   16.782 [mm] t=  1.060e-10 [s] E=   72.000 [MeV] 
-ParallelTTracker {0}[3]> 12:37:23 Step    106 at   16.893 [mm] t=  1.070e-10 [s] E=   72.000 [MeV] 
-ParallelTTracker {0}[3]> 12:37:24 Step    107 at   17.004 [mm] t=  1.080e-10 [s] E=   72.000 [MeV] 
-ParallelTTracker {0}[3]> 12:37:24 Step    108 at   17.116 [mm] t=  1.090e-10 [s] E=   72.000 [MeV] 
-ParallelTTracker {0}[3]> 12:37:24 Step    109 at   17.227 [mm] t=  1.100e-10 [s] E=   72.000 [MeV] 
-ParallelTTracker {0}[3]> 12:37:24 Step    110 at   17.338 [mm] t=  1.110e-10 [s] E=   72.000 [MeV] 
+ParallelTTracker {0}[3]> 12:37:23 Step    101 at   16.338 [mm] t=  1.020e-10 [s] E=   72.000 [MeV]
+ParallelTTracker {0}[3]> 12:37:23 Step    102 at   16.449 [mm] t=  1.030e-10 [s] E=   72.000 [MeV]
+ParallelTTracker {0}[3]> 12:37:23 Step    103 at   16.560 [mm] t=  1.040e-10 [s] E=   72.000 [MeV]
+ParallelTTracker {0}[3]> 12:37:23 Step    104 at   16.671 [mm] t=  1.050e-10 [s] E=   72.000 [MeV]
+ParallelTTracker {0}[3]> 12:37:23 Step    105 at   16.782 [mm] t=  1.060e-10 [s] E=   72.000 [MeV]
+ParallelTTracker {0}[3]> 12:37:23 Step    106 at   16.893 [mm] t=  1.070e-10 [s] E=   72.000 [MeV]
+ParallelTTracker {0}[3]> 12:37:24 Step    107 at   17.004 [mm] t=  1.080e-10 [s] E=   72.000 [MeV]
+ParallelTTracker {0}[3]> 12:37:24 Step    108 at   17.116 [mm] t=  1.090e-10 [s] E=   72.000 [MeV]
+ParallelTTracker {0}[3]> 12:37:24 Step    109 at   17.227 [mm] t=  1.100e-10 [s] E=   72.000 [MeV]
+ParallelTTracker {0}[3]> 12:37:24 Step    110 at   17.338 [mm] t=  1.110e-10 [s] E=   72.000 [MeV]
 OPAL {0}[3]> * Wrote beam phase space.
-OPAL {0}> 
-OPAL {0}> * ************** B U N C H ********************************************************* 
+OPAL {0}>
+OPAL {0}> * ************** B U N C H *********************************************************
 OPAL {0}> * NP              =   1000000
 OPAL {0}> * Qtot            =    3.95001e-02 [nC]       Qi    =  3.95001e-08 [nC]
 OPAL {0}> * Ekin            =    7.20000e+01 [MeV]      dEkin =  0.00000e+00 [MeV]
@@ -556,22 +556,22 @@ OPAL {0}> * hr              = (  4.75306e-04 ,  4.75675e-04 ,  4.76188e-05 ) [m]
 OPAL {0}> * dh              =    1.00000e-10 [%]
 OPAL {0}> * t               =    1.11000e-10 [s]        dT    =  1.00000e-12 [s]
 OPAL {0}> * spos            =    1.73379e-02 [m]
-OPAL {0}> * ********************************************************************************** 
-OPAL {0}> 
+OPAL {0}> * **********************************************************************************
+OPAL {0}>
 OPAL {0}[3]> * Wrote beam statistics.
-ParallelTTracker {0}[3]> 12:37:25 Step    111 at   17.449 [mm] t=  1.120e-10 [s] E=   72.000 [MeV] 
-ParallelTTracker {0}[3]> 12:37:25 Step    112 at   17.560 [mm] t=  1.130e-10 [s] E=   72.000 [MeV] 
-ParallelTTracker {0}[3]> 12:37:26 Step    113 at   17.671 [mm] t=  1.140e-10 [s] E=   72.000 [MeV] 
-ParallelTTracker {0}[3]> 12:37:26 Step    114 at   17.783 [mm] t=  1.150e-10 [s] E=   72.000 [MeV] 
-ParallelTTracker {0}[3]> 12:37:26 Step    115 at   17.894 [mm] t=  1.160e-10 [s] E=   72.000 [MeV] 
-ParallelTTracker {0}[3]> 12:37:26 Step    116 at   18.005 [mm] t=  1.170e-10 [s] E=   72.000 [MeV] 
-ParallelTTracker {0}[3]> 12:37:26 Step    117 at   18.116 [mm] t=  1.180e-10 [s] E=   72.000 [MeV] 
-ParallelTTracker {0}[3]> 12:37:26 Step    118 at   18.227 [mm] t=  1.190e-10 [s] E=   72.000 [MeV] 
-ParallelTTracker {0}[3]> 12:37:27 Step    119 at   18.338 [mm] t=  1.200e-10 [s] E=   72.000 [MeV] 
-ParallelTTracker {0}[3]> 12:37:27 Step    120 at   18.449 [mm] t=  1.210e-10 [s] E=   72.000 [MeV] 
+ParallelTTracker {0}[3]> 12:37:25 Step    111 at   17.449 [mm] t=  1.120e-10 [s] E=   72.000 [MeV]
+ParallelTTracker {0}[3]> 12:37:25 Step    112 at   17.560 [mm] t=  1.130e-10 [s] E=   72.000 [MeV]
+ParallelTTracker {0}[3]> 12:37:26 Step    113 at   17.671 [mm] t=  1.140e-10 [s] E=   72.000 [MeV]
+ParallelTTracker {0}[3]> 12:37:26 Step    114 at   17.783 [mm] t=  1.150e-10 [s] E=   72.000 [MeV]
+ParallelTTracker {0}[3]> 12:37:26 Step    115 at   17.894 [mm] t=  1.160e-10 [s] E=   72.000 [MeV]
+ParallelTTracker {0}[3]> 12:37:26 Step    116 at   18.005 [mm] t=  1.170e-10 [s] E=   72.000 [MeV]
+ParallelTTracker {0}[3]> 12:37:26 Step    117 at   18.116 [mm] t=  1.180e-10 [s] E=   72.000 [MeV]
+ParallelTTracker {0}[3]> 12:37:26 Step    118 at   18.227 [mm] t=  1.190e-10 [s] E=   72.000 [MeV]
+ParallelTTracker {0}[3]> 12:37:27 Step    119 at   18.338 [mm] t=  1.200e-10 [s] E=   72.000 [MeV]
+ParallelTTracker {0}[3]> 12:37:27 Step    120 at   18.449 [mm] t=  1.210e-10 [s] E=   72.000 [MeV]
 OPAL {0}[3]> * Wrote beam phase space.
-OPAL {0}> 
-OPAL {0}> * ************** B U N C H ********************************************************* 
+OPAL {0}>
+OPAL {0}> * ************** B U N C H *********************************************************
 OPAL {0}> * NP              =   1000000
 OPAL {0}> * Qtot            =    3.95001e-02 [nC]       Qi    =  3.95001e-08 [nC]
 OPAL {0}> * Ekin            =    7.20000e+01 [MeV]      dEkin =  0.00000e+00 [MeV]
@@ -587,54 +587,54 @@ OPAL {0}> * hr              = (  4.75306e-04 ,  4.75675e-04 ,  4.76188e-05 ) [m]
 OPAL {0}> * dh              =    1.00000e-10 [%]
 OPAL {0}> * t               =    1.21000e-10 [s]        dT    =  1.00000e-12 [s]
 OPAL {0}> * spos            =    1.84494e-02 [m]
-OPAL {0}> * ********************************************************************************** 
-OPAL {0}> 
+OPAL {0}> * **********************************************************************************
+OPAL {0}>
 OPAL {0}[3]> * Wrote beam statistics.
 Ippl{0}[3]> M1 gone live
 ParallelTTracker {0}[2]> ============== START SURFACE PHYSICS CALCULATION =============
 ParallelTTracker {0}> --- CollimatorPhysics - Type is DEGRADER Name DEG1 Material Graphite Particles in material 41
 ParallelTTracker {0}> Coll/Deg statistics:  bunch to material 41 redifused 0 stopped 0
 ParallelTTracker {0}> * Deleted 41 particles, remaining 999959 particles
-ParallelTTracker {0}[3]> 12:37:28 Step    121 at   18.561 [mm] t=  1.220e-10 [s] E=   72.000 [MeV] 
+ParallelTTracker {0}[3]> 12:37:28 Step    121 at   18.561 [mm] t=  1.220e-10 [s] E=   72.000 [MeV]
 ParallelTTracker {0}> --- CollimatorPhysics - Type is DEGRADER Name DEG1 Material Graphite Particles in material 1464
 ParallelTTracker {0}> Coll/Deg statistics:  bunch to material 1423 redifused 0 stopped 0
 ParallelTTracker {0}> * Deleted 1423 particles, remaining 998536 particles
-ParallelTTracker {0}[3]> 12:37:28 Step    122 at   18.670 [mm] t=  1.230e-10 [s] E=   72.000 [MeV] 
+ParallelTTracker {0}[3]> 12:37:28 Step    122 at   18.670 [mm] t=  1.230e-10 [s] E=   72.000 [MeV]
 ParallelTTracker {0}> --- CollimatorPhysics - Type is DEGRADER Name DEG1 Material Graphite Particles in material 4127
 ParallelTTracker {0}> Coll/Deg statistics:  bunch to material 2663 redifused 0 stopped 0
 ParallelTTracker {0}> * Deleted 2663 particles, remaining 995873 particles
-ParallelTTracker {0}[3]> 12:37:28 Step    123 at   18.777 [mm] t=  1.240e-10 [s] E=   72.000 [MeV] 
+ParallelTTracker {0}[3]> 12:37:28 Step    123 at   18.777 [mm] t=  1.240e-10 [s] E=   72.000 [MeV]
 ParallelTTracker {0}> --- CollimatorPhysics - Type is DEGRADER Name DEG1 Material Graphite Particles in material 8749
 ParallelTTracker {0}> Coll/Deg statistics:  bunch to material 4622 redifused 0 stopped 0
 ParallelTTracker {0}> * Deleted 4622 particles, remaining 991251 particles
-ParallelTTracker {0}[3]> 12:37:28 Step    124 at   18.883 [mm] t=  1.250e-10 [s] E=   72.000 [MeV] 
+ParallelTTracker {0}[3]> 12:37:28 Step    124 at   18.883 [mm] t=  1.250e-10 [s] E=   72.000 [MeV]
 ParallelTTracker {0}> --- CollimatorPhysics - Type is DEGRADER Name DEG1 Material Graphite Particles in material 16363
 ParallelTTracker {0}> Coll/Deg statistics:  bunch to material 7614 redifused 0 stopped 0
 ParallelTTracker {0}> * Deleted 7614 particles, remaining 983637 particles
-ParallelTTracker {0}[3]> 12:37:29 Step    125 at   18.985 [mm] t=  1.260e-10 [s] E=   72.000 [MeV] 
+ParallelTTracker {0}[3]> 12:37:29 Step    125 at   18.985 [mm] t=  1.260e-10 [s] E=   72.000 [MeV]
 ParallelTTracker {0}> --- CollimatorPhysics - Type is DEGRADER Name DEG1 Material Graphite Particles in material 28834
 ParallelTTracker {0}> Coll/Deg statistics:  bunch to material 12471 redifused 0 stopped 0
 ParallelTTracker {0}> * Deleted 12471 particles, remaining 971166 particles
-ParallelTTracker {0}[3]> 12:37:29 Step    126 at   19.083 [mm] t=  1.270e-10 [s] E=   72.000 [MeV] 
+ParallelTTracker {0}[3]> 12:37:29 Step    126 at   19.083 [mm] t=  1.270e-10 [s] E=   72.000 [MeV]
 ParallelTTracker {0}> --- CollimatorPhysics - Type is DEGRADER Name DEG1 Material Graphite Particles in material 47505
 ParallelTTracker {0}> Coll/Deg statistics:  bunch to material 18671 redifused 0 stopped 0
 ParallelTTracker {0}> * Deleted 18671 particles, remaining 952495 particles
-ParallelTTracker {0}[3]> 12:37:29 Step    127 at   19.177 [mm] t=  1.280e-10 [s] E=   72.000 [MeV] 
+ParallelTTracker {0}[3]> 12:37:29 Step    127 at   19.177 [mm] t=  1.280e-10 [s] E=   72.000 [MeV]
 ParallelTTracker {0}> --- CollimatorPhysics - Type is DEGRADER Name DEG1 Material Graphite Particles in material 74581
 ParallelTTracker {0}> Coll/Deg statistics:  bunch to material 27076 redifused 0 stopped 0
 ParallelTTracker {0}> * Deleted 27076 particles, remaining 925419 particles
-ParallelTTracker {0}[3]> 12:37:29 Step    128 at   19.264 [mm] t=  1.290e-10 [s] E=   72.000 [MeV] 
+ParallelTTracker {0}[3]> 12:37:29 Step    128 at   19.264 [mm] t=  1.290e-10 [s] E=   72.000 [MeV]
 ParallelTTracker {0}> --- CollimatorPhysics - Type is DEGRADER Name DEG1 Material Graphite Particles in material 111496
 ParallelTTracker {0}> Coll/Deg statistics:  bunch to material 36915 redifused 0 stopped 0
 ParallelTTracker {0}> * Deleted 36915 particles, remaining 888504 particles
-ParallelTTracker {0}[3]> 12:37:30 Step    129 at   19.344 [mm] t=  1.300e-10 [s] E=   72.000 [MeV] 
+ParallelTTracker {0}[3]> 12:37:30 Step    129 at   19.344 [mm] t=  1.300e-10 [s] E=   72.000 [MeV]
 ParallelTTracker {0}> --- CollimatorPhysics - Type is DEGRADER Name DEG1 Material Graphite Particles in material 160109
 ParallelTTracker {0}> Coll/Deg statistics:  bunch to material 48613 redifused 0 stopped 0
 ParallelTTracker {0}> * Deleted 48613 particles, remaining 839891 particles
-ParallelTTracker {0}[3]> 12:37:30 Step    130 at   19.418 [mm] t=  1.310e-10 [s] E=   72.000 [MeV] 
+ParallelTTracker {0}[3]> 12:37:30 Step    130 at   19.418 [mm] t=  1.310e-10 [s] E=   72.000 [MeV]
 OPAL {0}[3]> * Wrote beam phase space.
-OPAL {0}> 
-OPAL {0}> * ************** B U N C H ********************************************************* 
+OPAL {0}>
+OPAL {0}> * ************** B U N C H *********************************************************
 OPAL {0}> * NP              =   839891
 OPAL {0}> * Qtot            =    3.31758e-02 [nC]       Qi    =  3.95001e-08 [nC]
 OPAL {0}> * Ekin            =    7.20000e+01 [MeV]      dEkin =  0.00000e+00 [MeV]
@@ -650,52 +650,52 @@ OPAL {0}> * hr              = (  4.75258e-04 ,  4.75675e-04 ,  3.16683e-05 ) [m]
 OPAL {0}> * dh              =    1.00000e-10 [%]
 OPAL {0}> * t               =    1.31000e-10 [s]        dT    =  1.00000e-12 [s]
 OPAL {0}> * spos            =    1.94178e-02 [m]
-OPAL {0}> * ********************************************************************************** 
-OPAL {0}> 
+OPAL {0}> * **********************************************************************************
+OPAL {0}>
 OPAL {0}[3]> * Wrote beam statistics.
 ParallelTTracker {0}> --- CollimatorPhysics - Type is DEGRADER Name DEG1 Material Graphite Particles in material 220706
 ParallelTTracker {0}> Coll/Deg statistics:  bunch to material 60597 redifused 0 stopped 0
 ParallelTTracker {0}> * Deleted 60597 particles, remaining 779294 particles
-ParallelTTracker {0}[3]> 12:37:31 Step    131 at   19.484 [mm] t=  1.320e-10 [s] E=   72.000 [MeV] 
+ParallelTTracker {0}[3]> 12:37:31 Step    131 at   19.484 [mm] t=  1.320e-10 [s] E=   72.000 [MeV]
 ParallelTTracker {0}> --- CollimatorPhysics - Type is DEGRADER Name DEG1 Material Graphite Particles in material 291914
 ParallelTTracker {0}> Coll/Deg statistics:  bunch to material 71208 redifused 0 stopped 0
 ParallelTTracker {0}> * Deleted 71208 particles, remaining 708086 particles
-ParallelTTracker {0}[3]> 12:37:31 Step    132 at   19.543 [mm] t=  1.330e-10 [s] E=   72.000 [MeV] 
+ParallelTTracker {0}[3]> 12:37:31 Step    132 at   19.543 [mm] t=  1.330e-10 [s] E=   72.000 [MeV]
 ParallelTTracker {0}> --- CollimatorPhysics - Type is DEGRADER Name DEG1 Material Graphite Particles in material 372753
 ParallelTTracker {0}> Coll/Deg statistics:  bunch to material 80839 redifused 0 stopped 0
 ParallelTTracker {0}> * Deleted 80839 particles, remaining 627247 particles
-ParallelTTracker {0}[3]> 12:37:32 Step    133 at   19.596 [mm] t=  1.340e-10 [s] E=   72.000 [MeV] 
+ParallelTTracker {0}[3]> 12:37:32 Step    133 at   19.596 [mm] t=  1.340e-10 [s] E=   72.000 [MeV]
 ParallelTTracker {0}> --- CollimatorPhysics - Type is DEGRADER Name DEG1 Material Graphite Particles in material 459754
 ParallelTTracker {0}> Coll/Deg statistics:  bunch to material 87001 redifused 0 stopped 0
 ParallelTTracker {0}> * Deleted 87001 particles, remaining 540246 particles
-ParallelTTracker {0}[3]> 12:37:32 Step    134 at   19.642 [mm] t=  1.350e-10 [s] E=   72.000 [MeV] 
+ParallelTTracker {0}[3]> 12:37:32 Step    134 at   19.642 [mm] t=  1.350e-10 [s] E=   72.000 [MeV]
 ParallelTTracker {0}> --- CollimatorPhysics - Type is DEGRADER Name DEG1 Material Graphite Particles in material 548601
 ParallelTTracker {0}> Coll/Deg statistics:  bunch to material 88847 redifused 0 stopped 0
 ParallelTTracker {0}> * Deleted 88847 particles, remaining 451399 particles
-ParallelTTracker {0}[3]> 12:37:32 Step    135 at   19.682 [mm] t=  1.360e-10 [s] E=   72.000 [MeV] 
+ParallelTTracker {0}[3]> 12:37:32 Step    135 at   19.682 [mm] t=  1.360e-10 [s] E=   72.000 [MeV]
 ParallelTTracker {0}> --- CollimatorPhysics - Type is DEGRADER Name DEG1 Material Graphite Particles in material 635129
 ParallelTTracker {0}> Coll/Deg statistics:  bunch to material 86528 redifused 0 stopped 0
 ParallelTTracker {0}> * Deleted 86528 particles, remaining 364871 particles
-ParallelTTracker {0}[3]> 12:37:33 Step    136 at   19.718 [mm] t=  1.370e-10 [s] E=   72.000 [MeV] 
+ParallelTTracker {0}[3]> 12:37:33 Step    136 at   19.718 [mm] t=  1.370e-10 [s] E=   72.000 [MeV]
 ParallelTTracker {0}> --- CollimatorPhysics - Type is DEGRADER Name DEG1 Material Graphite Particles in material 715230
 ParallelTTracker {0}> Coll/Deg statistics:  bunch to material 80101 redifused 0 stopped 0
 ParallelTTracker {0}> * Deleted 80101 particles, remaining 284770 particles
-ParallelTTracker {0}[3]> 12:37:33 Step    137 at   19.750 [mm] t=  1.380e-10 [s] E=   72.000 [MeV] 
+ParallelTTracker {0}[3]> 12:37:33 Step    137 at   19.750 [mm] t=  1.380e-10 [s] E=   72.000 [MeV]
 ParallelTTracker {0}> --- CollimatorPhysics - Type is DEGRADER Name DEG1 Material Graphite Particles in material 786072
 ParallelTTracker {0}> Coll/Deg statistics:  bunch to material 70842 redifused 0 stopped 0
 ParallelTTracker {0}> * Deleted 70842 particles, remaining 213928 particles
-ParallelTTracker {0}[3]> 12:37:33 Step    138 at   19.777 [mm] t=  1.390e-10 [s] E=   72.000 [MeV] 
+ParallelTTracker {0}[3]> 12:37:33 Step    138 at   19.777 [mm] t=  1.390e-10 [s] E=   72.000 [MeV]
 ParallelTTracker {0}> --- CollimatorPhysics - Type is DEGRADER Name DEG1 Material Graphite Particles in material 845496
 ParallelTTracker {0}> Coll/Deg statistics:  bunch to material 59424 redifused 0 stopped 0
 ParallelTTracker {0}> * Deleted 59424 particles, remaining 154504 particles
-ParallelTTracker {0}[3]> 12:37:34 Step    139 at   19.802 [mm] t=  1.400e-10 [s] E=   72.000 [MeV] 
+ParallelTTracker {0}[3]> 12:37:34 Step    139 at   19.802 [mm] t=  1.400e-10 [s] E=   72.000 [MeV]
 ParallelTTracker {0}> --- CollimatorPhysics - Type is DEGRADER Name DEG1 Material Graphite Particles in material 892894
 ParallelTTracker {0}> Coll/Deg statistics:  bunch to material 47398 redifused 0 stopped 0
 ParallelTTracker {0}> * Deleted 47398 particles, remaining 107106 particles
-ParallelTTracker {0}[3]> 12:37:34 Step    140 at   19.825 [mm] t=  1.410e-10 [s] E=   72.000 [MeV] 
+ParallelTTracker {0}[3]> 12:37:34 Step    140 at   19.825 [mm] t=  1.410e-10 [s] E=   72.000 [MeV]
 OPAL {0}[3]> * Wrote beam phase space.
-OPAL {0}> 
-OPAL {0}> * ************** B U N C H ********************************************************* 
+OPAL {0}>
+OPAL {0}> * ************** B U N C H *********************************************************
 OPAL {0}> * NP              =   107106
 OPAL {0}> * Qtot            =    4.23070e-03 [nC]       Qi    =  3.95001e-08 [nC]
 OPAL {0}> * Ekin            =    7.20000e+01 [MeV]      dEkin =  1.58486e-04 [MeV]
@@ -711,52 +711,52 @@ OPAL {0}> * hr              = (  4.73329e-04 ,  4.74714e-04 ,  1.40257e-05 ) [m]
 OPAL {0}> * dh              =    1.00000e-10 [%]
 OPAL {0}> * t               =    1.41000e-10 [s]        dT    =  1.00000e-12 [s]
 OPAL {0}> * spos            =    1.98246e-02 [m]
-OPAL {0}> * ********************************************************************************** 
-OPAL {0}> 
+OPAL {0}> * **********************************************************************************
+OPAL {0}>
 OPAL {0}[3]> * Wrote beam statistics.
 ParallelTTracker {0}> --- CollimatorPhysics - Type is DEGRADER Name DEG1 Material Graphite Particles in material 928787
 ParallelTTracker {0}> Coll/Deg statistics:  bunch to material 35893 redifused 0 stopped 0
 ParallelTTracker {0}> * Deleted 35893 particles, remaining 71213 particles
-ParallelTTracker {0}[3]> 12:37:34 Step    141 at   19.846 [mm] t=  1.420e-10 [s] E=   72.000 [MeV] 
+ParallelTTracker {0}[3]> 12:37:34 Step    141 at   19.846 [mm] t=  1.420e-10 [s] E=   72.000 [MeV]
 ParallelTTracker {0}> --- CollimatorPhysics - Type is DEGRADER Name DEG1 Material Graphite Particles in material 954712
 ParallelTTracker {0}> Coll/Deg statistics:  bunch to material 25925 redifused 0 stopped 0
 ParallelTTracker {0}> * Deleted 25925 particles, remaining 45288 particles
-ParallelTTracker {0}[3]> 12:37:35 Step    142 at   19.867 [mm] t=  1.430e-10 [s] E=   72.000 [MeV] 
+ParallelTTracker {0}[3]> 12:37:35 Step    142 at   19.867 [mm] t=  1.430e-10 [s] E=   72.000 [MeV]
 ParallelTTracker {0}> --- CollimatorPhysics - Type is DEGRADER Name DEG1 Material Graphite Particles in material 972768
 ParallelTTracker {0}> Coll/Deg statistics:  bunch to material 18056 redifused 0 stopped 0
 ParallelTTracker {0}> * Deleted 18056 particles, remaining 27232 particles
-ParallelTTracker {0}[3]> 12:37:35 Step    143 at   19.888 [mm] t=  1.440e-10 [s] E=   72.000 [MeV] 
+ParallelTTracker {0}[3]> 12:37:35 Step    143 at   19.888 [mm] t=  1.440e-10 [s] E=   72.000 [MeV]
 ParallelTTracker {0}> --- CollimatorPhysics - Type is DEGRADER Name DEG1 Material Graphite Particles in material 984586
 ParallelTTracker {0}> Coll/Deg statistics:  bunch to material 11818 redifused 0 stopped 0
 ParallelTTracker {0}> * Deleted 11818 particles, remaining 15414 particles
-ParallelTTracker {0}[3]> 12:37:36 Step    144 at   19.910 [mm] t=  1.450e-10 [s] E=   72.000 [MeV] 
+ParallelTTracker {0}[3]> 12:37:36 Step    144 at   19.910 [mm] t=  1.450e-10 [s] E=   72.000 [MeV]
 ParallelTTracker {0}> --- CollimatorPhysics - Type is DEGRADER Name DEG1 Material Graphite Particles in material 991895
 ParallelTTracker {0}> Coll/Deg statistics:  bunch to material 7309 redifused 0 stopped 0
 ParallelTTracker {0}> * Deleted 7309 particles, remaining 8105 particles
-ParallelTTracker {0}[3]> 12:37:36 Step    145 at   19.935 [mm] t=  1.460e-10 [s] E=   72.000 [MeV] 
+ParallelTTracker {0}[3]> 12:37:36 Step    145 at   19.935 [mm] t=  1.460e-10 [s] E=   72.000 [MeV]
 ParallelTTracker {0}> --- CollimatorPhysics - Type is DEGRADER Name DEG1 Material Graphite Particles in material 996162
 ParallelTTracker {0}> Coll/Deg statistics:  bunch to material 4267 redifused 0 stopped 0
 ParallelTTracker {0}> * Deleted 4267 particles, remaining 3838 particles
-ParallelTTracker {0}[3]> 12:37:36 Step    146 at   19.969 [mm] t=  1.470e-10 [s] E=   72.000 [MeV] 
+ParallelTTracker {0}[3]> 12:37:36 Step    146 at   19.969 [mm] t=  1.470e-10 [s] E=   72.000 [MeV]
 ParallelTTracker {0}> --- CollimatorPhysics - Type is DEGRADER Name DEG1 Material Graphite Particles in material 998730
 ParallelTTracker {0}> Coll/Deg statistics:  bunch to material 2568 redifused 0 stopped 0
 ParallelTTracker {0}> * Deleted 2568 particles, remaining 1270 particles
-ParallelTTracker {0}[3]> 12:37:37 Step    147 at   20.008 [mm] t=  1.480e-10 [s] E=   72.000 [MeV] 
+ParallelTTracker {0}[3]> 12:37:37 Step    147 at   20.008 [mm] t=  1.480e-10 [s] E=   72.000 [MeV]
 ParallelTTracker {0}> --- CollimatorPhysics - Type is DEGRADER Name DEG1 Material Graphite Particles in material 1000000
 ParallelTTracker {0}> Coll/Deg statistics:  bunch to material 1270 redifused 0 stopped 0
 ParallelTTracker {0}> * Deleted 1266 particles, remaining 4 particles
-ParallelTTracker {0}[3]> 12:37:37 Step    148 at   20.114 [mm] t=  1.490e-10 [s] E=   72.000 [MeV] 
-CollimatorPhysics::apply {0}> All Particles are in the material ... 
+ParallelTTracker {0}[3]> 12:37:37 Step    148 at   20.114 [mm] t=  1.490e-10 [s] E=   72.000 [MeV]
+CollimatorPhysics::apply {0}> All Particles are in the material ...
 ParallelTTracker {0}> --- CollimatorPhysics - Type is DEGRADER Name DEG1 Material Graphite Particles in material 999444
 ParallelTTracker {0}> Coll/Deg statistics:  bunch to material 0 redifused 556 stopped 0
 ParallelTTracker {0}> * Deleted 4 particles, remaining 556 particles
-ParallelTTracker {0}[3]> 12:38:04 Step    149 at   30.171 [mm] t=  1.500e-10 [s] E=   51.407 [MeV] 
+ParallelTTracker {0}[3]> 12:38:04 Step    149 at   30.171 [mm] t=  1.500e-10 [s] E=   51.407 [MeV]
 ParallelTTracker {0}> --- CollimatorPhysics - Type is DEGRADER Name DEG1 Material Graphite Particles in material 997546
 ParallelTTracker {0}> Coll/Deg statistics:  bunch to material 0 redifused 1898 stopped 0
-ParallelTTracker {0}[3]> 12:38:05 Step    150 at   30.203 [mm] t=  1.510e-10 [s] E=   51.223 [MeV] 
+ParallelTTracker {0}[3]> 12:38:05 Step    150 at   30.203 [mm] t=  1.510e-10 [s] E=   51.223 [MeV]
 OPAL {0}[3]> * Wrote beam phase space.
-OPAL {0}> 
-OPAL {0}> * ************** B U N C H ********************************************************* 
+OPAL {0}>
+OPAL {0}> * ************** B U N C H *********************************************************
 OPAL {0}> * NP              =   2454
 OPAL {0}> * Qtot            =    9.69332e-05 [nC]       Qi    =  3.95001e-08 [nC]
 OPAL {0}> * Ekin            =    5.12235e+01 [MeV]      dEkin =  4.89511e-01 [MeV]
@@ -772,42 +772,42 @@ OPAL {0}> * hr              = (  4.47027e-04 ,  4.63170e-04 ,  3.05659e-06 ) [m]
 OPAL {0}> * dh              =    1.00000e-10 [%]
 OPAL {0}> * t               =    1.51000e-10 [s]        dT    =  1.00000e-12 [s]
 OPAL {0}> * spos            =    3.02029e-02 [m]
-OPAL {0}> * ********************************************************************************** 
-OPAL {0}> 
+OPAL {0}> * **********************************************************************************
+OPAL {0}>
 OPAL {0}[3]> * Wrote beam statistics.
 ParallelTTracker {0}> --- CollimatorPhysics - Type is DEGRADER Name DEG1 Material Graphite Particles in material 994132
 ParallelTTracker {0}> Coll/Deg statistics:  bunch to material 0 redifused 3414 stopped 0
-ParallelTTracker {0}[3]> 12:38:05 Step    151 at   30.233 [mm] t=  1.520e-10 [s] E=   51.201 [MeV] 
+ParallelTTracker {0}[3]> 12:38:05 Step    151 at   30.233 [mm] t=  1.520e-10 [s] E=   51.201 [MeV]
 ParallelTTracker {0}> --- CollimatorPhysics - Type is DEGRADER Name DEG1 Material Graphite Particles in material 988357
 ParallelTTracker {0}> Coll/Deg statistics:  bunch to material 0 redifused 5775 stopped 0
-ParallelTTracker {0}[3]> 12:38:06 Step    152 at   30.257 [mm] t=  1.530e-10 [s] E=   51.184 [MeV] 
+ParallelTTracker {0}[3]> 12:38:06 Step    152 at   30.257 [mm] t=  1.530e-10 [s] E=   51.184 [MeV]
 ParallelTTracker {0}> --- CollimatorPhysics - Type is DEGRADER Name DEG1 Material Graphite Particles in material 978778
 ParallelTTracker {0}> Coll/Deg statistics:  bunch to material 0 redifused 9579 stopped 0
-ParallelTTracker {0}[3]> 12:38:06 Step    153 at   30.277 [mm] t=  1.540e-10 [s] E=   51.176 [MeV] 
+ParallelTTracker {0}[3]> 12:38:06 Step    153 at   30.277 [mm] t=  1.540e-10 [s] E=   51.176 [MeV]
 ParallelTTracker {0}> --- CollimatorPhysics - Type is DEGRADER Name DEG1 Material Graphite Particles in material 963940
 ParallelTTracker {0}> Coll/Deg statistics:  bunch to material 0 redifused 14838 stopped 0
-ParallelTTracker {0}[3]> 12:38:06 Step    154 at   30.296 [mm] t=  1.550e-10 [s] E=   51.166 [MeV] 
+ParallelTTracker {0}[3]> 12:38:06 Step    154 at   30.296 [mm] t=  1.550e-10 [s] E=   51.166 [MeV]
 ParallelTTracker {0}> --- CollimatorPhysics - Type is DEGRADER Name DEG1 Material Graphite Particles in material 941961
 ParallelTTracker {0}> Coll/Deg statistics:  bunch to material 0 redifused 21979 stopped 0
-ParallelTTracker {0}[3]> 12:38:07 Step    155 at   30.314 [mm] t=  1.560e-10 [s] E=   51.157 [MeV] 
+ParallelTTracker {0}[3]> 12:38:07 Step    155 at   30.314 [mm] t=  1.560e-10 [s] E=   51.157 [MeV]
 ParallelTTracker {0}> --- CollimatorPhysics - Type is DEGRADER Name DEG1 Material Graphite Particles in material 910612
 ParallelTTracker {0}> Coll/Deg statistics:  bunch to material 0 redifused 31349 stopped 0
-ParallelTTracker {0}[3]> 12:38:07 Step    156 at   30.331 [mm] t=  1.570e-10 [s] E=   51.150 [MeV] 
+ParallelTTracker {0}[3]> 12:38:07 Step    156 at   30.331 [mm] t=  1.570e-10 [s] E=   51.150 [MeV]
 ParallelTTracker {0}> --- CollimatorPhysics - Type is DEGRADER Name DEG1 Material Graphite Particles in material 868915
 ParallelTTracker {0}> Coll/Deg statistics:  bunch to material 0 redifused 41697 stopped 0
-ParallelTTracker {0}[3]> 12:38:07 Step    157 at   30.350 [mm] t=  1.580e-10 [s] E=   51.147 [MeV] 
+ParallelTTracker {0}[3]> 12:38:07 Step    157 at   30.350 [mm] t=  1.580e-10 [s] E=   51.147 [MeV]
 ParallelTTracker {0}> --- CollimatorPhysics - Type is DEGRADER Name DEG1 Material Graphite Particles in material 815294
 ParallelTTracker {0}> Coll/Deg statistics:  bunch to material 0 redifused 53621 stopped 0
-ParallelTTracker {0}[3]> 12:38:08 Step    158 at   30.371 [mm] t=  1.590e-10 [s] E=   51.142 [MeV] 
+ParallelTTracker {0}[3]> 12:38:08 Step    158 at   30.371 [mm] t=  1.590e-10 [s] E=   51.142 [MeV]
 ParallelTTracker {0}> --- CollimatorPhysics - Type is DEGRADER Name DEG1 Material Graphite Particles in material 749848
 ParallelTTracker {0}> Coll/Deg statistics:  bunch to material 0 redifused 65446 stopped 0
-ParallelTTracker {0}[3]> 12:38:08 Step    159 at   30.393 [mm] t=  1.600e-10 [s] E=   51.138 [MeV] 
+ParallelTTracker {0}[3]> 12:38:08 Step    159 at   30.393 [mm] t=  1.600e-10 [s] E=   51.138 [MeV]
 ParallelTTracker {0}> --- CollimatorPhysics - Type is DEGRADER Name DEG1 Material Graphite Particles in material 674364
 ParallelTTracker {0}> Coll/Deg statistics:  bunch to material 0 redifused 75484 stopped 0
-ParallelTTracker {0}[3]> 12:38:08 Step    160 at   30.419 [mm] t=  1.610e-10 [s] E=   51.133 [MeV] 
+ParallelTTracker {0}[3]> 12:38:08 Step    160 at   30.419 [mm] t=  1.610e-10 [s] E=   51.133 [MeV]
 OPAL {0}[3]> * Wrote beam phase space.
-OPAL {0}> 
-OPAL {0}> * ************** B U N C H ********************************************************* 
+OPAL {0}>
+OPAL {0}> * ************** B U N C H *********************************************************
 OPAL {0}> * NP              =   325636
 OPAL {0}> * Qtot            =    1.28627e-02 [nC]       Qi    =  3.95001e-08 [nC]
 OPAL {0}> * Ekin            =    5.11333e+01 [MeV]      dEkin =  5.15605e-01 [MeV]
@@ -823,42 +823,42 @@ OPAL {0}> * hr              = (  4.80715e-04 ,  4.79828e-04 ,  1.83126e-05 ) [m]
 OPAL {0}> * dh              =    1.00000e-10 [%]
 OPAL {0}> * t               =    1.61000e-10 [s]        dT    =  1.00000e-12 [s]
 OPAL {0}> * spos            =    3.04187e-02 [m]
-OPAL {0}> * ********************************************************************************** 
-OPAL {0}> 
+OPAL {0}> * **********************************************************************************
+OPAL {0}>
 OPAL {0}[3]> * Wrote beam statistics.
 ParallelTTracker {0}> --- CollimatorPhysics - Type is DEGRADER Name DEG1 Material Graphite Particles in material 590133
 ParallelTTracker {0}> Coll/Deg statistics:  bunch to material 0 redifused 84231 stopped 0
-ParallelTTracker {0}[3]> 12:38:09 Step    161 at   30.447 [mm] t=  1.620e-10 [s] E=   51.131 [MeV] 
+ParallelTTracker {0}[3]> 12:38:09 Step    161 at   30.447 [mm] t=  1.620e-10 [s] E=   51.131 [MeV]
 ParallelTTracker {0}> --- CollimatorPhysics - Type is DEGRADER Name DEG1 Material Graphite Particles in material 501867
 ParallelTTracker {0}> Coll/Deg statistics:  bunch to material 0 redifused 88266 stopped 0
-ParallelTTracker {0}[3]> 12:38:09 Step    162 at   30.480 [mm] t=  1.630e-10 [s] E=   51.127 [MeV] 
+ParallelTTracker {0}[3]> 12:38:09 Step    162 at   30.480 [mm] t=  1.630e-10 [s] E=   51.127 [MeV]
 ParallelTTracker {0}> --- CollimatorPhysics - Type is DEGRADER Name DEG1 Material Graphite Particles in material 413630
 ParallelTTracker {0}> Coll/Deg statistics:  bunch to material 0 redifused 88237 stopped 0
-ParallelTTracker {0}[3]> 12:38:10 Step    163 at   30.517 [mm] t=  1.640e-10 [s] E=   51.124 [MeV] 
+ParallelTTracker {0}[3]> 12:38:10 Step    163 at   30.517 [mm] t=  1.640e-10 [s] E=   51.124 [MeV]
 ParallelTTracker {0}> --- CollimatorPhysics - Type is DEGRADER Name DEG1 Material Graphite Particles in material 329314
 ParallelTTracker {0}> Coll/Deg statistics:  bunch to material 0 redifused 84316 stopped 0
-ParallelTTracker {0}[3]> 12:38:10 Step    164 at   30.559 [mm] t=  1.650e-10 [s] E=   51.121 [MeV] 
+ParallelTTracker {0}[3]> 12:38:10 Step    164 at   30.559 [mm] t=  1.650e-10 [s] E=   51.121 [MeV]
 ParallelTTracker {0}> --- CollimatorPhysics - Type is DEGRADER Name DEG1 Material Graphite Particles in material 253146
 ParallelTTracker {0}> Coll/Deg statistics:  bunch to material 0 redifused 76168 stopped 0
-ParallelTTracker {0}[3]> 12:38:10 Step    165 at   30.606 [mm] t=  1.660e-10 [s] E=   51.119 [MeV] 
+ParallelTTracker {0}[3]> 12:38:10 Step    165 at   30.606 [mm] t=  1.660e-10 [s] E=   51.119 [MeV]
 ParallelTTracker {0}> --- CollimatorPhysics - Type is DEGRADER Name DEG1 Material Graphite Particles in material 187163
 ParallelTTracker {0}> Coll/Deg statistics:  bunch to material 0 redifused 65983 stopped 0
-ParallelTTracker {0}[3]> 12:38:10 Step    166 at   30.660 [mm] t=  1.670e-10 [s] E=   51.117 [MeV] 
+ParallelTTracker {0}[3]> 12:38:10 Step    166 at   30.660 [mm] t=  1.670e-10 [s] E=   51.117 [MeV]
 ParallelTTracker {0}> --- CollimatorPhysics - Type is DEGRADER Name DEG1 Material Graphite Particles in material 133254
 ParallelTTracker {0}> Coll/Deg statistics:  bunch to material 0 redifused 53909 stopped 0
-ParallelTTracker {0}[3]> 12:38:11 Step    167 at   30.720 [mm] t=  1.680e-10 [s] E=   51.115 [MeV] 
+ParallelTTracker {0}[3]> 12:38:11 Step    167 at   30.720 [mm] t=  1.680e-10 [s] E=   51.115 [MeV]
 ParallelTTracker {0}> --- CollimatorPhysics - Type is DEGRADER Name DEG1 Material Graphite Particles in material 90631
 ParallelTTracker {0}> Coll/Deg statistics:  bunch to material 0 redifused 42623 stopped 0
-ParallelTTracker {0}[3]> 12:38:11 Step    168 at   30.786 [mm] t=  1.690e-10 [s] E=   51.113 [MeV] 
+ParallelTTracker {0}[3]> 12:38:11 Step    168 at   30.786 [mm] t=  1.690e-10 [s] E=   51.113 [MeV]
 ParallelTTracker {0}> --- CollimatorPhysics - Type is DEGRADER Name DEG1 Material Graphite Particles in material 59192
 ParallelTTracker {0}> Coll/Deg statistics:  bunch to material 0 redifused 31439 stopped 0
-ParallelTTracker {0}[3]> 12:38:11 Step    169 at   30.858 [mm] t=  1.700e-10 [s] E=   51.111 [MeV] 
+ParallelTTracker {0}[3]> 12:38:11 Step    169 at   30.858 [mm] t=  1.700e-10 [s] E=   51.111 [MeV]
 ParallelTTracker {0}> --- CollimatorPhysics - Type is DEGRADER Name DEG1 Material Graphite Particles in material 37012
 ParallelTTracker {0}> Coll/Deg statistics:  bunch to material 0 redifused 22180 stopped 0
-ParallelTTracker {0}[3]> 12:38:11 Step    170 at   30.935 [mm] t=  1.710e-10 [s] E=   51.110 [MeV] 
+ParallelTTracker {0}[3]> 12:38:11 Step    170 at   30.935 [mm] t=  1.710e-10 [s] E=   51.110 [MeV]
 OPAL {0}[3]> * Wrote beam phase space.
-OPAL {0}> 
-OPAL {0}> * ************** B U N C H ********************************************************* 
+OPAL {0}>
+OPAL {0}> * ************** B U N C H *********************************************************
 OPAL {0}> * NP              =   962988
 OPAL {0}> * Qtot            =    3.80381e-02 [nC]       Qi    =  3.95001e-08 [nC]
 OPAL {0}> * Ekin            =    5.11104e+01 [MeV]      dEkin =  5.37910e-01 [MeV]
@@ -874,42 +874,42 @@ OPAL {0}> * hr              = (  4.86393e-04 ,  4.89781e-04 ,  3.37036e-05 ) [m]
 OPAL {0}> * dh              =    1.00000e-10 [%]
 OPAL {0}> * t               =    1.71000e-10 [s]        dT    =  1.00000e-12 [s]
 OPAL {0}> * spos            =    3.09354e-02 [m]
-OPAL {0}> * ********************************************************************************** 
-OPAL {0}> 
+OPAL {0}> * **********************************************************************************
+OPAL {0}>
 OPAL {0}[3]> * Wrote beam statistics.
 ParallelTTracker {0}> --- CollimatorPhysics - Type is DEGRADER Name DEG1 Material Graphite Particles in material 21765
 ParallelTTracker {0}> Coll/Deg statistics:  bunch to material 0 redifused 15247 stopped 0
-ParallelTTracker {0}[3]> 12:38:12 Step    171 at   31.017 [mm] t=  1.720e-10 [s] E=   51.110 [MeV] 
+ParallelTTracker {0}[3]> 12:38:12 Step    171 at   31.017 [mm] t=  1.720e-10 [s] E=   51.110 [MeV]
 ParallelTTracker {0}> --- CollimatorPhysics - Type is DEGRADER Name DEG1 Material Graphite Particles in material 11945
 ParallelTTracker {0}> Coll/Deg statistics:  bunch to material 0 redifused 9820 stopped 0
-ParallelTTracker {0}[3]> 12:38:13 Step    172 at   31.103 [mm] t=  1.730e-10 [s] E=   51.109 [MeV] 
+ParallelTTracker {0}[3]> 12:38:13 Step    172 at   31.103 [mm] t=  1.730e-10 [s] E=   51.109 [MeV]
 ParallelTTracker {0}> --- CollimatorPhysics - Type is DEGRADER Name DEG1 Material Graphite Particles in material 6072
 ParallelTTracker {0}> Coll/Deg statistics:  bunch to material 0 redifused 5873 stopped 0
-ParallelTTracker {0}[3]> 12:38:13 Step    173 at   31.192 [mm] t=  1.740e-10 [s] E=   51.109 [MeV] 
+ParallelTTracker {0}[3]> 12:38:13 Step    173 at   31.192 [mm] t=  1.740e-10 [s] E=   51.109 [MeV]
 ParallelTTracker {0}> --- CollimatorPhysics - Type is DEGRADER Name DEG1 Material Graphite Particles in material 2681
 ParallelTTracker {0}> Coll/Deg statistics:  bunch to material 0 redifused 3391 stopped 0
-ParallelTTracker {0}[3]> 12:38:13 Step    174 at   31.284 [mm] t=  1.750e-10 [s] E=   51.109 [MeV] 
+ParallelTTracker {0}[3]> 12:38:13 Step    174 at   31.284 [mm] t=  1.750e-10 [s] E=   51.109 [MeV]
 ParallelTTracker {0}> --- CollimatorPhysics - Type is DEGRADER Name DEG1 Material Graphite Particles in material 707
 ParallelTTracker {0}> Coll/Deg statistics:  bunch to material 0 redifused 1974 stopped 0
-ParallelTTracker {0}[3]> 12:38:13 Step    175 at   31.376 [mm] t=  1.760e-10 [s] E=   51.109 [MeV] 
+ParallelTTracker {0}[3]> 12:38:13 Step    175 at   31.376 [mm] t=  1.760e-10 [s] E=   51.109 [MeV]
 ParallelTTracker {0}> --- CollimatorPhysics - Type is DEGRADER Name DEG1 Material Graphite Particles in material 90
 ParallelTTracker {0}> Coll/Deg statistics:  bunch to material 0 redifused 617 stopped 0
-ParallelTTracker {0}[3]> 12:38:14 Step    176 at   31.471 [mm] t=  1.770e-10 [s] E=   51.108 [MeV] 
+ParallelTTracker {0}[3]> 12:38:14 Step    176 at   31.471 [mm] t=  1.770e-10 [s] E=   51.108 [MeV]
 ParallelTTracker {0}> --- CollimatorPhysics - Type is DEGRADER Name DEG1 Material Graphite Particles in material 81
 ParallelTTracker {0}> Coll/Deg statistics:  bunch to material 0 redifused 9 stopped 0
-ParallelTTracker {0}[3]> 12:38:14 Step    177 at   31.566 [mm] t=  1.780e-10 [s] E=   51.108 [MeV] 
+ParallelTTracker {0}[3]> 12:38:14 Step    177 at   31.566 [mm] t=  1.780e-10 [s] E=   51.108 [MeV]
 ParallelTTracker {0}> --- CollimatorPhysics - Type is DEGRADER Name DEG1 Material Graphite Particles in material 76
 ParallelTTracker {0}> Coll/Deg statistics:  bunch to material 0 redifused 5 stopped 0
-ParallelTTracker {0}[3]> 12:38:14 Step    178 at   31.661 [mm] t=  1.790e-10 [s] E=   51.108 [MeV] 
+ParallelTTracker {0}[3]> 12:38:14 Step    178 at   31.661 [mm] t=  1.790e-10 [s] E=   51.108 [MeV]
 ParallelTTracker {0}> --- CollimatorPhysics - Type is DEGRADER Name DEG1 Material Graphite Particles in material 74
 ParallelTTracker {0}> Coll/Deg statistics:  bunch to material 0 redifused 2 stopped 0
-ParallelTTracker {0}[3]> 12:38:14 Step    179 at   31.756 [mm] t=  1.800e-10 [s] E=   51.108 [MeV] 
+ParallelTTracker {0}[3]> 12:38:14 Step    179 at   31.756 [mm] t=  1.800e-10 [s] E=   51.108 [MeV]
 ParallelTTracker {0}> --- CollimatorPhysics - Type is DEGRADER Name DEG1 Material Graphite Particles in material 70
 ParallelTTracker {0}> Coll/Deg statistics:  bunch to material 0 redifused 4 stopped 0
-ParallelTTracker {0}[3]> 12:38:14 Step    180 at   31.851 [mm] t=  1.810e-10 [s] E=   51.108 [MeV] 
+ParallelTTracker {0}[3]> 12:38:14 Step    180 at   31.851 [mm] t=  1.810e-10 [s] E=   51.108 [MeV]
 OPAL {0}[3]> * Wrote beam phase space.
-OPAL {0}> 
-OPAL {0}> * ************** B U N C H ********************************************************* 
+OPAL {0}>
+OPAL {0}> * ************** B U N C H *********************************************************
 OPAL {0}> * NP              =   999930
 OPAL {0}> * Qtot            =    3.94973e-02 [nC]       Qi    =  3.95001e-08 [nC]
 OPAL {0}> * Ekin            =    5.11083e+01 [MeV]      dEkin =  5.58829e-01 [MeV]
@@ -925,42 +925,42 @@ OPAL {0}> * hr              = (  4.95681e-04 ,  5.15848e-04 ,  4.85823e-05 ) [m]
 OPAL {0}> * dh              =    1.00000e-10 [%]
 OPAL {0}> * t               =    1.81000e-10 [s]        dT    =  1.00000e-12 [s]
 OPAL {0}> * spos            =    3.18509e-02 [m]
-OPAL {0}> * ********************************************************************************** 
-OPAL {0}> 
+OPAL {0}> * **********************************************************************************
+OPAL {0}>
 OPAL {0}[3]> * Wrote beam statistics.
 ParallelTTracker {0}> --- CollimatorPhysics - Type is DEGRADER Name DEG1 Material Graphite Particles in material 65
 ParallelTTracker {0}> Coll/Deg statistics:  bunch to material 0 redifused 5 stopped 0
-ParallelTTracker {0}[3]> 12:38:16 Step    181 at   31.946 [mm] t=  1.820e-10 [s] E=   51.108 [MeV] 
+ParallelTTracker {0}[3]> 12:38:16 Step    181 at   31.946 [mm] t=  1.820e-10 [s] E=   51.108 [MeV]
 ParallelTTracker {0}> --- CollimatorPhysics - Type is DEGRADER Name DEG1 Material Graphite Particles in material 60
 ParallelTTracker {0}> Coll/Deg statistics:  bunch to material 0 redifused 5 stopped 0
-ParallelTTracker {0}[3]> 12:38:16 Step    182 at   32.041 [mm] t=  1.830e-10 [s] E=   51.108 [MeV] 
+ParallelTTracker {0}[3]> 12:38:16 Step    182 at   32.041 [mm] t=  1.830e-10 [s] E=   51.108 [MeV]
 ParallelTTracker {0}> --- CollimatorPhysics - Type is DEGRADER Name DEG1 Material Graphite Particles in material 59
 ParallelTTracker {0}> Coll/Deg statistics:  bunch to material 0 redifused 1 stopped 0
-ParallelTTracker {0}[3]> 12:38:16 Step    183 at   32.136 [mm] t=  1.840e-10 [s] E=   51.108 [MeV] 
+ParallelTTracker {0}[3]> 12:38:16 Step    183 at   32.136 [mm] t=  1.840e-10 [s] E=   51.108 [MeV]
 ParallelTTracker {0}> --- CollimatorPhysics - Type is DEGRADER Name DEG1 Material Graphite Particles in material 56
 ParallelTTracker {0}> Coll/Deg statistics:  bunch to material 0 redifused 3 stopped 0
-ParallelTTracker {0}[3]> 12:38:17 Step    184 at   32.231 [mm] t=  1.850e-10 [s] E=   51.108 [MeV] 
+ParallelTTracker {0}[3]> 12:38:17 Step    184 at   32.231 [mm] t=  1.850e-10 [s] E=   51.108 [MeV]
 ParallelTTracker {0}> --- CollimatorPhysics - Type is DEGRADER Name DEG1 Material Graphite Particles in material 56
 ParallelTTracker {0}> Coll/Deg statistics:  bunch to material 0 redifused 0 stopped 0
-ParallelTTracker {0}[3]> 12:38:17 Step    185 at   32.326 [mm] t=  1.860e-10 [s] E=   51.108 [MeV] 
+ParallelTTracker {0}[3]> 12:38:17 Step    185 at   32.326 [mm] t=  1.860e-10 [s] E=   51.108 [MeV]
 ParallelTTracker {0}> --- CollimatorPhysics - Type is DEGRADER Name DEG1 Material Graphite Particles in material 54
 ParallelTTracker {0}> Coll/Deg statistics:  bunch to material 0 redifused 2 stopped 0
-ParallelTTracker {0}[3]> 12:38:17 Step    186 at   32.421 [mm] t=  1.870e-10 [s] E=   51.108 [MeV] 
+ParallelTTracker {0}[3]> 12:38:17 Step    186 at   32.421 [mm] t=  1.870e-10 [s] E=   51.108 [MeV]
 ParallelTTracker {0}> --- CollimatorPhysics - Type is DEGRADER Name DEG1 Material Graphite Particles in material 53
 ParallelTTracker {0}> Coll/Deg statistics:  bunch to material 0 redifused 1 stopped 0
-ParallelTTracker {0}[3]> 12:38:17 Step    187 at   32.516 [mm] t=  1.880e-10 [s] E=   51.108 [MeV] 
+ParallelTTracker {0}[3]> 12:38:17 Step    187 at   32.516 [mm] t=  1.880e-10 [s] E=   51.108 [MeV]
 ParallelTTracker {0}> --- CollimatorPhysics - Type is DEGRADER Name DEG1 Material Graphite Particles in material 53
 ParallelTTracker {0}> Coll/Deg statistics:  bunch to material 0 redifused 0 stopped 0
-ParallelTTracker {0}[3]> 12:38:18 Step    188 at   32.611 [mm] t=  1.890e-10 [s] E=   51.108 [MeV] 
+ParallelTTracker {0}[3]> 12:38:18 Step    188 at   32.611 [mm] t=  1.890e-10 [s] E=   51.108 [MeV]
 ParallelTTracker {0}> --- CollimatorPhysics - Type is DEGRADER Name DEG1 Material Graphite Particles in material 52
 ParallelTTracker {0}> Coll/Deg statistics:  bunch to material 0 redifused 1 stopped 0
-ParallelTTracker {0}[3]> 12:38:18 Step    189 at   32.706 [mm] t=  1.900e-10 [s] E=   51.108 [MeV] 
+ParallelTTracker {0}[3]> 12:38:18 Step    189 at   32.706 [mm] t=  1.900e-10 [s] E=   51.108 [MeV]
 ParallelTTracker {0}> --- CollimatorPhysics - Type is DEGRADER Name DEG1 Material Graphite Particles in material 51
 ParallelTTracker {0}> Coll/Deg statistics:  bunch to material 0 redifused 1 stopped 0
-ParallelTTracker {0}[3]> 12:38:18 Step    190 at   32.801 [mm] t=  1.910e-10 [s] E=   51.108 [MeV] 
+ParallelTTracker {0}[3]> 12:38:18 Step    190 at   32.801 [mm] t=  1.910e-10 [s] E=   51.108 [MeV]
 OPAL {0}[3]> * Wrote beam phase space.
-OPAL {0}> 
-OPAL {0}> * ************** B U N C H ********************************************************* 
+OPAL {0}>
+OPAL {0}> * ************** B U N C H *********************************************************
 OPAL {0}> * NP              =   999949
 OPAL {0}> * Qtot            =    3.94981e-02 [nC]       Qi    =  3.95001e-08 [nC]
 OPAL {0}> * Ekin            =    5.11082e+01 [MeV]      dEkin =  5.73296e-01 [MeV]
@@ -976,42 +976,42 @@ OPAL {0}> * hr              = (  5.34719e-04 ,  5.22085e-04 ,  6.44964e-05 ) [m]
 OPAL {0}> * dh              =    1.00000e-10 [%]
 OPAL {0}> * t               =    1.91000e-10 [s]        dT    =  1.00000e-12 [s]
 OPAL {0}> * spos            =    3.28015e-02 [m]
-OPAL {0}> * ********************************************************************************** 
-OPAL {0}> 
+OPAL {0}> * **********************************************************************************
+OPAL {0}>
 OPAL {0}[3]> * Wrote beam statistics.
 ParallelTTracker {0}> --- CollimatorPhysics - Type is DEGRADER Name DEG1 Material Graphite Particles in material 51
 ParallelTTracker {0}> Coll/Deg statistics:  bunch to material 0 redifused 0 stopped 0
-ParallelTTracker {0}[3]> 12:38:20 Step    191 at   32.897 [mm] t=  1.920e-10 [s] E=   51.108 [MeV] 
+ParallelTTracker {0}[3]> 12:38:20 Step    191 at   32.897 [mm] t=  1.920e-10 [s] E=   51.108 [MeV]
 ParallelTTracker {0}> --- CollimatorPhysics - Type is DEGRADER Name DEG1 Material Graphite Particles in material 48
 ParallelTTracker {0}> Coll/Deg statistics:  bunch to material 0 redifused 3 stopped 0
-ParallelTTracker {0}[3]> 12:38:20 Step    192 at   32.992 [mm] t=  1.930e-10 [s] E=   51.108 [MeV] 
+ParallelTTracker {0}[3]> 12:38:20 Step    192 at   32.992 [mm] t=  1.930e-10 [s] E=   51.108 [MeV]
 ParallelTTracker {0}> --- CollimatorPhysics - Type is DEGRADER Name DEG1 Material Graphite Particles in material 46
 ParallelTTracker {0}> Coll/Deg statistics:  bunch to material 0 redifused 2 stopped 0
-ParallelTTracker {0}[3]> 12:38:20 Step    193 at   33.087 [mm] t=  1.940e-10 [s] E=   51.108 [MeV] 
+ParallelTTracker {0}[3]> 12:38:20 Step    193 at   33.087 [mm] t=  1.940e-10 [s] E=   51.108 [MeV]
 ParallelTTracker {0}> --- CollimatorPhysics - Type is DEGRADER Name DEG1 Material Graphite Particles in material 45
 ParallelTTracker {0}> Coll/Deg statistics:  bunch to material 0 redifused 1 stopped 0
-ParallelTTracker {0}[3]> 12:38:20 Step    194 at   33.182 [mm] t=  1.950e-10 [s] E=   51.108 [MeV] 
+ParallelTTracker {0}[3]> 12:38:20 Step    194 at   33.182 [mm] t=  1.950e-10 [s] E=   51.108 [MeV]
 ParallelTTracker {0}> --- CollimatorPhysics - Type is DEGRADER Name DEG1 Material Graphite Particles in material 45
 ParallelTTracker {0}> Coll/Deg statistics:  bunch to material 0 redifused 0 stopped 0
-ParallelTTracker {0}[3]> 12:38:20 Step    195 at   33.277 [mm] t=  1.960e-10 [s] E=   51.108 [MeV] 
+ParallelTTracker {0}[3]> 12:38:20 Step    195 at   33.277 [mm] t=  1.960e-10 [s] E=   51.108 [MeV]
 ParallelTTracker {0}> --- CollimatorPhysics - Type is DEGRADER Name DEG1 Material Graphite Particles in material 45
 ParallelTTracker {0}> Coll/Deg statistics:  bunch to material 0 redifused 0 stopped 0
-ParallelTTracker {0}[3]> 12:38:21 Step    196 at   33.372 [mm] t=  1.970e-10 [s] E=   51.108 [MeV] 
+ParallelTTracker {0}[3]> 12:38:21 Step    196 at   33.372 [mm] t=  1.970e-10 [s] E=   51.108 [MeV]
 ParallelTTracker {0}> --- CollimatorPhysics - Type is DEGRADER Name DEG1 Material Graphite Particles in material 44
 ParallelTTracker {0}> Coll/Deg statistics:  bunch to material 0 redifused 1 stopped 0
-ParallelTTracker {0}[3]> 12:38:21 Step    197 at   33.467 [mm] t=  1.980e-10 [s] E=   51.108 [MeV] 
+ParallelTTracker {0}[3]> 12:38:21 Step    197 at   33.467 [mm] t=  1.980e-10 [s] E=   51.108 [MeV]
 ParallelTTracker {0}> --- CollimatorPhysics - Type is DEGRADER Name DEG1 Material Graphite Particles in material 44
 ParallelTTracker {0}> Coll/Deg statistics:  bunch to material 0 redifused 0 stopped 0
-ParallelTTracker {0}[3]> 12:38:21 Step    198 at   33.562 [mm] t=  1.990e-10 [s] E=   51.108 [MeV] 
+ParallelTTracker {0}[3]> 12:38:21 Step    198 at   33.562 [mm] t=  1.990e-10 [s] E=   51.108 [MeV]
 ParallelTTracker {0}> --- CollimatorPhysics - Type is DEGRADER Name DEG1 Material Graphite Particles in material 43
 ParallelTTracker {0}> Coll/Deg statistics:  bunch to material 0 redifused 1 stopped 0
-ParallelTTracker {0}[2]> 12:38:21 Step    199 at   33.657 [mm] t=  2.000e-10 [s] E=   51.108 [MeV] 
+ParallelTTracker {0}[2]> 12:38:21 Step    199 at   33.657 [mm] t=  2.000e-10 [s] E=   51.108 [MeV]
 ParallelTTracker {0}> --- CollimatorPhysics - Type is DEGRADER Name DEG1 Material Graphite Particles in material 43
 ParallelTTracker {0}> Coll/Deg statistics:  bunch to material 0 redifused 0 stopped 0
-ParallelTTracker {0}[3]> 12:38:21 Step    200 at   33.752 [mm] t=  2.010e-10 [s] E=   51.108 [MeV] 
+ParallelTTracker {0}[3]> 12:38:21 Step    200 at   33.752 [mm] t=  2.010e-10 [s] E=   51.108 [MeV]
 OPAL {0}[3]> * Wrote beam phase space.
-OPAL {0}> 
-OPAL {0}> * ************** B U N C H ********************************************************* 
+OPAL {0}>
+OPAL {0}> * ************** B U N C H *********************************************************
 OPAL {0}> * NP              =   999957
 OPAL {0}> * Qtot            =    3.94984e-02 [nC]       Qi    =  3.95001e-08 [nC]
 OPAL {0}> * Ekin            =    5.11081e+01 [MeV]      dEkin =  5.87798e-01 [MeV]
@@ -1027,42 +1027,42 @@ OPAL {0}> * hr              = (  5.51244e-04 ,  5.28322e-04 ,  7.94477e-05 ) [m]
 OPAL {0}> * dh              =    1.00000e-10 [%]
 OPAL {0}> * t               =    2.01000e-10 [s]        dT    =  1.00000e-12 [s]
 OPAL {0}> * spos            =    3.37520e-02 [m]
-OPAL {0}> * ********************************************************************************** 
-OPAL {0}> 
+OPAL {0}> * **********************************************************************************
+OPAL {0}>
 OPAL {0}[3]> * Wrote beam statistics.
 ParallelTTracker {0}> --- CollimatorPhysics - Type is DEGRADER Name DEG1 Material Graphite Particles in material 42
 ParallelTTracker {0}> Coll/Deg statistics:  bunch to material 0 redifused 1 stopped 0
-ParallelTTracker {0}[3]> 12:38:23 Step    201 at   33.847 [mm] t=  2.020e-10 [s] E=   51.108 [MeV] 
+ParallelTTracker {0}[3]> 12:38:23 Step    201 at   33.847 [mm] t=  2.020e-10 [s] E=   51.108 [MeV]
 ParallelTTracker {0}> --- CollimatorPhysics - Type is DEGRADER Name DEG1 Material Graphite Particles in material 42
 ParallelTTracker {0}> Coll/Deg statistics:  bunch to material 0 redifused 0 stopped 0
-ParallelTTracker {0}[3]> 12:38:23 Step    202 at   33.942 [mm] t=  2.030e-10 [s] E=   51.108 [MeV] 
+ParallelTTracker {0}[3]> 12:38:23 Step    202 at   33.942 [mm] t=  2.030e-10 [s] E=   51.108 [MeV]
 ParallelTTracker {0}> --- CollimatorPhysics - Type is DEGRADER Name DEG1 Material Graphite Particles in material 40
 ParallelTTracker {0}> Coll/Deg statistics:  bunch to material 0 redifused 2 stopped 0
-ParallelTTracker {0}[3]> 12:38:23 Step    203 at   34.037 [mm] t=  2.040e-10 [s] E=   51.108 [MeV] 
+ParallelTTracker {0}[3]> 12:38:23 Step    203 at   34.037 [mm] t=  2.040e-10 [s] E=   51.108 [MeV]
 ParallelTTracker {0}> --- CollimatorPhysics - Type is DEGRADER Name DEG1 Material Graphite Particles in material 38
 ParallelTTracker {0}> Coll/Deg statistics:  bunch to material 0 redifused 2 stopped 0
-ParallelTTracker {0}[3]> 12:38:23 Step    204 at   34.132 [mm] t=  2.050e-10 [s] E=   51.108 [MeV] 
+ParallelTTracker {0}[3]> 12:38:23 Step    204 at   34.132 [mm] t=  2.050e-10 [s] E=   51.108 [MeV]
 ParallelTTracker {0}> --- CollimatorPhysics - Type is DEGRADER Name DEG1 Material Graphite Particles in material 37
 ParallelTTracker {0}> Coll/Deg statistics:  bunch to material 0 redifused 1 stopped 0
-ParallelTTracker {0}[3]> 12:38:24 Step    205 at   34.227 [mm] t=  2.060e-10 [s] E=   51.108 [MeV] 
+ParallelTTracker {0}[3]> 12:38:24 Step    205 at   34.227 [mm] t=  2.060e-10 [s] E=   51.108 [MeV]
 ParallelTTracker {0}> --- CollimatorPhysics - Type is DEGRADER Name DEG1 Material Graphite Particles in material 37
 ParallelTTracker {0}> Coll/Deg statistics:  bunch to material 0 redifused 0 stopped 0
-ParallelTTracker {0}[3]> 12:38:24 Step    206 at   34.322 [mm] t=  2.070e-10 [s] E=   51.108 [MeV] 
+ParallelTTracker {0}[3]> 12:38:24 Step    206 at   34.322 [mm] t=  2.070e-10 [s] E=   51.108 [MeV]
 ParallelTTracker {0}> --- CollimatorPhysics - Type is DEGRADER Name DEG1 Material Graphite Particles in material 37
 ParallelTTracker {0}> Coll/Deg statistics:  bunch to material 0 redifused 0 stopped 0
-ParallelTTracker {0}[3]> 12:38:24 Step    207 at   34.417 [mm] t=  2.080e-10 [s] E=   51.108 [MeV] 
+ParallelTTracker {0}[3]> 12:38:24 Step    207 at   34.417 [mm] t=  2.080e-10 [s] E=   51.108 [MeV]
 ParallelTTracker {0}> --- CollimatorPhysics - Type is DEGRADER Name DEG1 Material Graphite Particles in material 36
 ParallelTTracker {0}> Coll/Deg statistics:  bunch to material 0 redifused 1 stopped 0
-ParallelTTracker {0}[3]> 12:38:24 Step    208 at   34.512 [mm] t=  2.090e-10 [s] E=   51.108 [MeV] 
+ParallelTTracker {0}[3]> 12:38:24 Step    208 at   34.512 [mm] t=  2.090e-10 [s] E=   51.108 [MeV]
 ParallelTTracker {0}> --- CollimatorPhysics - Type is DEGRADER Name DEG1 Material Graphite Particles in material 34
 ParallelTTracker {0}> Coll/Deg statistics:  bunch to material 0 redifused 2 stopped 0
-ParallelTTracker {0}[3]> 12:38:25 Step    209 at   34.607 [mm] t=  2.100e-10 [s] E=   51.108 [MeV] 
+ParallelTTracker {0}[3]> 12:38:25 Step    209 at   34.607 [mm] t=  2.100e-10 [s] E=   51.108 [MeV]
 ParallelTTracker {0}> --- CollimatorPhysics - Type is DEGRADER Name DEG1 Material Graphite Particles in material 33
 ParallelTTracker {0}> Coll/Deg statistics:  bunch to material 0 redifused 1 stopped 0
-ParallelTTracker {0}[3]> 12:38:25 Step    210 at   34.702 [mm] t=  2.110e-10 [s] E=   51.108 [MeV] 
+ParallelTTracker {0}[3]> 12:38:25 Step    210 at   34.702 [mm] t=  2.110e-10 [s] E=   51.108 [MeV]
 OPAL {0}[3]> * Wrote beam phase space.
-OPAL {0}> 
-OPAL {0}> * ************** B U N C H ********************************************************* 
+OPAL {0}>
+OPAL {0}> * ************** B U N C H *********************************************************
 OPAL {0}> * NP              =   999967
 OPAL {0}> * Qtot            =    3.94988e-02 [nC]       Qi    =  3.95001e-08 [nC]
 OPAL {0}> * Ekin            =    5.11080e+01 [MeV]      dEkin =  6.10073e-01 [MeV]
@@ -1078,42 +1078,42 @@ OPAL {0}> * hr              = (  5.67770e-04 ,  5.34559e-04 ,  9.55869e-05 ) [m]
 OPAL {0}> * dh              =    1.00000e-10 [%]
 OPAL {0}> * t               =    2.11000e-10 [s]        dT    =  1.00000e-12 [s]
 OPAL {0}> * spos            =    3.47025e-02 [m]
-OPAL {0}> * ********************************************************************************** 
-OPAL {0}> 
+OPAL {0}> * **********************************************************************************
+OPAL {0}>
 OPAL {0}[3]> * Wrote beam statistics.
 ParallelTTracker {0}> --- CollimatorPhysics - Type is DEGRADER Name DEG1 Material Graphite Particles in material 31
 ParallelTTracker {0}> Coll/Deg statistics:  bunch to material 0 redifused 2 stopped 0
-ParallelTTracker {0}[3]> 12:38:26 Step    211 at   34.798 [mm] t=  2.120e-10 [s] E=   51.108 [MeV] 
+ParallelTTracker {0}[3]> 12:38:26 Step    211 at   34.798 [mm] t=  2.120e-10 [s] E=   51.108 [MeV]
 ParallelTTracker {0}> --- CollimatorPhysics - Type is DEGRADER Name DEG1 Material Graphite Particles in material 31
 ParallelTTracker {0}> Coll/Deg statistics:  bunch to material 0 redifused 0 stopped 0
-ParallelTTracker {0}[3]> 12:38:26 Step    212 at   34.893 [mm] t=  2.130e-10 [s] E=   51.108 [MeV] 
+ParallelTTracker {0}[3]> 12:38:26 Step    212 at   34.893 [mm] t=  2.130e-10 [s] E=   51.108 [MeV]
 ParallelTTracker {0}> --- CollimatorPhysics - Type is DEGRADER Name DEG1 Material Graphite Particles in material 30
 ParallelTTracker {0}> Coll/Deg statistics:  bunch to material 0 redifused 1 stopped 0
-ParallelTTracker {0}[3]> 12:38:26 Step    213 at   34.988 [mm] t=  2.140e-10 [s] E=   51.108 [MeV] 
+ParallelTTracker {0}[3]> 12:38:26 Step    213 at   34.988 [mm] t=  2.140e-10 [s] E=   51.108 [MeV]
 ParallelTTracker {0}> --- CollimatorPhysics - Type is DEGRADER Name DEG1 Material Graphite Particles in material 30
 ParallelTTracker {0}> Coll/Deg statistics:  bunch to material 0 redifused 0 stopped 0
-ParallelTTracker {0}[3]> 12:38:27 Step    214 at   35.083 [mm] t=  2.150e-10 [s] E=   51.108 [MeV] 
+ParallelTTracker {0}[3]> 12:38:27 Step    214 at   35.083 [mm] t=  2.150e-10 [s] E=   51.108 [MeV]
 ParallelTTracker {0}> --- CollimatorPhysics - Type is DEGRADER Name DEG1 Material Graphite Particles in material 30
 ParallelTTracker {0}> Coll/Deg statistics:  bunch to material 0 redifused 0 stopped 0
-ParallelTTracker {0}[3]> 12:38:27 Step    215 at   35.178 [mm] t=  2.160e-10 [s] E=   51.108 [MeV] 
+ParallelTTracker {0}[3]> 12:38:27 Step    215 at   35.178 [mm] t=  2.160e-10 [s] E=   51.108 [MeV]
 ParallelTTracker {0}> --- CollimatorPhysics - Type is DEGRADER Name DEG1 Material Graphite Particles in material 29
 ParallelTTracker {0}> Coll/Deg statistics:  bunch to material 0 redifused 1 stopped 0
-ParallelTTracker {0}[3]> 12:38:27 Step    216 at   35.273 [mm] t=  2.170e-10 [s] E=   51.108 [MeV] 
+ParallelTTracker {0}[3]> 12:38:27 Step    216 at   35.273 [mm] t=  2.170e-10 [s] E=   51.108 [MeV]
 ParallelTTracker {0}> --- CollimatorPhysics - Type is DEGRADER Name DEG1 Material Graphite Particles in material 29
 ParallelTTracker {0}> Coll/Deg statistics:  bunch to material 0 redifused 0 stopped 0
-ParallelTTracker {0}[3]> 12:38:27 Step    217 at   35.368 [mm] t=  2.180e-10 [s] E=   51.108 [MeV] 
+ParallelTTracker {0}[3]> 12:38:27 Step    217 at   35.368 [mm] t=  2.180e-10 [s] E=   51.108 [MeV]
 ParallelTTracker {0}> --- CollimatorPhysics - Type is DEGRADER Name DEG1 Material Graphite Particles in material 29
 ParallelTTracker {0}> Coll/Deg statistics:  bunch to material 0 redifused 0 stopped 0
-ParallelTTracker {0}[3]> 12:38:28 Step    218 at   35.463 [mm] t=  2.190e-10 [s] E=   51.108 [MeV] 
+ParallelTTracker {0}[3]> 12:38:28 Step    218 at   35.463 [mm] t=  2.190e-10 [s] E=   51.108 [MeV]
 ParallelTTracker {0}> --- CollimatorPhysics - Type is DEGRADER Name DEG1 Material Graphite Particles in material 29
 ParallelTTracker {0}> Coll/Deg statistics:  bunch to material 0 redifused 0 stopped 0
-ParallelTTracker {0}[3]> 12:38:28 Step    219 at   35.558 [mm] t=  2.200e-10 [s] E=   51.108 [MeV] 
+ParallelTTracker {0}[3]> 12:38:28 Step    219 at   35.558 [mm] t=  2.200e-10 [s] E=   51.108 [MeV]
 ParallelTTracker {0}> --- CollimatorPhysics - Type is DEGRADER Name DEG1 Material Graphite Particles in material 28
 ParallelTTracker {0}> Coll/Deg statistics:  bunch to material 0 redifused 1 stopped 0
-ParallelTTracker {0}[3]> 12:38:28 Step    220 at   35.653 [mm] t=  2.210e-10 [s] E=   51.108 [MeV] 
+ParallelTTracker {0}[3]> 12:38:28 Step    220 at   35.653 [mm] t=  2.210e-10 [s] E=   51.108 [MeV]
 OPAL {0}[3]> * Wrote beam phase space.
-OPAL {0}> 
-OPAL {0}> * ************** B U N C H ********************************************************* 
+OPAL {0}>
+OPAL {0}> * ************** B U N C H *********************************************************
 OPAL {0}> * NP              =   999972
 OPAL {0}> * Qtot            =    3.94990e-02 [nC]       Qi    =  3.95001e-08 [nC]
 OPAL {0}> * Ekin            =    5.11080e+01 [MeV]      dEkin =  6.21572e-01 [MeV]
@@ -1129,39 +1129,39 @@ OPAL {0}> * hr              = (  5.94745e-04 ,  5.40795e-04 ,  1.11042e-04 ) [m]
 OPAL {0}> * dh              =    1.00000e-10 [%]
 OPAL {0}> * t               =    2.21000e-10 [s]        dT    =  1.00000e-12 [s]
 OPAL {0}> * spos            =    3.56530e-02 [m]
-OPAL {0}> * ********************************************************************************** 
-OPAL {0}> 
+OPAL {0}> * **********************************************************************************
+OPAL {0}>
 OPAL {0}[3]> * Wrote beam statistics.
 ParallelTTracker {0}> --- CollimatorPhysics - Type is DEGRADER Name DEG1 Material Graphite Particles in material 28
 ParallelTTracker {0}> Coll/Deg statistics:  bunch to material 0 redifused 0 stopped 0
-ParallelTTracker {0}[3]> 12:38:29 Step    221 at   35.748 [mm] t=  2.220e-10 [s] E=   51.108 [MeV] 
+ParallelTTracker {0}[3]> 12:38:29 Step    221 at   35.748 [mm] t=  2.220e-10 [s] E=   51.108 [MeV]
 ParallelTTracker {0}> --- CollimatorPhysics - Type is DEGRADER Name DEG1 Material Graphite Particles in material 28
 ParallelTTracker {0}> Coll/Deg statistics:  bunch to material 0 redifused 0 stopped 0
-ParallelTTracker {0}[3]> 12:38:30 Step    222 at   35.843 [mm] t=  2.230e-10 [s] E=   51.108 [MeV] 
+ParallelTTracker {0}[3]> 12:38:30 Step    222 at   35.843 [mm] t=  2.230e-10 [s] E=   51.108 [MeV]
 ParallelTTracker {0}> --- CollimatorPhysics - Type is DEGRADER Name DEG1 Material Graphite Particles in material 27
 ParallelTTracker {0}> Coll/Deg statistics:  bunch to material 0 redifused 1 stopped 0
-ParallelTTracker {0}[3]> 12:38:30 Step    223 at   35.938 [mm] t=  2.240e-10 [s] E=   51.108 [MeV] 
+ParallelTTracker {0}[3]> 12:38:30 Step    223 at   35.938 [mm] t=  2.240e-10 [s] E=   51.108 [MeV]
 ParallelTTracker {0}> --- CollimatorPhysics - Type is DEGRADER Name DEG1 Material Graphite Particles in material 27
 ParallelTTracker {0}> Coll/Deg statistics:  bunch to material 0 redifused 0 stopped 0
-ParallelTTracker {0}[3]> 12:38:30 Step    224 at   36.033 [mm] t=  2.250e-10 [s] E=   51.108 [MeV] 
+ParallelTTracker {0}[3]> 12:38:30 Step    224 at   36.033 [mm] t=  2.250e-10 [s] E=   51.108 [MeV]
 ParallelTTracker {0}> --- CollimatorPhysics - Type is DEGRADER Name DEG1 Material Graphite Particles in material 27
 ParallelTTracker {0}> Coll/Deg statistics:  bunch to material 0 redifused 0 stopped 0
-ParallelTTracker {0}[3]> 12:38:30 Step    225 at   36.128 [mm] t=  2.260e-10 [s] E=   51.108 [MeV] 
+ParallelTTracker {0}[3]> 12:38:30 Step    225 at   36.128 [mm] t=  2.260e-10 [s] E=   51.108 [MeV]
 ParallelTTracker {0}> --- CollimatorPhysics - Type is DEGRADER Name DEG1 Material Graphite Particles in material 26
 ParallelTTracker {0}> Coll/Deg statistics:  bunch to material 0 redifused 1 stopped 0
-ParallelTTracker {0}[3]> 12:38:31 Step    226 at   36.223 [mm] t=  2.270e-10 [s] E=   51.108 [MeV] 
+ParallelTTracker {0}[3]> 12:38:31 Step    226 at   36.223 [mm] t=  2.270e-10 [s] E=   51.108 [MeV]
 ParallelTTracker {0}> --- CollimatorPhysics - Type is DEGRADER Name DEG1 Material Graphite Particles in material 26
 ParallelTTracker {0}> Coll/Deg statistics:  bunch to material 0 redifused 0 stopped 0
-ParallelTTracker {0}[3]> 12:38:31 Step    227 at   36.318 [mm] t=  2.280e-10 [s] E=   51.108 [MeV] 
+ParallelTTracker {0}[3]> 12:38:31 Step    227 at   36.318 [mm] t=  2.280e-10 [s] E=   51.108 [MeV]
 ParallelTTracker {0}> --- CollimatorPhysics - Type is DEGRADER Name DEG1 Material Graphite Particles in material 26
 ParallelTTracker {0}> Coll/Deg statistics:  bunch to material 0 redifused 0 stopped 0
-ParallelTTracker {0}[3]> 12:38:31 Step    228 at   36.413 [mm] t=  2.290e-10 [s] E=   51.108 [MeV] 
+ParallelTTracker {0}[3]> 12:38:31 Step    228 at   36.413 [mm] t=  2.290e-10 [s] E=   51.108 [MeV]
 ParallelTTracker {0}> --- CollimatorPhysics - Type is DEGRADER Name DEG1 Material Graphite Particles in material 26
 ParallelTTracker {0}> Coll/Deg statistics:  bunch to material 0 redifused 0 stopped 0
-ParallelTTracker {0}[3]> 12:38:31 Step    229 at   36.508 [mm] t=  2.300e-10 [s] E=   51.108 [MeV] 
+ParallelTTracker {0}[3]> 12:38:31 Step    229 at   36.508 [mm] t=  2.300e-10 [s] E=   51.108 [MeV]
 OPAL {0}[3]> * Wrote beam phase space.
-OPAL {0}> 
-OPAL {0}> * ************** B U N C H ********************************************************* 
+OPAL {0}>
+OPAL {0}> * ************** B U N C H *********************************************************
 OPAL {0}> * NP              =   999974
 OPAL {0}> * Qtot            =    3.94991e-02 [nC]       Qi    =  3.95001e-08 [nC]
 OPAL {0}> * Ekin            =    5.11079e+01 [MeV]      dEkin =  6.31549e-01 [MeV]
@@ -1177,8 +1177,8 @@ OPAL {0}> * hr              = (  6.12266e-04 ,  5.46720e-04 ,  1.24447e-04 ) [m]
 OPAL {0}> * dh              =    1.00000e-10 [%]
 OPAL {0}> * t               =    2.30000e-10 [s]        dT    =  1.00000e-12 [s]
 OPAL {0}> * spos            =    3.65085e-02 [m]
-OPAL {0}> * ********************************************************************************** 
-OPAL {0}> 
+OPAL {0}> * **********************************************************************************
+OPAL {0}>
 OPAL {0}[3]> * Wrote beam statistics.
 ParallelTTracker {0}[2]> Dump phase space of last step
 Degrader::goOffline {0}>  done...
@@ -1191,101 +1191,101 @@ Timings{0}> -----------------------------------------------------------------
 Timings{0}>      Timing results for 4 nodes:
 Timings{0}> -----------------------------------------------------------------
 Timings{0}> mainTimer........... Wall tot =    103.448, CPU tot =      80.29
-Timings{0}> 
+Timings{0}>
 Timings{0}> Binaryrepart........ Wall max =   0.038533, CPU max =       0.04
 Timings{0}>                      Wall avg =  0.0384217, CPU avg =       0.04
 Timings{0}>                      Wall min =   0.038377, CPU min =       0.04
-Timings{0}> 
+Timings{0}>
 Timings{0}> Boundingbox......... Wall max =    6.71334, CPU max =       6.64
 Timings{0}>                      Wall avg =    6.22752, CPU avg =      6.175
 Timings{0}>                      Wall min =    5.08294, CPU min =       5.05
-Timings{0}> 
+Timings{0}>
 Timings{0}> CollPhysApply....... Wall max =    38.7721, CPU max =      38.78
 Timings{0}>                      Wall avg =    38.7599, CPU avg =    38.7475
 Timings{0}>                      Wall min =    38.7426, CPU min =      38.68
-Timings{0}> 
+Timings{0}>
 Timings{0}> CollPhysApplyLoop... Wall max =    37.2225, CPU max =      37.27
 Timings{0}>                      Wall avg =    36.1011, CPU avg =    36.1225
 Timings{0}>                      Wall min =    35.6178, CPU min =      35.59
-Timings{0}> 
+Timings{0}>
 Timings{0}> CreatDistr.......... Wall max =          0, CPU max =          0
 Timings{0}>                      Wall avg =          0, CPU avg =          0
 Timings{0}>                      Wall min =          0, CPU min =          0
-Timings{0}> 
+Timings{0}>
 Timings{0}> Fast inside test.... Wall max =          0, CPU max =          0
 Timings{0}>                      Wall avg =          0, CPU avg =          0
 Timings{0}>                      Wall min =          0, CPU min =          0
-Timings{0}> 
+Timings{0}>
 Timings{0}> Fieldeval........... Wall max =    3.49541, CPU max =       3.53
 Timings{0}>                      Wall avg =      3.257, CPU avg =      3.255
 Timings{0}>                      Wall min =    3.00072, CPU min =       3.06
-Timings{0}> 
+Timings{0}>
 Timings{0}> H5PartTimer......... Wall max =    24.4813, CPU max =       2.11
 Timings{0}>                      Wall avg =    24.4802, CPU avg =       1.89
 Timings{0}>                      Wall min =     24.479, CPU min =       1.37
-Timings{0}> 
+Timings{0}>
 Timings{0}> Histogram........... Wall max =          0, CPU max =          0
 Timings{0}>                      Wall avg =          0, CPU avg =          0
 Timings{0}>                      Wall min =          0, CPU min =          0
-Timings{0}> 
+Timings{0}>
 Timings{0}> Initialize geometry. Wall max =          0, CPU max =          0
 Timings{0}>                      Wall avg =          0, CPU avg =          0
 Timings{0}>                      Wall min =          0, CPU min =          0
-Timings{0}> 
+Timings{0}>
 Timings{0}> Inside test......... Wall max =          0, CPU max =          0
 Timings{0}>                      Wall avg =          0, CPU avg =          0
 Timings{0}>                      Wall min =          0, CPU min =          0
-Timings{0}> 
+Timings{0}>
 Timings{0}> LoadDistr........... Wall max =          0, CPU max =          0
 Timings{0}>                      Wall avg =          0, CPU avg =          0
 Timings{0}>                      Wall min =          0, CPU min =          0
-Timings{0}> 
+Timings{0}>
 Timings{0}> Particle Inside..... Wall max =          0, CPU max =          0
 Timings{0}>                      Wall avg =          0, CPU avg =          0
 Timings{0}>                      Wall min =          0, CPU min =          0
-Timings{0}> 
+Timings{0}>
 Timings{0}> Ray tracing......... Wall max =          0, CPU max =          0
 Timings{0}>                      Wall avg =          0, CPU avg =          0
 Timings{0}>                      Wall min =          0, CPU min =          0
-Timings{0}> 
+Timings{0}>
 Timings{0}> Secondary emission.. Wall max =          0, CPU max =          0
 Timings{0}>                      Wall avg =          0, CPU avg =          0
 Timings{0}>                      Wall min =          0, CPU min =          0
-Timings{0}> 
+Timings{0}>
 Timings{0}> SelfField total..... Wall max =   0.167619, CPU max =       0.18
 Timings{0}>                      Wall avg =   0.134254, CPU avg =      0.135
 Timings{0}>                      Wall min =   0.114664, CPU min =       0.07
-Timings{0}> 
+Timings{0}>
 Timings{0}> SF: Potential....... Wall max =          0, CPU max =          0
 Timings{0}>                      Wall avg =          0, CPU avg =          0
 Timings{0}>                      Wall min =          0, CPU min =          0
-Timings{0}> 
+Timings{0}>
 Timings{0}> Statistics.......... Wall max =    6.35851, CPU max =       6.31
 Timings{0}>                      Wall avg =    6.15226, CPU avg =      6.065
 Timings{0}>                      Wall min =    5.93626, CPU min =       5.75
-Timings{0}> 
+Timings{0}>
 Timings{0}> StatMarkerTimer..... Wall max =   0.287648, CPU max =       0.31
 Timings{0}>                      Wall avg =   0.285235, CPU avg =     0.2825
 Timings{0}>                      Wall min =   0.284416, CPU min =       0.23
-Timings{0}> 
+Timings{0}>
 Timings{0}> TIntegration1....... Wall max =    10.7871, CPU max =      10.89
 Timings{0}>                      Wall avg =     10.787, CPU avg =      10.77
 Timings{0}>                      Wall min =    10.7869, CPU min =      10.68
-Timings{0}> 
+Timings{0}>
 Timings{0}> TIntegration1Push... Wall max =    8.66589, CPU max =       8.73
 Timings{0}>                      Wall avg =    8.63463, CPU avg =       8.64
 Timings{0}>                      Wall min =    8.59318, CPU min =       8.58
-Timings{0}> 
+Timings{0}>
 Timings{0}> TIntegration2....... Wall max =    15.1104, CPU max =      15.15
 Timings{0}>                      Wall avg =     15.071, CPU avg =    15.0925
 Timings{0}>                      Wall min =    15.0284, CPU min =      14.96
-Timings{0}> 
+Timings{0}>
 Timings{0}> TIntegration2Push... Wall max =    8.85496, CPU max =       8.94
 Timings{0}>                      Wall avg =    8.81616, CPU avg =     8.8825
 Timings{0}>                      Wall min =    8.77607, CPU min =       8.85
-Timings{0}> 
+Timings{0}>
 Timings{0}> WakeField........... Wall max =          0, CPU max =          0
 Timings{0}>                      Wall avg =          0, CPU avg =          0
 Timings{0}>                      Wall min =          0, CPU min =          0
-Timings{0}> 
+Timings{0}>
 Timings{0}> -----------------------------------------------------------------
diff --git a/tests/Kollimator/Degrader/reference/Degrader-1.stat b/tests/Kollimator/Degrader/reference/Degrader-1.stat
index 7269efbcfb7212531dcaa54a2602dd0315854970..5b1d0eda0b3c9e59f1b576006c08e08b59c045b3 100644
--- a/tests/Kollimator/Degrader/reference/Degrader-1.stat
+++ b/tests/Kollimator/Degrader/reference/Degrader-1.stat
@@ -1,5 +1,5 @@
 SDDS1
-&description text="Statistics data Degrader-1.in 24/09/2015 12:36:53" 
+&description text="Statistics data Degrader-1.in 24/09/2015 12:36:53"
 , contents="stat parameters" &end
 &parameter name=processors, type=long, description="Number of Cores used" &end
 &parameter name=revision, type=string, description="git revision of opal" &end
@@ -55,27 +55,27 @@ SDDS1
 &data mode=ascii, no_row_counts=1 &end
 4
 OPAL 1.3.99.1 git rev. dad65505d9d1d4155b79ad70e6f1bfc994c8dd5c
-1.000000000000000e-12         	5.111592237710847e-03         	1000000         	3.950008689997970e-11         	7.200000000353884e+01         	4.868420649430107e-03         	4.872143023593891e-03         	4.927502284618087e-04         	0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	-4.681653880401086e-06         	-5.567764406704669e-06         	5.111592237710847e-03         	1.497913217034574e-02         	1.499028976336469e-02         	6.555572158842316e-03         	0.000000000000000e+00         	0.000000000000000e+00         	-0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	-1.868924807572966e-06         	0.000000000000000e+00         	-2.222661753386660e-06         	0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	0         	
-1.100000000000000e-11         	6.223077424194536e-03         	1000000         	3.950008689997970e-11         	7.200000000353884e+01         	4.868420649430107e-03         	4.872143023593891e-03         	4.927502284627065e-04         	0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	-4.681653880401086e-06         	-5.567764406704782e-06         	6.223077424194536e-03         	1.497913217034574e-02         	1.499028976336469e-02         	7.667057345326093e-03         	0.000000000000000e+00         	0.000000000000000e+00         	-0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	-1.868924807572966e-06         	0.000000000000000e+00         	-2.222661753386660e-06         	0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	0         	
-2.100000000000000e-11         	7.334562610678335e-03         	1000000         	3.950008689997970e-11         	7.200000000353884e+01         	4.868420649430107e-03         	4.872143023593891e-03         	4.927502284621080e-04         	0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	-4.681653880401086e-06         	-5.567764406704782e-06         	7.334562610678334e-03         	1.497913217034574e-02         	1.499028976336469e-02         	8.778542531809874e-03         	0.000000000000000e+00         	0.000000000000000e+00         	-0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	-1.868924807572966e-06         	0.000000000000000e+00         	-2.222661753386660e-06         	0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	0         	
-3.100000000000000e-11         	8.446047797162166e-03         	1000000         	3.950008689997970e-11         	7.200000000353884e+01         	4.868420649430107e-03         	4.872143023593891e-03         	4.927502284620864e-04         	0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	-4.681653880401086e-06         	-5.567764406704782e-06         	8.446047797162168e-03         	1.497913217034574e-02         	1.499028976336469e-02         	9.890027718293658e-03         	0.000000000000000e+00         	0.000000000000000e+00         	-0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	-1.868924807572966e-06         	0.000000000000000e+00         	-2.222661753386660e-06         	0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	0         	
-4.100000000000003e-11         	9.557532983645881e-03         	1000000         	3.950008689997970e-11         	7.200000000353884e+01         	4.868420649430106e-03         	4.872143023593891e-03         	4.927502284627641e-04         	0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	-4.681653880401086e-06         	-5.567764406704782e-06         	9.557532983645881e-03         	1.497913217034574e-02         	1.499028976336469e-02         	1.100151290477744e-02         	0.000000000000000e+00         	0.000000000000000e+00         	-0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	-1.868924807572966e-06         	0.000000000000000e+00         	-2.222661753386660e-06         	0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	0         	
-5.100000000000006e-11         	1.066901817012962e-02         	1000000         	3.950008689997970e-11         	7.200000000353884e+01         	4.868420649430106e-03         	4.872143023593891e-03         	4.927502284629804e-04         	0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	-4.681653880401086e-06         	-5.567764406704782e-06         	1.066901817012962e-02         	1.497913217034574e-02         	1.499028976336469e-02         	1.211299809126121e-02         	0.000000000000000e+00         	0.000000000000000e+00         	-0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	-1.868924807572966e-06         	0.000000000000000e+00         	-2.222661753386660e-06         	0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	0         	
-6.100000000000007e-11         	1.178050335661341e-02         	1000000         	3.950008689997970e-11         	7.200000000353884e+01         	4.868420649430107e-03         	4.872143023593891e-03         	4.927502284639465e-04         	0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	-4.681653880401086e-06         	-5.567764406704782e-06         	1.178050335661342e-02         	1.497913217034574e-02         	1.499028976336469e-02         	1.322448327774499e-02         	0.000000000000000e+00         	0.000000000000000e+00         	-0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	-1.868924807572966e-06         	0.000000000000000e+00         	-2.222661753386660e-06         	0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	0         	
-7.100000000000004e-11         	1.289198854309729e-02         	1000000         	3.950008689997970e-11         	7.200000000353884e+01         	4.868420649430107e-03         	4.872143023593891e-03         	4.927502284623891e-04         	0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	-4.681653880401086e-06         	-5.567764406704669e-06         	1.289198854309729e-02         	1.497913217034574e-02         	1.499028976336469e-02         	1.433596846422877e-02         	0.000000000000000e+00         	0.000000000000000e+00         	-0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	-1.868924807572966e-06         	0.000000000000000e+00         	-2.222661753386660e-06         	0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	0         	
-8.100000000000000e-11         	1.400347372958092e-02         	1000000         	3.950008689997970e-11         	7.200000000353884e+01         	4.868420649430106e-03         	4.872143023593891e-03         	4.927502284626488e-04         	0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	-4.681653880401086e-06         	-5.567764406704669e-06         	1.400347372958092e-02         	1.497913217034574e-02         	1.499028976336469e-02         	1.544745365071254e-02         	0.000000000000000e+00         	0.000000000000000e+00         	-0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	-1.868924807572966e-06         	0.000000000000000e+00         	-2.222661753386660e-06         	0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	0         	
-9.099999999999997e-11         	1.511495891606482e-02         	1000000         	3.950008689997970e-11         	7.200000000353884e+01         	4.868420649430106e-03         	4.872143023593891e-03         	4.927502284646098e-04         	0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	-4.681653880401086e-06         	-5.567764406704669e-06         	1.511495891606482e-02         	1.497913217034574e-02         	1.499028976336469e-02         	1.655893883719632e-02         	0.000000000000000e+00         	0.000000000000000e+00         	-0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	-1.868924807572966e-06         	0.000000000000000e+00         	-2.222661753386660e-06         	0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	0         	
-1.009999999999999e-10         	1.622644410254854e-02         	1000000         	3.950008689997970e-11         	7.200000000353884e+01         	4.868420649430107e-03         	4.872143023593891e-03         	4.927502284637157e-04         	0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	-4.681653880401086e-06         	-5.567764406704782e-06         	1.622644410254854e-02         	1.497913217034574e-02         	1.499028976336469e-02         	1.767042402368011e-02         	0.000000000000000e+00         	0.000000000000000e+00         	-0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	-1.868924807572966e-06         	0.000000000000000e+00         	-2.222661753386660e-06         	0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	0         	
-1.109999999999999e-10         	1.733792928903230e-02         	1000000         	3.950008689997970e-11         	7.200000000353884e+01         	4.868420649430106e-03         	4.872143023593891e-03         	4.927502284645809e-04         	0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	-4.681653880401086e-06         	-5.567764406704669e-06         	1.733792928903230e-02         	1.497913217034574e-02         	1.499028976336469e-02         	1.878190921016390e-02         	0.000000000000000e+00         	0.000000000000000e+00         	-0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	-1.868924807572966e-06         	0.000000000000000e+00         	-2.222661753386660e-06         	0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	0         	
-1.209999999999999e-10         	1.844941447551611e-02         	1000000         	3.950008689997970e-11         	7.200000000353884e+01         	4.868420649430107e-03         	4.872143023593891e-03         	4.927502284593899e-04         	0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	-4.681653880401086e-06         	-5.567764406704782e-06         	1.844941447551611e-02         	1.497913217034574e-02         	1.499028976336469e-02         	1.989339439664768e-02         	0.000000000000000e+00         	0.000000000000000e+00         	-0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	-1.868924807572966e-06         	0.000000000000000e+00         	-2.222661753386660e-06         	0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	0         	
-1.309999999999998e-10         	1.941780584792183e-02         	839891         	3.317576748660614e-11         	7.200000000306115e+01         	4.869452494376657e-03         	4.870080863004039e-03         	3.909906132807008e-04         	0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	-7.607728687033984e-06         	-5.191995999074283e-06         	1.941780584792183e-02         	1.497607561455540e-02         	1.499028976336469e-02         	1.999999892270974e-02         	0.000000000000000e+00         	0.000000000000000e+00         	-0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	-3.037019232035862e-06         	0.000000000000000e+00         	-2.072654316507927e-06         	0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	0         	
-1.409999999999998e-10         	1.982463087489001e-02         	107106         	4.230696307531995e-12         	7.200000000007996e+01         	4.870823735168309e-03         	4.867579588880033e-03         	1.895926134288195e-04         	0.000000000000000e+00         	0.000000000000000e+00         	4.555953932439722e-07         	0.000000000000000e+00         	0.000000000000000e+00         	8.637752118269553e-11         	-1.365275902406469e-05         	-3.773591525986880e-06         	1.982463087489001e-02         	1.487272406989349e-02         	1.493384243785322e-02         	1.999999919019552e-02         	0.000000000000000e+00         	0.000000000000000e+00         	4.528278624471229e-05         	0.000000000000000e+00         	0.000000000000000e+00         	-5.450206419342710e-06         	0.000000000000000e+00         	-1.506424651794112e-06         	0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	1.584861077832305e-04         	0         	
-1.509999999999998e-10         	3.020293155281732e-02         	2454         	9.693321325307009e-14         	5.122348914695328e+01         	4.956472242671688e-03         	4.816575914604397e-03         	4.215463150068369e-05         	6.826248490582596e-03         	7.024925604397689e-03         	1.642802453482960e-03         	3.382986370461748e-05         	3.383189685660921e-05         	6.807619451391868e-08         	1.443246651081983e-04         	1.051238760511410e-04         	3.020293155281732e-02         	1.397851011422493e-02         	1.429183253502998e-02         	3.028763820948039e-02         	1.584486916693556e-02         	1.573802305418739e-02         	1.834708373072699e-01         	0.000000000000000e+00         	0.000000000000000e+00         	4.848639340633806e-05         	9.950722549969653e-06         	3.528592757055124e-05         	-5.391748849287457e-05         	0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	4.895107823181550e-01         	0         	
-1.609999999999997e-10         	3.041868455837234e-02         	325636         	1.286265029783102e-11         	5.113334838953455e+01         	4.873419529321916e-03         	4.882273368489733e-03         	2.174107559890713e-04         	7.474755598893295e-03         	7.499403898751201e-03         	1.731782127806550e-03         	3.641855429849215e-05         	3.660709328071981e-05         	3.763533789721698e-07         	1.196506611297183e-05         	-1.554222565211750e-06         	3.041868455837235e-02         	1.510800700739082e-02         	1.516606417828000e-02         	3.124750794826335e-02         	2.230854217642294e-02         	1.961828986863846e-02         	2.866183814213220e-02         	0.000000000000000e+00         	0.000000000000000e+00         	3.979701455168738e-06         	9.444489934052951e-06         	-5.272321407357167e-07         	7.147740957617706e-06         	0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	5.156050017069520e-01         	0         	
-1.709999999999997e-10         	3.093539046241331e-02         	962988         	3.803810968365968e-11         	5.111043896759536e+01         	4.871069792481001e-03         	4.874815539192410e-03         	3.889933851879795e-04         	7.641839955004233e-03         	7.635370812050827e-03         	1.807070865008352e-03         	3.721246938863041e-05         	3.720944952350782e-05         	7.020366009408028e-07         	-4.113193110821973e-06         	-4.904214075198571e-06         	3.093539046241331e-02         	1.542844575664340e-02         	1.557888611133477e-02         	3.220841891929872e-02         	2.481895428278474e-02         	2.493693321454169e-02         	5.064343046654003e-02         	0.000000000000000e+00         	0.000000000000000e+00         	-1.385692783968422e-06         	4.989688053642326e-06         	-1.644661975081908e-06         	3.688725465175520e-06         	0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	5.379095028340021e-01         	0         	
-1.809999999999997e-10         	3.185094354145679e-02         	999930         	3.949732189389674e-11         	5.110828687832232e+01         	4.870970168449542e-03         	4.874750743550525e-03         	4.224964172374927e-04         	7.718227367605665e-03         	7.700101521761150e-03         	1.877384916633805e-03         	3.757852584822735e-05         	3.751961458300269e-05         	7.913379855022614e-07         	-4.288515893469802e-06         	-5.243199301984600e-06         	3.185094354145679e-02         	1.590666361225554e-02         	1.714916878514068e-02         	3.317108605075062e-02         	2.982912451310766e-02         	2.961225792512086e-02         	6.826655982658801e-02         	0.000000000000000e+00         	0.000000000000000e+00         	-1.446253822253402e-06         	5.870513434236887e-06         	-1.762525577763600e-06         	4.376632356485783e-06         	0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	5.588289747652002e-01         	0         	
-1.909999999999996e-10         	3.280146100267775e-02         	999949         	3.949807239554783e-11         	5.110820576105885e+01         	4.871728747630793e-03         	4.875501482013335e-03         	4.229664665506866e-04         	7.746430698209431e-03         	7.725198741924909e-03         	1.925989822603065e-03         	3.771596841358244e-05         	3.764215660041368e-05         	8.118365322189566e-07         	-4.268089053259737e-06         	-5.214164039123373e-06         	3.280146100267775e-02         	1.638488146786955e-02         	1.747009864580812e-02         	3.413375318220259e-02         	3.455744048543640e-02         	3.422178124249192e-02         	8.273040520039902e-02         	0.000000000000000e+00         	0.000000000000000e+00         	-1.437283926305482e-06         	5.523200795012970e-06         	-1.752394308003896e-06         	4.557889929603111e-06         	0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	5.732964614251223e-01         	0         	
-2.009999999999996e-10         	3.375198918962945e-02         	999957         	3.949838839624302e-11         	5.110813675873874e+01         	4.872536634219184e-03         	4.876312872258974e-03         	4.235156314648329e-04         	7.756942261389267e-03         	7.741657065713579e-03         	1.974709329251728e-03         	3.776711800058772e-05         	3.772230751158408e-05         	8.323909360615566e-07         	-4.234266273663596e-06         	-5.206963748270960e-06         	3.375198918962945e-02         	1.686309932348214e-02         	1.779102850647556e-02         	3.509642031365449e-02         	3.907622363111093e-02         	3.880549099171989e-02         	9.682273755338482e-02         	0.000000000000000e+00         	0.000000000000000e+00         	-1.423557806582691e-06         	5.486905047771423e-06         	-1.746393804756563e-06         	4.393806809214385e-06         	0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	5.877981035920842e-01         	0         	
-2.109999999999996e-10         	3.470249672497108e-02         	999967         	3.949878339710981e-11         	5.110803637005880e+01         	4.873505329127087e-03         	4.877264623457779e-03         	4.242749521548516e-04         	7.775059020078020e-03         	7.761729100299482e-03         	2.049544450919070e-03         	3.785542495487379e-05         	3.782021786336607e-05         	8.639592855598002e-07         	-4.235171099039965e-06         	-5.116127375193411e-06         	3.470249672497108e-02         	1.734131717909473e-02         	1.811195836714300e-02         	3.605908744510647e-02         	4.380156537218768e-02         	4.347294576647796e-02         	1.134186450162775e-01         	0.000000000000000e+00         	0.000000000000000e+00         	-1.417549045904531e-06         	5.268845313996851e-06         	-1.725101327949558e-06         	4.570419658468024e-06         	0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	6.100732048619008e-01         	0         	
-2.209999999999995e-10         	3.565301720895587e-02         	999972         	3.949898089754651e-11         	5.110797850424476e+01         	4.874590627816890e-03         	4.878285604767481e-03         	4.250845371740724e-04         	7.784498054845327e-03         	7.769962384291275e-03         	2.088175403724481e-03         	3.790151850836323e-05         	3.786030118298352e-05         	8.802725460142234e-07         	-4.179313835136367e-06         	-5.059079462662418e-06         	3.565301720895587e-02         	1.847788042864819e-02         	1.843288822781045e-02         	3.702175457655840e-02         	4.853632338731736e-02         	4.805693435032890e-02         	1.286691288444957e-01         	0.000000000000000e+00         	0.000000000000000e+00         	-1.399588552604808e-06         	5.313848448673142e-06         	-1.709868531617869e-06         	4.633347316438789e-06         	0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	6.215718788078700e-01         	0         	
-2.299999999999995e-10         	3.650849426550903e-02         	999974         	3.949905989771857e-11         	5.110794622449372e+01         	4.875594160776566e-03         	4.879297595437868e-03         	4.258504860273446e-04         	7.784491472941141e-03         	7.779109616693153e-03         	2.121695391266010e-03         	3.790145529776526e-05         	3.790484062779962e-05         	8.944093200425694e-07         	-4.140985312649076e-06         	-5.001648918063761e-06         	3.650849426550902e-02         	1.904692088164371e-02         	1.873777159544452e-02         	3.793628835143766e-02         	5.261233935929627e-02         	5.220107139495963e-02         	1.416907798282542e-01         	0.000000000000000e+00         	0.000000000000000e+00         	-1.386028652498502e-06         	5.313983932384949e-06         	-1.696632084667518e-06         	4.670021204142811e-06         	0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	6.315493438759794e-01         	0         	
+1.000000000000000e-12         	5.111592237710847e-03         	1000000         	3.950008689997970e-11         	7.200000000353884e+01         	4.868420649430107e-03         	4.872143023593891e-03         	4.927502284618087e-04         	0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	-4.681653880401086e-06         	-5.567764406704669e-06         	5.111592237710847e-03         	1.497913217034574e-02         	1.499028976336469e-02         	6.555572158842316e-03         	0.000000000000000e+00         	0.000000000000000e+00         	-0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	-1.868924807572966e-06         	0.000000000000000e+00         	-2.222661753386660e-06         	0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	0
+1.100000000000000e-11         	6.223077424194536e-03         	1000000         	3.950008689997970e-11         	7.200000000353884e+01         	4.868420649430107e-03         	4.872143023593891e-03         	4.927502284627065e-04         	0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	-4.681653880401086e-06         	-5.567764406704782e-06         	6.223077424194536e-03         	1.497913217034574e-02         	1.499028976336469e-02         	7.667057345326093e-03         	0.000000000000000e+00         	0.000000000000000e+00         	-0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	-1.868924807572966e-06         	0.000000000000000e+00         	-2.222661753386660e-06         	0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	0
+2.100000000000000e-11         	7.334562610678335e-03         	1000000         	3.950008689997970e-11         	7.200000000353884e+01         	4.868420649430107e-03         	4.872143023593891e-03         	4.927502284621080e-04         	0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	-4.681653880401086e-06         	-5.567764406704782e-06         	7.334562610678334e-03         	1.497913217034574e-02         	1.499028976336469e-02         	8.778542531809874e-03         	0.000000000000000e+00         	0.000000000000000e+00         	-0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	-1.868924807572966e-06         	0.000000000000000e+00         	-2.222661753386660e-06         	0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	0
+3.100000000000000e-11         	8.446047797162166e-03         	1000000         	3.950008689997970e-11         	7.200000000353884e+01         	4.868420649430107e-03         	4.872143023593891e-03         	4.927502284620864e-04         	0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	-4.681653880401086e-06         	-5.567764406704782e-06         	8.446047797162168e-03         	1.497913217034574e-02         	1.499028976336469e-02         	9.890027718293658e-03         	0.000000000000000e+00         	0.000000000000000e+00         	-0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	-1.868924807572966e-06         	0.000000000000000e+00         	-2.222661753386660e-06         	0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	0
+4.100000000000003e-11         	9.557532983645881e-03         	1000000         	3.950008689997970e-11         	7.200000000353884e+01         	4.868420649430106e-03         	4.872143023593891e-03         	4.927502284627641e-04         	0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	-4.681653880401086e-06         	-5.567764406704782e-06         	9.557532983645881e-03         	1.497913217034574e-02         	1.499028976336469e-02         	1.100151290477744e-02         	0.000000000000000e+00         	0.000000000000000e+00         	-0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	-1.868924807572966e-06         	0.000000000000000e+00         	-2.222661753386660e-06         	0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	0
+5.100000000000006e-11         	1.066901817012962e-02         	1000000         	3.950008689997970e-11         	7.200000000353884e+01         	4.868420649430106e-03         	4.872143023593891e-03         	4.927502284629804e-04         	0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	-4.681653880401086e-06         	-5.567764406704782e-06         	1.066901817012962e-02         	1.497913217034574e-02         	1.499028976336469e-02         	1.211299809126121e-02         	0.000000000000000e+00         	0.000000000000000e+00         	-0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	-1.868924807572966e-06         	0.000000000000000e+00         	-2.222661753386660e-06         	0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	0
+6.100000000000007e-11         	1.178050335661341e-02         	1000000         	3.950008689997970e-11         	7.200000000353884e+01         	4.868420649430107e-03         	4.872143023593891e-03         	4.927502284639465e-04         	0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	-4.681653880401086e-06         	-5.567764406704782e-06         	1.178050335661342e-02         	1.497913217034574e-02         	1.499028976336469e-02         	1.322448327774499e-02         	0.000000000000000e+00         	0.000000000000000e+00         	-0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	-1.868924807572966e-06         	0.000000000000000e+00         	-2.222661753386660e-06         	0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	0
+7.100000000000004e-11         	1.289198854309729e-02         	1000000         	3.950008689997970e-11         	7.200000000353884e+01         	4.868420649430107e-03         	4.872143023593891e-03         	4.927502284623891e-04         	0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	-4.681653880401086e-06         	-5.567764406704669e-06         	1.289198854309729e-02         	1.497913217034574e-02         	1.499028976336469e-02         	1.433596846422877e-02         	0.000000000000000e+00         	0.000000000000000e+00         	-0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	-1.868924807572966e-06         	0.000000000000000e+00         	-2.222661753386660e-06         	0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	0
+8.100000000000000e-11         	1.400347372958092e-02         	1000000         	3.950008689997970e-11         	7.200000000353884e+01         	4.868420649430106e-03         	4.872143023593891e-03         	4.927502284626488e-04         	0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	-4.681653880401086e-06         	-5.567764406704669e-06         	1.400347372958092e-02         	1.497913217034574e-02         	1.499028976336469e-02         	1.544745365071254e-02         	0.000000000000000e+00         	0.000000000000000e+00         	-0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	-1.868924807572966e-06         	0.000000000000000e+00         	-2.222661753386660e-06         	0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	0
+9.099999999999997e-11         	1.511495891606482e-02         	1000000         	3.950008689997970e-11         	7.200000000353884e+01         	4.868420649430106e-03         	4.872143023593891e-03         	4.927502284646098e-04         	0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	-4.681653880401086e-06         	-5.567764406704669e-06         	1.511495891606482e-02         	1.497913217034574e-02         	1.499028976336469e-02         	1.655893883719632e-02         	0.000000000000000e+00         	0.000000000000000e+00         	-0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	-1.868924807572966e-06         	0.000000000000000e+00         	-2.222661753386660e-06         	0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	0
+1.009999999999999e-10         	1.622644410254854e-02         	1000000         	3.950008689997970e-11         	7.200000000353884e+01         	4.868420649430107e-03         	4.872143023593891e-03         	4.927502284637157e-04         	0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	-4.681653880401086e-06         	-5.567764406704782e-06         	1.622644410254854e-02         	1.497913217034574e-02         	1.499028976336469e-02         	1.767042402368011e-02         	0.000000000000000e+00         	0.000000000000000e+00         	-0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	-1.868924807572966e-06         	0.000000000000000e+00         	-2.222661753386660e-06         	0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	0
+1.109999999999999e-10         	1.733792928903230e-02         	1000000         	3.950008689997970e-11         	7.200000000353884e+01         	4.868420649430106e-03         	4.872143023593891e-03         	4.927502284645809e-04         	0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	-4.681653880401086e-06         	-5.567764406704669e-06         	1.733792928903230e-02         	1.497913217034574e-02         	1.499028976336469e-02         	1.878190921016390e-02         	0.000000000000000e+00         	0.000000000000000e+00         	-0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	-1.868924807572966e-06         	0.000000000000000e+00         	-2.222661753386660e-06         	0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	0
+1.209999999999999e-10         	1.844941447551611e-02         	1000000         	3.950008689997970e-11         	7.200000000353884e+01         	4.868420649430107e-03         	4.872143023593891e-03         	4.927502284593899e-04         	0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	-4.681653880401086e-06         	-5.567764406704782e-06         	1.844941447551611e-02         	1.497913217034574e-02         	1.499028976336469e-02         	1.989339439664768e-02         	0.000000000000000e+00         	0.000000000000000e+00         	-0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	-1.868924807572966e-06         	0.000000000000000e+00         	-2.222661753386660e-06         	0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	0
+1.309999999999998e-10         	1.941780584792183e-02         	839891         	3.317576748660614e-11         	7.200000000306115e+01         	4.869452494376657e-03         	4.870080863004039e-03         	3.909906132807008e-04         	0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	-7.607728687033984e-06         	-5.191995999074283e-06         	1.941780584792183e-02         	1.497607561455540e-02         	1.499028976336469e-02         	1.999999892270974e-02         	0.000000000000000e+00         	0.000000000000000e+00         	-0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	-3.037019232035862e-06         	0.000000000000000e+00         	-2.072654316507927e-06         	0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	0
+1.409999999999998e-10         	1.982463087489001e-02         	107106         	4.230696307531995e-12         	7.200000000007996e+01         	4.870823735168309e-03         	4.867579588880033e-03         	1.895926134288195e-04         	0.000000000000000e+00         	0.000000000000000e+00         	4.555953932439722e-07         	0.000000000000000e+00         	0.000000000000000e+00         	8.637752118269553e-11         	-1.365275902406469e-05         	-3.773591525986880e-06         	1.982463087489001e-02         	1.487272406989349e-02         	1.493384243785322e-02         	1.999999919019552e-02         	0.000000000000000e+00         	0.000000000000000e+00         	4.528278624471229e-05         	0.000000000000000e+00         	0.000000000000000e+00         	-5.450206419342710e-06         	0.000000000000000e+00         	-1.506424651794112e-06         	0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	1.584861077832305e-04         	0
+1.509999999999998e-10         	3.020293155281732e-02         	2454         	9.693321325307009e-14         	5.122348914695328e+01         	4.956472242671688e-03         	4.816575914604397e-03         	4.215463150068369e-05         	6.826248490582596e-03         	7.024925604397689e-03         	1.642802453482960e-03         	3.382986370461748e-05         	3.383189685660921e-05         	6.807619451391868e-08         	1.443246651081983e-04         	1.051238760511410e-04         	3.020293155281732e-02         	1.397851011422493e-02         	1.429183253502998e-02         	3.028763820948039e-02         	1.584486916693556e-02         	1.573802305418739e-02         	1.834708373072699e-01         	0.000000000000000e+00         	0.000000000000000e+00         	4.848639340633806e-05         	9.950722549969653e-06         	3.528592757055124e-05         	-5.391748849287457e-05         	0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	4.895107823181550e-01         	0
+1.609999999999997e-10         	3.041868455837234e-02         	325636         	1.286265029783102e-11         	5.113334838953455e+01         	4.873419529321916e-03         	4.882273368489733e-03         	2.174107559890713e-04         	7.474755598893295e-03         	7.499403898751201e-03         	1.731782127806550e-03         	3.641855429849215e-05         	3.660709328071981e-05         	3.763533789721698e-07         	1.196506611297183e-05         	-1.554222565211750e-06         	3.041868455837235e-02         	1.510800700739082e-02         	1.516606417828000e-02         	3.124750794826335e-02         	2.230854217642294e-02         	1.961828986863846e-02         	2.866183814213220e-02         	0.000000000000000e+00         	0.000000000000000e+00         	3.979701455168738e-06         	9.444489934052951e-06         	-5.272321407357167e-07         	7.147740957617706e-06         	0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	5.156050017069520e-01         	0
+1.709999999999997e-10         	3.093539046241331e-02         	962988         	3.803810968365968e-11         	5.111043896759536e+01         	4.871069792481001e-03         	4.874815539192410e-03         	3.889933851879795e-04         	7.641839955004233e-03         	7.635370812050827e-03         	1.807070865008352e-03         	3.721246938863041e-05         	3.720944952350782e-05         	7.020366009408028e-07         	-4.113193110821973e-06         	-4.904214075198571e-06         	3.093539046241331e-02         	1.542844575664340e-02         	1.557888611133477e-02         	3.220841891929872e-02         	2.481895428278474e-02         	2.493693321454169e-02         	5.064343046654003e-02         	0.000000000000000e+00         	0.000000000000000e+00         	-1.385692783968422e-06         	4.989688053642326e-06         	-1.644661975081908e-06         	3.688725465175520e-06         	0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	5.379095028340021e-01         	0
+1.809999999999997e-10         	3.185094354145679e-02         	999930         	3.949732189389674e-11         	5.110828687832232e+01         	4.870970168449542e-03         	4.874750743550525e-03         	4.224964172374927e-04         	7.718227367605665e-03         	7.700101521761150e-03         	1.877384916633805e-03         	3.757852584822735e-05         	3.751961458300269e-05         	7.913379855022614e-07         	-4.288515893469802e-06         	-5.243199301984600e-06         	3.185094354145679e-02         	1.590666361225554e-02         	1.714916878514068e-02         	3.317108605075062e-02         	2.982912451310766e-02         	2.961225792512086e-02         	6.826655982658801e-02         	0.000000000000000e+00         	0.000000000000000e+00         	-1.446253822253402e-06         	5.870513434236887e-06         	-1.762525577763600e-06         	4.376632356485783e-06         	0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	5.588289747652002e-01         	0
+1.909999999999996e-10         	3.280146100267775e-02         	999949         	3.949807239554783e-11         	5.110820576105885e+01         	4.871728747630793e-03         	4.875501482013335e-03         	4.229664665506866e-04         	7.746430698209431e-03         	7.725198741924909e-03         	1.925989822603065e-03         	3.771596841358244e-05         	3.764215660041368e-05         	8.118365322189566e-07         	-4.268089053259737e-06         	-5.214164039123373e-06         	3.280146100267775e-02         	1.638488146786955e-02         	1.747009864580812e-02         	3.413375318220259e-02         	3.455744048543640e-02         	3.422178124249192e-02         	8.273040520039902e-02         	0.000000000000000e+00         	0.000000000000000e+00         	-1.437283926305482e-06         	5.523200795012970e-06         	-1.752394308003896e-06         	4.557889929603111e-06         	0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	5.732964614251223e-01         	0
+2.009999999999996e-10         	3.375198918962945e-02         	999957         	3.949838839624302e-11         	5.110813675873874e+01         	4.872536634219184e-03         	4.876312872258974e-03         	4.235156314648329e-04         	7.756942261389267e-03         	7.741657065713579e-03         	1.974709329251728e-03         	3.776711800058772e-05         	3.772230751158408e-05         	8.323909360615566e-07         	-4.234266273663596e-06         	-5.206963748270960e-06         	3.375198918962945e-02         	1.686309932348214e-02         	1.779102850647556e-02         	3.509642031365449e-02         	3.907622363111093e-02         	3.880549099171989e-02         	9.682273755338482e-02         	0.000000000000000e+00         	0.000000000000000e+00         	-1.423557806582691e-06         	5.486905047771423e-06         	-1.746393804756563e-06         	4.393806809214385e-06         	0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	5.877981035920842e-01         	0
+2.109999999999996e-10         	3.470249672497108e-02         	999967         	3.949878339710981e-11         	5.110803637005880e+01         	4.873505329127087e-03         	4.877264623457779e-03         	4.242749521548516e-04         	7.775059020078020e-03         	7.761729100299482e-03         	2.049544450919070e-03         	3.785542495487379e-05         	3.782021786336607e-05         	8.639592855598002e-07         	-4.235171099039965e-06         	-5.116127375193411e-06         	3.470249672497108e-02         	1.734131717909473e-02         	1.811195836714300e-02         	3.605908744510647e-02         	4.380156537218768e-02         	4.347294576647796e-02         	1.134186450162775e-01         	0.000000000000000e+00         	0.000000000000000e+00         	-1.417549045904531e-06         	5.268845313996851e-06         	-1.725101327949558e-06         	4.570419658468024e-06         	0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	6.100732048619008e-01         	0
+2.209999999999995e-10         	3.565301720895587e-02         	999972         	3.949898089754651e-11         	5.110797850424476e+01         	4.874590627816890e-03         	4.878285604767481e-03         	4.250845371740724e-04         	7.784498054845327e-03         	7.769962384291275e-03         	2.088175403724481e-03         	3.790151850836323e-05         	3.786030118298352e-05         	8.802725460142234e-07         	-4.179313835136367e-06         	-5.059079462662418e-06         	3.565301720895587e-02         	1.847788042864819e-02         	1.843288822781045e-02         	3.702175457655840e-02         	4.853632338731736e-02         	4.805693435032890e-02         	1.286691288444957e-01         	0.000000000000000e+00         	0.000000000000000e+00         	-1.399588552604808e-06         	5.313848448673142e-06         	-1.709868531617869e-06         	4.633347316438789e-06         	0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	6.215718788078700e-01         	0
+2.299999999999995e-10         	3.650849426550903e-02         	999974         	3.949905989771857e-11         	5.110794622449372e+01         	4.875594160776566e-03         	4.879297595437868e-03         	4.258504860273446e-04         	7.784491472941141e-03         	7.779109616693153e-03         	2.121695391266010e-03         	3.790145529776526e-05         	3.790484062779962e-05         	8.944093200425694e-07         	-4.140985312649076e-06         	-5.001648918063761e-06         	3.650849426550902e-02         	1.904692088164371e-02         	1.873777159544452e-02         	3.793628835143766e-02         	5.261233935929627e-02         	5.220107139495963e-02         	1.416907798282542e-01         	0.000000000000000e+00         	0.000000000000000e+00         	-1.386028652498502e-06         	5.313983932384949e-06         	-1.696632084667518e-06         	4.670021204142811e-06         	0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	0.000000000000000e+00         	6.315493438759794e-01         	0
diff --git a/tests/Kollimator/collimator.in b/tests/Kollimator/collimator.in
index 9424933e5b08707d460a3e5962ee61050de63060..9476d7d177e036a422ad203e0038dc8dd5ed86e3 100644
--- a/tests/Kollimator/collimator.in
+++ b/tests/Kollimator/collimator.in
@@ -1,60 +1 @@
-OPTION, ECHO=FALSE;
-OPTION, PSDUMPFREQ=1;
-
-TITLE,STRING="Collimator simulation";
-
-Edes   = 0.13;
-gamma  = (Edes+PMASS)/PMASS;
-beta   = sqrt(1-(1/gamma^2));
-gambet = gamma*beta;
-P0     = gamma*beta*PMASS;
-brho   = (PMASS*1.0e9*gambet) / CLIGHT;
-rf     = 50.6328e6;  //need to be confirmed
-
-VALUE,{gamma,brho,Edes,beta,gambet};
-
-
-KX1IPHYS: SURFACEPHYSICS, TYPE="COLLIMATOR", MATERIAL="Graphite";
-
-ECOLL1: ECOLLIMATOR, L=0.04, ELEMEDGE=0.01, XSIZE=0.003, YSIZE=0.003, OUTFN="ECOLL1.h5" , SURFACEPHYSICS=KX1IPHYS, DX=0, DY=0, DZ=0;
-
-//ECOLL2: ECOLLIMATOR, L=0.02, ELEMEDGE=0.05, XSIZE=0.003, YSIZE=0.003, OUTFN="ECOLL2.h5", SURFACEPHYSICS=KX1IPHYS, DX=0, DY=0, DZ=0;
-
-DEGPHYS_Wedge1 :  SURFACEPHYSICS, TYPE="DEGRADER", MATERIAL="GraphiteR6710";
-Wedge1: DEGRADER, L=0.0148363, ZSIZE= 0.0148363, OUTFN="Wedge1.h5", SURFACEPHYSICS=DEGPHYS_Wedge1 , ELEMEDGE=0.01;
-Deg_D1: DRIFT, L=0.02, ELEMEDGE=0.3;
-
-
-
-
-//M0ecoll: Monitor, L=0.001, ELEMEDGE=0.01, OUTFN="M0-ecoll.h5";
-//M0ecoll: Monitor, L=0.001, ELEMEDGE=0.008, OUTFN="M0-ecoll.h5";
-//M1: Monitor, L=0.001, ELEMEDGE=0.07, OUTFN="M1-ecoll.h5";
-
-//COLTEST: LINE=(M0ecoll,ECOLL,M1ecoll);
-//COLTEST: LINE=(ECOLL1,ECOLL2);
-COLTEST: LINE=(ECOLL1,M1);
-
-//COLTEST: LINE=(Wedge1,Deg_D1);
-
-
-D1: DISTRIBUTION, DISTRIBUTION=GAUSS,
-SIGMAX=  5.0e-03,   SIGMAPX=0.0,  CORRX=0.0,
-SIGMAY=  5.0e-03,   SIGMAPY=0.0,  CORRY=0.0,
-T     =  0.005,     SIGMAT= 0.0005, 
-PT    =  Edes*1E9, SIGMAPT=0.0, CORRT=0.0, R61=0.0;
-
-FS1:FIELDSOLVER, FSTYPE=NONE, MX=64, MY=64, MT=64, 
-                 PARFFTX=true, PARFFTY=true, PARFFTT=false,
-                 BCFFTX=open, BCFFTY=open, BCFFTT=open, 
-                 BBOXINCR=1, GREENSF=STANDARD;
-
-BEAM1: BEAM, PARTICLE=PROTON, PC=P0, NPART=100000, BCURRENT=2.0e-03, BFREQ=rf, CHARGE=1;
-
-SELECT, LINE=COLTEST;
-
-TRACK, LINE=COLTEST, BEAM=BEAM1, MAXSTEPS=300,  DT=1.0e-12;
- RUN, METHOD = "PARALLEL-T", BEAM=BEAM1, FIELDSOLVER=FS1, DISTRIBUTION=D1;
-ENDTRACK;
-
-STOP;
+collimator.in
\ No newline at end of file
diff --git a/tests/PROSCAN-G3-LA1-130/PROSCAN-G3-LA1-130.in b/tests/PROSCAN-G3-LA1-130/PROSCAN-G3-LA1-130.in
index 1f07b769152f85d76911e6e0080ece5aeab80eb0..1975c74c1e919a60f5fa4f6600180097d1bef7b3 100644
--- a/tests/PROSCAN-G3-LA1-130/PROSCAN-G3-LA1-130.in
+++ b/tests/PROSCAN-G3-LA1-130/PROSCAN-G3-LA1-130.in
@@ -1,118 +1 @@
-OPTION, ECHO=FALSE;
-OPTION, PSDUMPFREQ=50;
-OPTION, TELL=TRUE;
-
-// OPAL Input forLA1line
-TFast = 5e-11;
-TSlow = 5e-12;
-TDeg = 1e-12;
-Edes = 0.249489;
-gamma = (Edes+PMASS)/PMASS;
-beta = sqrt(1-(1/gamma^2));
-gambet = gamma*beta;
-P0 = gamma*beta*PMASS;
-brho = (PMASS*1.0e9*gambet) / CLIGHT;
-VALUE,{gamma,brho,Edes,beta,gambet};
-
-rf = 50.6328e6;
-NProt = 500000;
-
-DISTRIB1: DISTRIBUTION,
-SIGMAX = 0.001861, SIGMAPX = 0.001485*gambet,
-SIGMAY = 0.001974, SIGMAPY = 0.001291*gambet,
-SIGMAZ = 1e-05, SIGMAPZ = 0.0007*gambet,
-CORRX = 0.503, CORRY = 0.858, CORRZ = 0,
-R51 = 0, R52 = 0, R61 = 0, R62 = 0,
-CUTOFFX = 5, CUTOFFPX = 5, CUTOFFY = 5,
-CUTOFFPY = 5, CUTOFFLONG = 5, CUTOFFPZ = 5,
-OFFSETX = 0.00094113, OFFSETY =-0.002157, OFFSETZ = 0,
-DISTRIBUTION = GAUSS, INPUTMOUNITS = NONE;
-
-UPAC: DRIFT, L=0, ELEMEDGE=0;
-D1: DRIFT, L=0.3262, ELEMEDGE=0;
-D2: DRIFT, L=0.0823, ELEMEDGE=0.3262;
-MMAP1X: MONITOR, OUTFN="MMAP1X.h5", ELEMEDGE=0.4085;
-MMAP2Y: MONITOR, OUTFN="MMAP2Y.h5", ELEMEDGE=0.4085;
-D3: DRIFT, L=0.09, ELEMEDGE=0.4085;
-MMAP3X: MONITOR, OUTFN="MMAP3X.h5", ELEMEDGE=0.4985;
-MMAP4Y: MONITOR, OUTFN="MMAP4Y.h5", ELEMEDGE=0.4985;
-D4: DRIFT, L=0.3075, ELEMEDGE=0.4985;
-QMA1: QUADRUPOLE, K1=-16, L=0.368, ELEMEDGE=0.806;
-QMA1_r0: ECOLLIMATOR, XSIZE=0.0465, YSIZE=0.0465, L=0.368, ELEMEDGE=0.806;
-D5: DRIFT, L=0.294, ELEMEDGE=1.174;
-QMA2: QUADRUPOLE, K1=13.092, L=0.368, ELEMEDGE=1.468;
-QMA2_r0: ECOLLIMATOR, XSIZE=0.0465, YSIZE=0.0465, L=0.368, ELEMEDGE=1.468;
-D6: DRIFT, L=0.324, ELEMEDGE=1.836;
-D7: DRIFT, L=0.324, ELEMEDGE=2.16;
-QMA3: QUADRUPOLE, K1=-11.7681, L=0.368, ELEMEDGE=2.484;
-QMA3_r0: ECOLLIMATOR, XSIZE=0.0465, YSIZE=0.0465, L=0.368, ELEMEDGE=2.484;
-D8: DRIFT, L=0.274, ELEMEDGE=2.852;
-D9: DRIFT, L=0.164, ELEMEDGE=3.126;
-D10: DRIFT, L=0.1875, ELEMEDGE=3.29;
-D11: DRIFT, L=0.0815, ELEMEDGE=3.4775;
-MMAP5X: MONITOR, OUTFN="MMAP5X.h5", ELEMEDGE=3.559;
-MMAP6Y: MONITOR, OUTFN="MMAP6Y.h5", ELEMEDGE=3.559;
-D12: DRIFT, L=0.086, ELEMEDGE=3.559;
-MMAP7X: MONITOR, OUTFN="MMAP7X.h5", ELEMEDGE=3.645;
-MMAP8Y: MONITOR, OUTFN="MMAP8Y.h5", ELEMEDGE=3.645;
-Titan1: DRIFT, L=0.000228, ELEMEDGE=3.645;
-Air1: DRIFT, L=0.069, ELEMEDGE=3.64523;
-D13: DRIFT, L=0.015772, ELEMEDGE=3.71423;
-BMA1I: ECOLLIMATOR, XSIZE=0.005, YSIZE=0.005, L=0.002, ELEMEDGE=3.73;
-D14: DRIFT, L=0.246, ELEMEDGE=3.732;
-BMA1O: ECOLLIMATOR, XSIZE=0.00625, YSIZE=0.00625, L=0.002, ELEMEDGE=3.978;
-D15: DRIFT, L=0.02, ELEMEDGE=3.98;
-
-DEGPHYS_Wedge1 :  SURFACEPHYSICS, TYPE="DEGRADER", MATERIAL="GraphiteR6710";
-
-Wedge1: DEGRADER, L=0.0148363, ZSIZE= 0.0148363, OUTFN="Wedge1.h5", SURFACEPHYSICS=DEGPHYS_Wedge1 , ELEMEDGE=4;
-Deg_D1: DRIFT, L=0.0114374, ELEMEDGE=4.01484;
-
-Wedge2: DEGRADER, L=0.0296726, ZSIZE= 0.0296726, OUTFN="Wedge2.h5", SURFACEPHYSICS=DEGPHYS_Wedge1 , ELEMEDGE=4.02627;
-Deg_D2: DRIFT, L=0.0114374, ELEMEDGE=4.05595;
-
-Wedge3: DEGRADER, L=0.0296726, ZSIZE= 0.0296726, OUTFN="Wedge3.h5", SURFACEPHYSICS=DEGPHYS_Wedge1 , ELEMEDGE=4.06738;
-Deg_D3: DRIFT, L=0.0114374, ELEMEDGE=4.09706;
-
-Wedge4: DEGRADER, L=0.0296726, ZSIZE= 0.0296726, OUTFN="Wedge4.h5", SURFACEPHYSICS=DEGPHYS_Wedge1 , ELEMEDGE=4.10849;
-Deg_D4: DRIFT, L=0.0114374, ELEMEDGE=4.13817;
-
-Wedge5: DEGRADER, L=0.0296726, ZSIZE= 0.0296726, OUTFN="Wedge5.h5", SURFACEPHYSICS=DEGPHYS_Wedge1 , ELEMEDGE=4.1496;
-Deg_D5: DRIFT, L=0.0114374, ELEMEDGE=4.17928;
-
-Wedge6: DEGRADER, L=0.0148363, ZSIZE= 0.0148363, OUTFN="Wedge6.h5", SURFACEPHYSICS=DEGPHYS_Wedge1 , ELEMEDGE=4.19071;
-Alumina1: DRIFT, L=0.0003, ELEMEDGE=4.20555;
-MDegX: MONITOR, OUTFN="MDegX.h5", ELEMEDGE=4.20585;
-MDegY: MONITOR, OUTFN="MDegY.h5", ELEMEDGE=4.20585;
-END: DRIFT, L=0.2, ELEMEDGE=4.3;
-
-BEAMLINE_A1: LINE=(UPAC,D1,D2,MMAP1X,MMAP2Y,D3,MMAP3X,MMAP4Y,D4,QMA1,QMA1_r0,D5,QMA2,QMA2_r0,D6,D7,QMA3,QMA3_r0,D8,D9,D10,D11,MMAP5X,MMAP6Y,D12,MMAP7X,MMAP8Y,Titan1,Air1,D13,BMA1I,D14,BMA1O,D15,Wedge1,Deg_D1,Wedge2,Deg_D2,Wedge3,Deg_D3,Wedge4,Deg_D4,Wedge5,Deg_D5,Wedge6,Alumina1,MDegX,MDegY,END);
-
-FS1:FIELDSOLVER, FSTYPE=NONE, MX=64, MY=64, MT=64, PARFFTX=true, PARFFTY=true, PARFFTT=true, BCFFTX=open, BCFFTY=open, BCFFTT=open, BBOXINCR=1, GREENSF=STANDARD;
-BEAM_A1: BEAM, PARTICLE=PROTON, PC=P0, NPART=NProt, BCURRENT=NProt*1.6e-19*rf, BFREQ=rf,  CHARGE=1;
-
-STEP0= (0.2262- 0)/(beta*CLIGHT*TFast);
-SELECT, LINE=BEAMLINE_A1;
-TRACK, LINE=BEAMLINE_A1, BEAM=BEAM_A1, MAXSTEPS= STEP0, DT=TFast;//, ZSTOP=0.2262;
-RUN, METHOD = "PARALLEL-T", BEAM=BEAM_A1, FIELDSOLVER=FS1, DISTRIBUTION=DISTRIB1;
-ENDTRACK;
-
-STEP1= (0.5985- 0.2262)/(beta*CLIGHT*TSlow);
-SELECT, LINE=BEAMLINE_A1;
-TRACK, LINE=BEAMLINE_A1, BEAM=BEAM_A1, MAXSTEPS= STEP1, DT=TSlow;//, ZSTOP=0.5985;
-RUN, METHOD = "PARALLEL-T", BEAM=BEAM_A1, FIELDSOLVER=FS1, DISTRIBUTION=DISTRIB1;
-ENDTRACK;
-
-STEP2= (3.3775- 0.5985)/(beta*CLIGHT*TFast);
-SELECT, LINE=BEAMLINE_A1;
-TRACK, LINE=BEAMLINE_A1, BEAM=BEAM_A1, MAXSTEPS= STEP2, DT=TFast;//, ZSTOP=3.3775;
-RUN, METHOD = "PARALLEL-T", BEAM=BEAM_A1, FIELDSOLVER=FS1, DISTRIBUTION=DISTRIB1;
-ENDTRACK;
-
-STEP3= (3.99-4.3)/(beta*CLIGHT*TDeg);
-SELECT, LINE=BEAMLINE_A1;
-TRACK, LINE=BEAMLINE_A1, BEAM=BEAM_A1, MAXSTEPS= 10000, DT=TSlow, ZSTOP=4.5;
-RUN, METHOD = "PARALLEL-T", BEAM=BEAM_A1, FIELDSOLVER=FS1, DISTRIBUTION=DISTRIB1;
-ENDTRACK;
-
-STOP;
+PROSCAN-G3-LA1-130.in
\ No newline at end of file
diff --git a/tests/PROSCAN-G3-LA1-130/doAll b/tests/PROSCAN-G3-LA1-130/doAll
index cddc4cce3814817090bcb7465abd64d826a2833c..e481bb6ae0cf929d90cf122a5b088a673b8fe01c 100755
--- a/tests/PROSCAN-G3-LA1-130/doAll
+++ b/tests/PROSCAN-G3-LA1-130/doAll
@@ -1,7 +1,7 @@
 #!/bin/bash
 #
 #
-for NP in 1 
+for NP in 1
 do
  mkdir -p ${NP}p
  rm -rf PROSCAN-G3-LA1-130-${NP}p.in
diff --git a/tests/classic_src/AbsBeamline/RingTest.cpp b/tests/classic_src/AbsBeamline/RingTest.cpp
index e83e8870c9e101d4e61c738b7e993cb5d3b43e7c..7588f0d3f469ad5f3177ff50e1c31ce70c177c2e 100644
--- a/tests/classic_src/AbsBeamline/RingTest.cpp
+++ b/tests/classic_src/AbsBeamline/RingTest.cpp
@@ -123,6 +123,8 @@ TEST(RingTest, TestAppend1) {
     defaultCerr = std::cerr.rdbuf(debugOutput.rdbuf());
 
     try {
+        std::cout.setstate(std::ios::failbit);
+        std::cerr.setstate(std::ios::failbit);
         double radius = 5.;
         Ring ring("my_ring");
         ring.setLatticeRInit(radius);
@@ -147,6 +149,8 @@ TEST(RingTest, TestAppend1) {
                                                          -cos(Physics::pi/3.),
                                                           0.)(i), 1e-6)  << ::burnAfterReading(debugOutput);
         }
+        std::cout.clear();
+        std::cerr.clear();
     } catch (OpalException& exc) {
         std::cout.rdbuf(defaultCout);
         std::cerr.rdbuf(defaultCerr);
@@ -166,6 +170,8 @@ TEST(RingTest, TestAppend2) {
     defaultCerr = std::cerr.rdbuf(debugOutput.rdbuf());
 
     try {
+        std::cout.setstate(std::ios::failbit);
+        std::cerr.setstate(std::ios::failbit);
         double radius = 5.;
         Ring ring("my_ring");
         ring.setLatticeRInit(radius);
@@ -194,6 +200,8 @@ TEST(RingTest, TestAppend2) {
                 << i << "\n"
                 << ::burnAfterReading(debugOutput);
         }
+        std::cout.clear();
+        std::cerr.clear();
     } catch (OpalException& exc) {
         std::cout.rdbuf(defaultCout);
         std::cerr.rdbuf(defaultCerr);
@@ -213,6 +221,8 @@ TEST(RingTest, TestAppend3) {
     defaultCerr = std::cerr.rdbuf(debugOutput.rdbuf());
 
     try {
+        std::cout.setstate(std::ios::failbit);
+        std::cerr.setstate(std::ios::failbit);
         double radius = 5.;
         Ring ring("my_ring");
         ring.setLatticeRInit(radius);
@@ -225,6 +235,8 @@ TEST(RingTest, TestAppend3) {
             ring.appendElement(off);
         }
         ring.lockRing();
+        std::cout.clear();
+        std::cerr.clear();
     } catch (OpalException& exc) {
         std::cout.rdbuf(defaultCout);
         std::cerr.rdbuf(defaultCerr);
@@ -288,6 +300,8 @@ TEST(RingTest, TestApply) {
 
     Ring ring("my_ring");
     try {
+        std::cout.setstate(std::ios::failbit);
+        std::cerr.setstate(std::ios::failbit);
         double radius = 2.*(2.*sin(Physics::pi/6.)+1.*sin(Physics::pi/3.)+1.0);
         ring.setLatticeRInit(radius-2.);
         ring.setLatticePhiInit(0.);
@@ -305,23 +319,25 @@ TEST(RingTest, TestApply) {
             Vector_t pos(x, y, -0.5);
             Vector_t centroid, B, E;
             // std::cout << pos << " ** " << std::flush;
-            EXPECT_FALSE(ring.apply(pos, centroid, 0., E, B))  << " for pos " << pos << ::burnAfterReading(debugOutput);
+            EXPECT_FALSE(ring.apply(pos, Vector_t(0.0), 0., E, B)) << " for pos " << pos << ::burnAfterReading(debugOutput);
             // std::cout << B << " " << E << std::endl;
             Vector_t BRef(0.0, 0.0, 0.0);
             if (x > 0. and x < 1.)
                 BRef = Vector_t(x-1., y+2., -0.5);
             for (int i = 0; i < 3; ++i) {
-                EXPECT_NEAR(B(i), BRef(i), 1e-6)  << " for pos " << pos << ::burnAfterReading(debugOutput);
-                EXPECT_NEAR(E(i), -BRef(i), 1e-6) << " for pos " << pos << ::burnAfterReading(debugOutput);
+                EXPECT_NEAR(B(i), BRef(i), 1e-6)   << " for pos " << pos << ::burnAfterReading(debugOutput);
+                EXPECT_NEAR(E(i), -BRef(i), 1e-6)  << " for pos " << pos << ::burnAfterReading(debugOutput);
             }
         }
         // check that we get something reasonable for all phi
         for (double phi = 0.; phi < 2.*Physics::pi+0.1; phi += Physics::pi/100.) {
             Vector_t pos(radius/2.*sin(phi), radius/2.+radius/2.*cos(phi), 0.5);
             Vector_t centroid, B, E;
-            EXPECT_FALSE(ring.apply(pos, centroid, 0., E, B)) << ::burnAfterReading(debugOutput); // check we don't throw for all angles
+            EXPECT_FALSE(ring.apply(pos, Vector_t(0.0), 0., E, B)) << ::burnAfterReading(debugOutput); // check we don't throw for all angles
             // std::cout << phi << " " << pos << " " << B << std::endl;
         }
+        std::cout.clear();
+        std::cerr.clear();
     } catch (OpalException& exc) {
         std::cout.rdbuf(defaultCout);
         std::cerr.rdbuf(defaultCerr);
@@ -358,7 +374,7 @@ TEST(RingTest, TestApply2) {
             Vector_t pos((radius+0.5)*sin(phi), (radius+0.5)*cos(phi), -0.5);
             Vector_t centroid, B, E;
             std::vector<RingSection*> sections = ring.getSectionsAt(pos);
-            EXPECT_FALSE(ring.apply(pos, centroid, 0., E, B)) << ::burnAfterReading(debugOutput);
+            EXPECT_FALSE(ring.apply(pos, Vector_t(0.0), 0., E, B)) << ::burnAfterReading(debugOutput);
             // check we don't throw for all angles
             // a few are coming out with Bz = 1. instead of Bz = 0.5; looks like
             // floating point precision issue? It's okay, Ring is not
@@ -367,6 +383,8 @@ TEST(RingTest, TestApply2) {
             EXPECT_LE(-B(2), 1.1) << ::burnAfterReading(debugOutput);
             // std::cout << phi << " " << pos << " " << B << " " << sections.size() << std::endl;
         }
+        std::cout.clear();
+        std::cerr.clear();
     } catch (OpalException& exc) {
         std::cout.rdbuf(defaultCout);
         std::cerr.rdbuf(defaultCerr);
@@ -376,6 +394,8 @@ TEST(RingTest, TestApply2) {
     // Now apply symmetry 2x10 fields instead of 20x1
     Ring ring2("my_ring");
     try {
+        std::cout.setstate(std::ios::failbit);
+        std::cerr.setstate(std::ios::failbit);
         double radius = 1.5;
         ring2.setLatticeRInit(radius);
         ring2.setLatticePhiInit(7.*Physics::pi/4.);
@@ -391,11 +411,13 @@ TEST(RingTest, TestApply2) {
             Vector_t pos((radius+0.5)*sin(phi), (radius+0.5)*cos(phi), 0.5);
             Vector_t centroid, B1, B2, E;
             std::vector<RingSection*> sections = ring2.getSectionsAt(pos);
-            ring.apply(pos, centroid, 0., E, B1);
-            ring2.apply(pos, centroid, 0., E, B2);
+            ring.apply(pos, Vector_t(0.0), 0., E, B1);
+            ring2.apply(pos, Vector_t(0.0), 0., E, B2);
             EXPECT_NEAR(B1(2), B2(2), 1e-6) << ::burnAfterReading(debugOutput);
             // std::cout << phi << " " << pos << " " << B << " " << sections.size() << std::endl;
         }
+        std::cout.clear();
+        std::cerr.clear();
     } catch (OpalException& exc) {
         std::cout.rdbuf(defaultCout);
         std::cerr.rdbuf(defaultCerr);
@@ -406,6 +428,8 @@ TEST(RingTest, TestApply2) {
     // the field
     Ring ring3("my_ring");
     try {
+        std::cout.setstate(std::ios::failbit);
+        std::cerr.setstate(std::ios::failbit);
         double radius = 1.5;
         ring3.setLatticeRInit(radius);
         ring3.setLatticePhiInit(7.*Physics::pi/4.);
@@ -420,11 +444,13 @@ TEST(RingTest, TestApply2) {
             Vector_t pos((radius+0.5)*sin(phi), (radius+0.5)*cos(phi), 0.5);
             Vector_t centroid, B1, B2, E;
             std::vector<RingSection*> sections = ring3.getSectionsAt(pos);
-            ring.apply(pos, centroid, 0., E, B1);
-            ring3.apply(pos, centroid, 0., E, B2);
+            ring.apply(pos, Vector_t(0.0), 0., E, B1);
+            ring3.apply(pos, Vector_t(0.0), 0., E, B2);
             EXPECT_NEAR(2.*B1(2), B2(2), 1e-6) << ::burnAfterReading(debugOutput);
             // std::cout << phi << " " << pos << " " << B << " " << sections.size() << std::endl;
         }
+        std::cout.clear();
+        std::cerr.clear();
     } catch (OpalException& exc) {
         std::cout.rdbuf(defaultCout);
         std::cerr.rdbuf(defaultCerr);
@@ -460,7 +486,7 @@ void testField(double s, double r, double y, double phi,
     Vector_t pos(radius*sin(phi)+s*cos(phi)+r*sin(phi),
                  radius*cos(phi)-s*sin(phi)+r*cos(phi),
                  y);
-    ring.apply(pos, centroid, 0., E, B);
+    ring.apply(pos, Vector_t(0.0), 0., E, B);
     EXPECT_NEAR(B(0), bx, 1e-6) << ::burnAfterReading(debugOutput);
     EXPECT_NEAR(B(1), by, 1e-6) << ::burnAfterReading(debugOutput);
     EXPECT_NEAR(B(2), bz, 1e-6) << ::burnAfterReading(debugOutput);
@@ -471,6 +497,8 @@ void testField(double s, double r, double y, double phi,
 }
 
 TEST(RingTest, TestApply3) {
+    std::cout.setstate(std::ios::failbit);
+    std::cerr.setstate(std::ios::failbit);
     testField(0.1, 0., 0.2, 0., 3., 1., 2., 1e-6);
     testField(0.1, 0., 0.2, Physics::pi, -3., -1., 2., 1e-6);
     testField(0.1, 0., 0.2, Physics::pi/2., 1., -3., 2., 1e-6);
@@ -478,4 +506,7 @@ TEST(RingTest, TestApply3) {
     testField(0.1, 0.15, 0.2, Physics::pi/6.,
               3.*cos(Physics::pi/6)+1.*sin(Physics::pi/6),
               -3.*sin(Physics::pi/6)+1.*cos(Physics::pi/6), 2., 1e-6);
-}
+
+    std::cout.clear();
+    std::cerr.clear();
+}
\ No newline at end of file
diff --git a/tests/classic_src/AbsBeamline/SBend3DTest.cpp b/tests/classic_src/AbsBeamline/SBend3DTest.cpp
index b353f61636cd6663005b1d81c7723e997f202a6f..59489a0095fe8106b106b9e24504a018fc742d18 100644
--- a/tests/classic_src/AbsBeamline/SBend3DTest.cpp
+++ b/tests/classic_src/AbsBeamline/SBend3DTest.cpp
@@ -44,11 +44,11 @@ class LoadFieldMap {
     // Load a field map
     // name - file name to which the field map will be written
     // polynomial_order - order of the polynomial fit to use
-    // smoothing_order - order at which the polynomial is smoothed (i.e. 
+    // smoothing_order - order at which the polynomial is smoothed (i.e.
     //                   derivatives set equal
     // skip_line - skip a line in the input file, index from 0; ignored if -ve
     LoadFieldMap(std::string name, int polynomial_order, int smoothing_order,
-                 int skip_line) 
+                 int skip_line)
         : fname_m(name), sbend3d_m(NULL) {
         writeFieldMap(skip_line);
         getFieldMap(polynomial_order, smoothing_order);
@@ -155,7 +155,7 @@ TEST(SBend3DTest, SBend3DGeometryTest) {
                     y,
                     (radius+r)*sin(phi)
                 );
-                field->apply(pos, centroid, 0, E, B);
+                field->apply(pos, Vector_t(0.0), 0, E, B);
                 if (r > -10. && r < 10. &&
                     phi > 0. && phi < Physics::pi/4. &&
                     y > -5. && y < 5.) {
@@ -190,7 +190,7 @@ void testField(double r, double y, double phi,
         y,
         (radius+r)*sin(phi)
     );
-    field->apply(pos, centroid, 0, E, B);
+    field->apply(pos, Vector_t(0.0), 0, E, B);
     // the field map is rotated through pi/8. (into start at z=0. coordinates)
     double sR = sin(Physics::pi/8.);
     double cR = cos(Physics::pi/8.);
@@ -246,11 +246,11 @@ TEST(SBend3DTest, SBend3DPolyPatchTest) {
                     Vector_t B, E, centroid;
                     Vector_t pos(r*cos(phi)-radius, y, r*sin(phi));
                     std::cerr << "pos: " << pos << " r: " << r << " phi: " << phi/Physics::pi*180. << std::endl;
-                    field1->apply(pos, centroid, 0, E, B);
+                    field1->apply(pos, Vector_t(0.0), 0, E, B);
                     std::cerr << "   field1: " << B << std::endl;
-                    field2->apply(pos, centroid, 0, E, B);
+                    field2->apply(pos, Vector_t(0.0), 0, E, B);
                     std::cerr << "   field2: " << B << std::endl;
-                    field3->apply(pos, centroid, 0, E, B);
+                    field3->apply(pos, Vector_t(0.0), 0, E, B);
                     std::cerr << "   field3: " << B << std::endl;
                 }
     } catch (LogicalError& err) {
diff --git a/tests/classic_src/AbsBeamline/VariableRFCavityTest.cpp b/tests/classic_src/AbsBeamline/VariableRFCavityTest.cpp
index 39d78763a222fc0b1cd2570beec092d59e9c8a5c..752c559d04a4f2f05561083a6bd642da24af0bfd 100644
--- a/tests/classic_src/AbsBeamline/VariableRFCavityTest.cpp
+++ b/tests/classic_src/AbsBeamline/VariableRFCavityTest.cpp
@@ -166,7 +166,7 @@ TEST(VariableRFCavityTest, TestApplyField) {
     Vector_t E(0., 0., 0.);
     for (double t = 0.; t < 10.; t += 1.) {
         double e_test = (1.+2.*t)*sin(Physics::two_pi*t*(3.+4.*t)+(5.+6.*t));
-        ASSERT_FALSE(cav1.apply(R, centroid, t, E, B));
+        ASSERT_FALSE(cav1.apply(R, Vector_t(0.0), t, E, B));
         EXPECT_NEAR(0., E[0], 1.e-6);
         EXPECT_NEAR(0., E[1], 1.e-6);
         EXPECT_NEAR(e_test, E[2], 1.e-6);
@@ -192,27 +192,26 @@ TEST(VariableRFCavityTest, TestApplyBoundingBox) {
     Vector_t B(0., 0., 0.);
     Vector_t E(0., 0., 0.);
     double t = 0;
-    EXPECT_FALSE(cav1.apply(R, centroid, t, E, B));
+    EXPECT_FALSE(cav1.apply(R, Vector_t(0.0), t, E, B));
     R[2] = 2.-1e-9;
-    EXPECT_FALSE(cav1.apply(R, centroid, t, E, B));
+    EXPECT_FALSE(cav1.apply(R, Vector_t(0.0), t, E, B));
     R[2] = 1.e-9;
-    EXPECT_FALSE(cav1.apply(R, centroid, t, E, B));
+    EXPECT_FALSE(cav1.apply(R, Vector_t(0.0), t, E, B));
     R[2] = -1.e-9;
-    EXPECT_TRUE(cav1.apply(R, centroid, t, E, B));
+    EXPECT_TRUE(cav1.apply(R, Vector_t(0.0), t, E, B));
     R[2] = 2.+1.e-9;
-    EXPECT_TRUE(cav1.apply(R, centroid, t, E, B));
+    EXPECT_TRUE(cav1.apply(R, Vector_t(0.0), t, E, B));
     R[2] = 1.;
     R[1] = -1.5-1e-9;
-    EXPECT_TRUE(cav1.apply(R, centroid, t, E, B));
+    EXPECT_TRUE(cav1.apply(R, Vector_t(0.0), t, E, B));
     R[1] = +1.5+1e-9;
-    EXPECT_TRUE(cav1.apply(R, centroid, t, E, B));
+    EXPECT_TRUE(cav1.apply(R, Vector_t(0.0), t, E, B));
     R[1] = 0.;
-    EXPECT_FALSE(cav1.apply(R, centroid, t, E, B));
+    EXPECT_FALSE(cav1.apply(R, Vector_t(0.0), t, E, B));
     R[0] = -2.-1e-9;
-    EXPECT_TRUE(cav1.apply(R, centroid, t, E, B));
+    EXPECT_TRUE(cav1.apply(R, Vector_t(0.0), t, E, B));
     R[0] = +2.+1e-9;
-    EXPECT_TRUE(cav1.apply(R, centroid, t, E, B));
+    EXPECT_TRUE(cav1.apply(R, Vector_t(0.0), t, E, B));
     R[0] = 0.;
-    EXPECT_FALSE(cav1.apply(R, centroid, t, E, B));
-}
-
+    EXPECT_FALSE(cav1.apply(R, Vector_t(0.0), t, E, B));
+}
\ No newline at end of file
diff --git a/tests/opal_src/CMakeLists.txt b/tests/opal_src/CMakeLists.txt
index 2fc4dfdab1a522366550069fa4d048624c73f42c..6f5b32509fcf5bfaaf37fb617b0ce8aaef5fd3f9 100644
--- a/tests/opal_src/CMakeLists.txt
+++ b/tests/opal_src/CMakeLists.txt
@@ -1,6 +1,8 @@
+add_subdirectory (Algorithms/StatisticalErrors)
 add_subdirectory (BasicActions)
 add_subdirectory (Distribution)
 add_subdirectory (Elements)
 add_subdirectory (Utilities)
+#add_subdirectory (Distribution)
 
-set (TEST_SRCS_LOCAL ${TEST_SRCS_LOCAL} PARENT_SCOPE)
+set (TEST_SRCS_LOCAL ${TEST_SRCS_LOCAL} PARENT_SCOPE)
\ No newline at end of file
diff --git a/tests/opal_src/Distribution/GaussTest.cpp b/tests/opal_src/Distribution/GaussTest.cpp
index 2dd1d13fbd3a599925590e400378f5c52894e4dc..9749aef33a1674bf98cbb0be065e21725d121e3a 100644
--- a/tests/opal_src/Distribution/GaussTest.cpp
+++ b/tests/opal_src/Distribution/GaussTest.cpp
@@ -114,11 +114,11 @@ TEST(GaussTest, FullSigmaTest1) {
     if (distObj) {
         Distribution *dist = dynamic_cast<Distribution*>(distObj);
 
-        dist->SetDistType();
-        dist->CheckIfEmitted();
+        dist->setDistType();
+        dist->checkIfEmitted();
 
         size_t numParticles = 1000000;
-        dist->Create(numParticles, Physics::m_p);
+        dist->create(numParticles, Physics::m_p);
 
 
         double R11 = gsl_stats_variance(&(dist->xDist_m[0]), 1, dist->xDist_m.size()) * 1e6;
@@ -243,11 +243,11 @@ TEST(GaussTest, FullSigmaTest2) {
     if (distObj) {
         Distribution *dist = dynamic_cast<Distribution*>(distObj);
 
-        dist->SetDistType();
-        dist->CheckIfEmitted();
+        dist->setDistType();
+        dist->checkIfEmitted();
 
         size_t numParticles = 1000000;
-        dist->Create(numParticles, Physics::m_p);
+        dist->create(numParticles, Physics::m_p);
 
 
         double R11 = gsl_stats_variance(&(dist->xDist_m[0]), 1, dist->xDist_m.size()) * 1e6;
diff --git a/tests/opal_src/Utilities/MockComponent.h b/tests/opal_src/Utilities/MockComponent.h
index 5dae069c5f0d61351713bca622dca5562a8294a5..97c3bd0c3624e09173351212287e6ad760783504 100644
--- a/tests/opal_src/Utilities/MockComponent.h
+++ b/tests/opal_src/Utilities/MockComponent.h
@@ -34,7 +34,7 @@
 /** Mockups for an Opal Component (e.g. field object). The idea is to test
  *  field lookup routines and placement routines and the like by generating a
  *  "fake" component.
- */ 
+ */
 class MockComponent : public Component {
 public:
     MockComponent() : Component("MockComponent"), geom_m(NULL) {
@@ -49,11 +49,13 @@ public:
     ElementBase* clone() const {return new MockComponent(*this);}
     EMField& getField() {EMField* em = NULL; return *em;}
     EMField& getField() const {EMField* em = NULL; return *em;}
-    bool apply(const size_t&, const double&, double*, double*) {return true;}
+    bool apply(const double&, Vector_t&, Vector_t&) {
+        return false;
+    }
     bool apply(const size_t&, const double&, Vector_t&, Vector_t&) {
         return true;
     }
-    bool apply(const Vector_t& r, const Vector_t& c, const double& t,
+    bool apply(const Vector_t& r, const Vector_t& P, const double& t,
                Vector_t& E, Vector_t& B) {
         if (r(0) < 0. || r(0) > 1. ||
             r(1) < -1. || r(1) > 0. ||
@@ -67,7 +69,7 @@ public:
         E(2) = -r(2);
         return false; // NOT isOutOfBounds
     }
-    void initialise(PartBunch*, double&, double&, const double&) {}
+    void initialise(PartBunch*, double&, double&) {}
     void finalise() {}
     bool bends() const {return true;}
     void getDimensions(double&, double&) const {}
@@ -84,24 +86,23 @@ private:
 class MockComponent2 : public Component {
 public:
     MockComponent2() : Component("MockComponent"), geom_m(NULL), refB(1,2,3) {
-        // std::cout << "MOCK2 CONSTRUCTOR " << this << std::endl;
     }
     MockComponent2(const MockComponent2& rhs)
         : Component("MockComponent"), geom_m(rhs.geom_m), refB(rhs.refB) {
-        // std::cout << "MOCK2 COPY CONSTRUCTOR " << this << std::endl;
     }
-    ~MockComponent2() { };//std::cout << "MOCK2 DESTRUCTOR " << this << std::endl;}
+    ~MockComponent2() { };
     void accept(BeamlineVisitor&) const {}
     ElementBase* clone() const {return new MockComponent2(*this);}
     EMField& getField() {EMField* em = NULL; return *em;}
     EMField& getField() const {EMField* em = NULL; return *em;}
-    bool apply(const size_t&, const double&, double*, double*) {return true;}
+    bool apply(const double&, Vector_t&, Vector_t&) {
+        return false;
+    }
     bool apply(const size_t&, const double&, Vector_t&, Vector_t&) {
         return true;
     }
-    bool apply(const Vector_t& r, const Vector_t& c, const double& t,
+    bool apply(const Vector_t& r, const Vector_t& P, const double& t,
                Vector_t& E, Vector_t& B) {
-        std::cerr << "  MockComponent2::apply " << this << " " << r << std::endl;
         lastPos = r;
         if (r(0) < -1. || r(0) > 1. ||
             r(1) < -1. || r(1) > 1. ||
@@ -113,7 +114,7 @@ public:
         E(2) = 0.;
         return false; // NOT isOutOfBounds
     }
-    void initialise(PartBunch*, double&, double&, const double&) {}
+    void initialise(PartBunch*, double&, double&) {}
     void finalise() {}
     bool bends() const {return true;}
     void getDimensions(double&, double&) const {}