diff --git a/make_for_gcc.sh b/make_for_gcc.sh
index 9da62cb5b90a31202c253029bdc071df8e95ca1e..531400e459fc9fc62311c413299bb41903dbe1e5 100755
--- a/make_for_gcc.sh
+++ b/make_for_gcc.sh
@@ -1,7 +1,17 @@
-#!/bin/sh
+#!/bin/sh 
+set -x # for debugging
+
+if [ $# -ne 1 ] 
+then                    # affiche l'usage
+  echo "Missing parameter" 
+  echo "Use: $0 debug for debug" 
+  echo "Use: $0 opt for optimization result" 
+  exit 1
+fi
 
-dir=`pwd`
 
+
+dir=`pwd`
 #NUM_REC="$dir/num_rec"
 
 #INSTALL="/usr/bin/install"
@@ -16,7 +26,17 @@ rm -rf aclocal.m4
 make distclean
 
 ./bootstrap
-F77=gfortran ./configure --prefix=$dir/$TRACY/tracy
+
+if [ $1 == "debug" ]
+then 
+  F77=gfortran ./configure --prefix=$dir/$TRACY/tracy FFLAGS="-g -O2  -Wall -fbounds-check" CFLAGS="-g -O2  -Wall -fno-implicit-templates" CXXFLAGS="-g -O2  -Wall -fno-implicit-templates"
+fi
+
+if [ $1 == "opt" ]
+then 
+F77=gfortran ./configure --prefix=$dir/$TRACY/tracy FFLAGS="-O2  -Wall -fbounds-check" CFLAGS="-O2  -Wall -fno-implicit-templates" CXXFLAGS="-O2  -Wall -fno-implicit-templates"
+
+fi
 
 make
 make install
diff --git a/make_for_isei.sh b/make_for_isei.sh
index 7bed6b4d3df0848c12fcf89107c2e6ef156e95a2..27d0598a1b8154cefb9adc6a6dbc5e5e4d8e6910 100755
--- a/make_for_isei.sh
+++ b/make_for_isei.sh
@@ -16,7 +16,8 @@ rm -rf aclocal.m4
 make distclean
 
 ./bootstrap
-CC=icc F77=ifort CXX=icc ./configure --prefix=$dir/$TRACY/tracy
+CC=icc F77=ifort CXX=icc ./configure --prefix=$dir/$TRACY/tracy 
+FFLAGS="-O2  -Wall -fbounds-check" CXXFLAGS="-O2  -Wall -fno-implicit-templates"
 
 make
 make install
diff --git a/set_var.sh b/set_var.sh
index cc0847cdb48120202f79e28d2e6b7812afe4a6d5..a350d1ecb1e0a1be475c93c00067af3bd8670e46 100644
--- a/set_var.sh
+++ b/set_var.sh
@@ -1,9 +1,12 @@
 # set environment variable for running TracyIII
-
-export LIBPATH=/usr/lib/gcc/i386-redhat-linux/4.1.1
-export LD_LIBRARY_PATH=/usr/lib/gcc/i386-redhat-linux/4.1.1:/usr/local/lib:/usr/lib
-export NUM_REC=$HOME/codes/nrecipes/recipes_c-ansi
-export TRACY_LIB=$HOME/codes/tracy/TracyIII/tracy
+# 32 bits MAC OS X
+#export LIBPATH=/usr/lib/gcc/i686-apple-darwin10/4.2.1
+# 64 bit MAC OS X
+export LIBPATH=/usr/lib/gcc/i686-apple-darwin10/4.2.1/x86_64/
+export LD_LIBRARY_PATH=$LIBPATH:/usr/local/lib:/usr/lib
+CODEDIR=$HOME/Documents/Travail/codes
+export NUM_REC=$CODEDIR/nrecipes/recipes_c-ansi
+export TRACY_LIB=$CODEDIR/tracy/TracyIII/tracy
 export THOR_LIB=$HOME/Thor-2.0
 export LAT="$HOME/projects/in/lattice"
 
diff --git a/tracy/bootstrap b/tracy/bootstrap
index 72f0f967f01d052040b7f555e4fcc8955d10c8a5..31a94c6be9e6c8af185ea5b637e23d5fd6ec2b22 100755
--- a/tracy/bootstrap
+++ b/tracy/bootstrap
@@ -2,5 +2,5 @@
 set -x
 aclocal -I config
 autoheader
-autoconf
+autoreconf
 automake --add-missing --foreign --copy
diff --git a/tracy/config/depcomp b/tracy/config/depcomp
index 807b991f4a895431dfc232112e77b0ae7e3d5017..df8eea7e4ce8862105fcd7929b20bdb45488048b 100755
--- a/tracy/config/depcomp
+++ b/tracy/config/depcomp
@@ -1,7 +1,10 @@
 #! /bin/sh
-
 # depcomp - compile a program generating dependencies as side-effects
-# Copyright 1999, 2000 Free Software Foundation, Inc.
+
+scriptversion=2009-04-28.21; # UTC
+
+# Copyright (C) 1999, 2000, 2003, 2004, 2005, 2006, 2007, 2009 Free
+# Software Foundation, Inc.
 
 # This program is free software; you can redistribute it and/or modify
 # it under the terms of the GNU General Public License as published by
@@ -14,9 +17,7 @@
 # GNU General Public License for more details.
 
 # You should have received a copy of the GNU General Public License
-# along with this program; if not, write to the Free Software
-# Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA
-# 02111-1307, USA.
+# along with this program.  If not, see <http://www.gnu.org/licenses/>.
 
 # As a special exception to the GNU General Public License, if you
 # distribute this file as part of a program that contains a
@@ -25,22 +26,45 @@
 
 # Originally written by Alexandre Oliva <oliva@dcc.unicamp.br>.
 
+case $1 in
+  '')
+     echo "$0: No command.  Try \`$0 --help' for more information." 1>&2
+     exit 1;
+     ;;
+  -h | --h*)
+    cat <<\EOF
+Usage: depcomp [--help] [--version] PROGRAM [ARGS]
+
+Run PROGRAMS ARGS to compile a file, generating dependencies
+as side-effects.
+
+Environment variables:
+  depmode     Dependency tracking mode.
+  source      Source file read by `PROGRAMS ARGS'.
+  object      Object file output by `PROGRAMS ARGS'.
+  DEPDIR      directory where to store dependencies.
+  depfile     Dependency file to output.
+  tmpdepfile  Temporary file to use when outputing dependencies.
+  libtool     Whether libtool is used (yes/no).
+
+Report bugs to <bug-automake@gnu.org>.
+EOF
+    exit $?
+    ;;
+  -v | --v*)
+    echo "depcomp $scriptversion"
+    exit $?
+    ;;
+esac
+
 if test -z "$depmode" || test -z "$source" || test -z "$object"; then
   echo "depcomp: Variables source, object and depmode must be set" 1>&2
   exit 1
 fi
-# `libtool' can also be set to `yes' or `no'.
-
-if test -z "$depfile"; then
-   base=`echo "$object" | sed -e 's,^.*/,,' -e 's,\.\([^.]*\)$,.P\1,'`
-   dir=`echo "$object" | sed 's,/.*$,/,'`
-   if test "$dir" = "$object"; then
-      dir=
-   fi
-   # FIXME: should be _deps on DOS.
-   depfile="$dir.deps/$base"
-fi
 
+# Dependencies for sub/bar.o or sub/bar.obj go into sub/.deps/bar.Po.
+depfile=${depfile-`echo "$object" |
+  sed 's|[^\\/]*$|'${DEPDIR-.deps}'/&|;s|\.\([^.]*\)$|.P\1|;s|Pobj$|Po|'`}
 tmpdepfile=${tmpdepfile-`echo "$depfile" | sed 's/\.\([^.]*\)$/.T\1/'`}
 
 rm -f "$tmpdepfile"
@@ -61,12 +85,34 @@ if test "$depmode" = dashXmstdout; then
    depmode=dashmstdout
 fi
 
+cygpath_u="cygpath -u -f -"
+if test "$depmode" = msvcmsys; then
+   # This is just like msvisualcpp but w/o cygpath translation.
+   # Just convert the backslash-escaped backslashes to single forward
+   # slashes to satisfy depend.m4
+   cygpath_u="sed s,\\\\\\\\,/,g"
+   depmode=msvisualcpp
+fi
+
 case "$depmode" in
 gcc3)
 ## gcc 3 implements dependency tracking that does exactly what
 ## we want.  Yay!  Note: for some reason libtool 1.4 doesn't like
 ## it if -MD -MP comes after the -MF stuff.  Hmm.
-  "$@" -MT "$object" -MD -MP -MF "$tmpdepfile"
+## Unfortunately, FreeBSD c89 acceptance of flags depends upon
+## the command line argument order; so add the flags where they
+## appear in depend2.am.  Note that the slowdown incurred here
+## affects only configure: in makefiles, %FASTDEP% shortcuts this.
+  for arg
+  do
+    case $arg in
+    -c) set fnord "$@" -MT "$object" -MD -MP -MF "$tmpdepfile" "$arg" ;;
+    *)  set fnord "$@" "$arg" ;;
+    esac
+    shift # fnord
+    shift # $arg
+  done
+  "$@"
   stat=$?
   if test $stat -eq 0; then :
   else
@@ -153,14 +199,14 @@ sgi)
 ' < "$tmpdepfile" \
     | sed -e 's/^.*\.o://' -e 's/#.*$//' -e '/^$/ d' | \
     tr '
-' ' ' >> $depfile
-    echo >> $depfile
+' ' ' >> "$depfile"
+    echo >> "$depfile"
 
     # The second pass generates a dummy entry for each header file.
     tr ' ' '
 ' < "$tmpdepfile" \
    | sed -e 's/^.*\.o://' -e 's/#.*$//' -e '/^$/ d' -e 's/$/:/' \
-   >> $depfile
+   >> "$depfile"
   else
     # The sourcefile does not contain any dependencies, so just
     # store a dummy comment line, to avoid errors with the Makefile
@@ -172,31 +218,43 @@ sgi)
 
 aix)
   # The C for AIX Compiler uses -M and outputs the dependencies
-  # in a .u file.  This file always lives in the current directory.
-  # Also, the AIX compiler puts `$object:' at the start of each line;
-  # $object doesn't have directory information.
-  stripped=`echo "$object" | sed -e 's,^.*/,,' -e 's/\(.*\)\..*$/\1/'`
-  tmpdepfile="$stripped.u"
-  outname="$stripped.o"
+  # in a .u file.  In older versions, this file always lives in the
+  # current directory.  Also, the AIX compiler puts `$object:' at the
+  # start of each line; $object doesn't have directory information.
+  # Version 6 uses the directory in both cases.
+  dir=`echo "$object" | sed -e 's|/[^/]*$|/|'`
+  test "x$dir" = "x$object" && dir=
+  base=`echo "$object" | sed -e 's|^.*/||' -e 's/\.o$//' -e 's/\.lo$//'`
   if test "$libtool" = yes; then
+    tmpdepfile1=$dir$base.u
+    tmpdepfile2=$base.u
+    tmpdepfile3=$dir.libs/$base.u
     "$@" -Wc,-M
   else
+    tmpdepfile1=$dir$base.u
+    tmpdepfile2=$dir$base.u
+    tmpdepfile3=$dir$base.u
     "$@" -M
   fi
-
   stat=$?
+
   if test $stat -eq 0; then :
   else
-    rm -f "$tmpdepfile"
+    rm -f "$tmpdepfile1" "$tmpdepfile2" "$tmpdepfile3"
     exit $stat
   fi
 
+  for tmpdepfile in "$tmpdepfile1" "$tmpdepfile2" "$tmpdepfile3"
+  do
+    test -f "$tmpdepfile" && break
+  done
   if test -f "$tmpdepfile"; then
     # Each line is of the form `foo.o: dependent.h'.
     # Do two passes, one to just change these to
     # `$object: dependent.h' and one to simply `dependent.h:'.
-    sed -e "s,^$outname:,$object :," < "$tmpdepfile" > "$depfile"
-    sed -e "s,^$outname: \(.*\)$,\1:," < "$tmpdepfile" >> "$depfile"
+    sed -e "s,^.*\.[a-z]*:,$object:," < "$tmpdepfile" > "$depfile"
+    # That's a tab and a space in the [].
+    sed -e 's,^.*\.[a-z]*:[	 ]*,,' -e 's,$,:,' < "$tmpdepfile" >> "$depfile"
   else
     # The sourcefile does not contain any dependencies, so just
     # store a dummy comment line, to avoid errors with the Makefile
@@ -206,6 +264,89 @@ aix)
   rm -f "$tmpdepfile"
   ;;
 
+icc)
+  # Intel's C compiler understands `-MD -MF file'.  However on
+  #    icc -MD -MF foo.d -c -o sub/foo.o sub/foo.c
+  # ICC 7.0 will fill foo.d with something like
+  #    foo.o: sub/foo.c
+  #    foo.o: sub/foo.h
+  # which is wrong.  We want:
+  #    sub/foo.o: sub/foo.c
+  #    sub/foo.o: sub/foo.h
+  #    sub/foo.c:
+  #    sub/foo.h:
+  # ICC 7.1 will output
+  #    foo.o: sub/foo.c sub/foo.h
+  # and will wrap long lines using \ :
+  #    foo.o: sub/foo.c ... \
+  #     sub/foo.h ... \
+  #     ...
+
+  "$@" -MD -MF "$tmpdepfile"
+  stat=$?
+  if test $stat -eq 0; then :
+  else
+    rm -f "$tmpdepfile"
+    exit $stat
+  fi
+  rm -f "$depfile"
+  # Each line is of the form `foo.o: dependent.h',
+  # or `foo.o: dep1.h dep2.h \', or ` dep3.h dep4.h \'.
+  # Do two passes, one to just change these to
+  # `$object: dependent.h' and one to simply `dependent.h:'.
+  sed "s,^[^:]*:,$object :," < "$tmpdepfile" > "$depfile"
+  # Some versions of the HPUX 10.20 sed can't process this invocation
+  # correctly.  Breaking it into two sed invocations is a workaround.
+  sed 's,^[^:]*: \(.*\)$,\1,;s/^\\$//;/^$/d;/:$/d' < "$tmpdepfile" |
+    sed -e 's/$/ :/' >> "$depfile"
+  rm -f "$tmpdepfile"
+  ;;
+
+hp2)
+  # The "hp" stanza above does not work with aCC (C++) and HP's ia64
+  # compilers, which have integrated preprocessors.  The correct option
+  # to use with these is +Maked; it writes dependencies to a file named
+  # 'foo.d', which lands next to the object file, wherever that
+  # happens to be.
+  # Much of this is similar to the tru64 case; see comments there.
+  dir=`echo "$object" | sed -e 's|/[^/]*$|/|'`
+  test "x$dir" = "x$object" && dir=
+  base=`echo "$object" | sed -e 's|^.*/||' -e 's/\.o$//' -e 's/\.lo$//'`
+  if test "$libtool" = yes; then
+    tmpdepfile1=$dir$base.d
+    tmpdepfile2=$dir.libs/$base.d
+    "$@" -Wc,+Maked
+  else
+    tmpdepfile1=$dir$base.d
+    tmpdepfile2=$dir$base.d
+    "$@" +Maked
+  fi
+  stat=$?
+  if test $stat -eq 0; then :
+  else
+     rm -f "$tmpdepfile1" "$tmpdepfile2"
+     exit $stat
+  fi
+
+  for tmpdepfile in "$tmpdepfile1" "$tmpdepfile2"
+  do
+    test -f "$tmpdepfile" && break
+  done
+  if test -f "$tmpdepfile"; then
+    sed -e "s,^.*\.[a-z]*:,$object:," "$tmpdepfile" > "$depfile"
+    # Add `dependent.h:' lines.
+    sed -ne '2,${
+	       s/^ *//
+	       s/ \\*$//
+	       s/$/:/
+	       p
+	     }' "$tmpdepfile" >> "$depfile"
+  else
+    echo "#dummy" > "$depfile"
+  fi
+  rm -f "$tmpdepfile" "$tmpdepfile2"
+  ;;
+
 tru64)
    # The Tru64 compiler uses -MD to generate dependencies as a side
    # effect.  `cc -MD -o foo.o ...' puts the dependencies into `foo.o.d'.
@@ -217,31 +358,47 @@ tru64)
    base=`echo "$object" | sed -e 's|^.*/||' -e 's/\.o$//' -e 's/\.lo$//'`
 
    if test "$libtool" = yes; then
-      tmpdepfile1="$dir.libs/$base.lo.d"
-      tmpdepfile2="$dir.libs/$base.d"
+      # With Tru64 cc, shared objects can also be used to make a
+      # static library.  This mechanism is used in libtool 1.4 series to
+      # handle both shared and static libraries in a single compilation.
+      # With libtool 1.4, dependencies were output in $dir.libs/$base.lo.d.
+      #
+      # With libtool 1.5 this exception was removed, and libtool now
+      # generates 2 separate objects for the 2 libraries.  These two
+      # compilations output dependencies in $dir.libs/$base.o.d and
+      # in $dir$base.o.d.  We have to check for both files, because
+      # one of the two compilations can be disabled.  We should prefer
+      # $dir$base.o.d over $dir.libs/$base.o.d because the latter is
+      # automatically cleaned when .libs/ is deleted, while ignoring
+      # the former would cause a distcleancheck panic.
+      tmpdepfile1=$dir.libs/$base.lo.d   # libtool 1.4
+      tmpdepfile2=$dir$base.o.d          # libtool 1.5
+      tmpdepfile3=$dir.libs/$base.o.d    # libtool 1.5
+      tmpdepfile4=$dir.libs/$base.d      # Compaq CCC V6.2-504
       "$@" -Wc,-MD
    else
-      tmpdepfile1="$dir$base.o.d"
-      tmpdepfile2="$dir$base.d"
+      tmpdepfile1=$dir$base.o.d
+      tmpdepfile2=$dir$base.d
+      tmpdepfile3=$dir$base.d
+      tmpdepfile4=$dir$base.d
       "$@" -MD
    fi
 
    stat=$?
    if test $stat -eq 0; then :
    else
-      rm -f "$tmpdepfile1" "$tmpdepfile2"
+      rm -f "$tmpdepfile1" "$tmpdepfile2" "$tmpdepfile3" "$tmpdepfile4"
       exit $stat
    fi
 
-   if test -f "$tmpdepfile1"; then
-      tmpdepfile="$tmpdepfile1"
-   else
-      tmpdepfile="$tmpdepfile2"
-   fi
+   for tmpdepfile in "$tmpdepfile1" "$tmpdepfile2" "$tmpdepfile3" "$tmpdepfile4"
+   do
+     test -f "$tmpdepfile" && break
+   done
    if test -f "$tmpdepfile"; then
       sed -e "s,^.*\.[a-z]*:,$object:," < "$tmpdepfile" > "$depfile"
-      # That's a space and a tab in the [].
-      sed -e 's,^.*\.[a-z]*:[ 	]*,,' -e 's,$,:,' < "$tmpdepfile" >> "$depfile"
+      # That's a tab and a space in the [].
+      sed -e 's,^.*\.[a-z]*:[	 ]*,,' -e 's,$,:,' < "$tmpdepfile" >> "$depfile"
    else
       echo "#dummy" > "$depfile"
    fi
@@ -254,20 +411,18 @@ tru64)
 
 dashmstdout)
   # Important note: in order to support this mode, a compiler *must*
-  # always write the proprocessed file to stdout, regardless of -o.
+  # always write the preprocessed file to stdout, regardless of -o.
   "$@" || exit $?
 
   # Remove the call to Libtool.
   if test "$libtool" = yes; then
-    while test $1 != '--mode=compile'; do
+    while test "X$1" != 'X--mode=compile'; do
       shift
     done
     shift
   fi
 
-  # Remove `-o $object'.  We will use -o /dev/null later,
-  # however we can't do the remplacement now because
-  # `-o $object' might simply not be used
+  # Remove `-o $object'.
   IFS=" "
   for arg
   do
@@ -287,7 +442,11 @@ dashmstdout)
   done
 
   test -z "$dashmflag" && dashmflag=-M
-  "$@" -o /dev/null $dashmflag | sed 's:^[^:]*\:[ 	]*:'"$object"'\: :' > "$tmpdepfile"
+  # Require at least two characters before searching for `:'
+  # in the target name.  This is to cope with DOS-style filenames:
+  # a dependency such as `c:/foo/bar' could be seen as target `c' otherwise.
+  "$@" $dashmflag |
+    sed 's:^[  ]*[^: ][^:][^:]*\:[    ]*:'"$object"'\: :' > "$tmpdepfile"
   rm -f "$depfile"
   cat < "$tmpdepfile" > "$depfile"
   tr ' ' '
@@ -306,25 +465,41 @@ dashXmstdout)
 
 makedepend)
   "$@" || exit $?
+  # Remove any Libtool call
+  if test "$libtool" = yes; then
+    while test "X$1" != 'X--mode=compile'; do
+      shift
+    done
+    shift
+  fi
   # X makedepend
   shift
-  cleared=no
-  for arg in "$@"; do
+  cleared=no eat=no
+  for arg
+  do
     case $cleared in
     no)
       set ""; shift
       cleared=yes ;;
     esac
+    if test $eat = yes; then
+      eat=no
+      continue
+    fi
     case "$arg" in
     -D*|-I*)
       set fnord "$@" "$arg"; shift ;;
-    -*)
+    # Strip any option that makedepend may not understand.  Remove
+    # the object too, otherwise makedepend will parse it as a source file.
+    -arch)
+      eat=yes ;;
+    -*|$object)
       ;;
     *)
       set fnord "$@" "$arg"; shift ;;
     esac
   done
-  obj_suffix="`echo $object | sed 's/^.*\././'`"
+  obj_suffix=`echo "$object" | sed 's/^.*\././'`
   touch "$tmpdepfile"
   ${MAKEDEPEND-makedepend} -o"$obj_suffix" -f"$tmpdepfile" "$@"
   rm -f "$depfile"
@@ -339,12 +514,12 @@ makedepend)
 
 cpp)
   # Important note: in order to support this mode, a compiler *must*
-  # always write the proprocessed file to stdout.
+  # always write the preprocessed file to stdout.
   "$@" || exit $?
 
   # Remove the call to Libtool.
   if test "$libtool" = yes; then
-    while test $1 != '--mode=compile'; do
+    while test "X$1" != 'X--mode=compile'; do
       shift
     done
     shift
@@ -370,7 +545,8 @@ cpp)
   done
 
   "$@" -E |
-    sed -n '/^# [0-9][0-9]* "\([^"]*\)".*/ s:: \1 \\:p' |
+    sed -n -e '/^# [0-9][0-9]* "\([^"]*\)".*/ s:: \1 \\:p' \
+       -e '/^#line [0-9][0-9]* "\([^"]*\)".*/ s:: \1 \\:p' |
     sed '$ s: \\$::' > "$tmpdepfile"
   rm -f "$depfile"
   echo "$object : \\" > "$depfile"
@@ -381,13 +557,27 @@ cpp)
 
 msvisualcpp)
   # Important note: in order to support this mode, a compiler *must*
-  # always write the proprocessed file to stdout, regardless of -o,
-  # because we must use -o when running libtool.
+  # always write the preprocessed file to stdout.
   "$@" || exit $?
+
+  # Remove the call to Libtool.
+  if test "$libtool" = yes; then
+    while test "X$1" != 'X--mode=compile'; do
+      shift
+    done
+    shift
+  fi
+
   IFS=" "
   for arg
   do
     case "$arg" in
+    -o)
+      shift
+      ;;
+    $object)
+      shift
+      ;;
     "-Gm"|"/Gm"|"-Gi"|"/Gi"|"-ZI"|"/ZI")
 	set fnord "$@"
 	shift
@@ -400,16 +590,23 @@ msvisualcpp)
 	;;
     esac
   done
-  "$@" -E |
-  sed -n '/^#line [0-9][0-9]* "\([^"]*\)"/ s::echo "`cygpath -u \\"\1\\"`":p' | sort | uniq > "$tmpdepfile"
+  "$@" -E 2>/dev/null |
+  sed -n '/^#line [0-9][0-9]* "\([^"]*\)"/ s::\1:p' | $cygpath_u | sort -u > "$tmpdepfile"
   rm -f "$depfile"
   echo "$object : \\" > "$depfile"
-  . "$tmpdepfile" | sed 's% %\\ %g' | sed -n '/^\(.*\)$/ s::	\1 \\:p' >> "$depfile"
+  sed < "$tmpdepfile" -n -e 's% %\\ %g' -e '/^\(.*\)$/ s::	\1 \\:p' >> "$depfile"
   echo "	" >> "$depfile"
-  . "$tmpdepfile" | sed 's% %\\ %g' | sed -n '/^\(.*\)$/ s::\1\::p' >> "$depfile"
+  sed < "$tmpdepfile" -n -e 's% %\\ %g' -e '/^\(.*\)$/ s::\1\::p' >> "$depfile"
   rm -f "$tmpdepfile"
   ;;
 
+msvcmsys)
+  # This case exists only to let depend.m4 do its work.  It works by
+  # looking at the text of this script.  This case will never be run,
+  # since it is checked for above.
+  exit 1
+  ;;
+
 none)
   exec "$@"
   ;;
@@ -421,3 +618,13 @@ none)
 esac
 
 exit 0
+
+# Local Variables:
+# mode: shell-script
+# sh-indentation: 2
+# eval: (add-hook 'write-file-hooks 'time-stamp)
+# time-stamp-start: "scriptversion="
+# time-stamp-format: "%:y-%02m-%02d.%02H"
+# time-stamp-time-zone: "UTC"
+# time-stamp-end: "; # UTC"
+# End:
diff --git a/tracy/config/install-sh b/tracy/config/install-sh
index e9de23842dcd44d2953129c866b1ad25f7e1f1d9..6781b987bdbcbc23efe6bbe1654a1e3637b9af07 100755
--- a/tracy/config/install-sh
+++ b/tracy/config/install-sh
@@ -1,251 +1,520 @@
 #!/bin/sh
-#
 # install - install a program, script, or datafile
-# This comes from X11R5 (mit/util/scripts/install.sh).
+
+scriptversion=2009-04-28.21; # UTC
+
+# This originates from X11R5 (mit/util/scripts/install.sh), which was
+# later released in X11R6 (xc/config/util/install.sh) with the
+# following copyright and license.
+#
+# Copyright (C) 1994 X Consortium
+#
+# Permission is hereby granted, free of charge, to any person obtaining a copy
+# of this software and associated documentation files (the "Software"), to
+# deal in the Software without restriction, including without limitation the
+# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
+# sell copies of the Software, and to permit persons to whom the Software is
+# furnished to do so, subject to the following conditions:
+#
+# The above copyright notice and this permission notice shall be included in
+# all copies or substantial portions of the Software.
+#
+# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL THE
+# X CONSORTIUM BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN
+# AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNEC-
+# TION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
 #
-# Copyright 1991 by the Massachusetts Institute of Technology
+# Except as contained in this notice, the name of the X Consortium shall not
+# be used in advertising or otherwise to promote the sale, use or other deal-
+# ings in this Software without prior written authorization from the X Consor-
+# tium.
 #
-# Permission to use, copy, modify, distribute, and sell this software and its
-# documentation for any purpose is hereby granted without fee, provided that
-# the above copyright notice appear in all copies and that both that
-# copyright notice and this permission notice appear in supporting
-# documentation, and that the name of M.I.T. not be used in advertising or
-# publicity pertaining to distribution of the software without specific,
-# written prior permission.  M.I.T. makes no representations about the
-# suitability of this software for any purpose.  It is provided "as is"
-# without express or implied warranty.
+#
+# FSF changes to this file are in the public domain.
 #
 # Calling this script install-sh is preferred over install.sh, to prevent
 # `make' implicit rules from creating a file called install from it
 # when there is no Makefile.
 #
 # This script is compatible with the BSD install script, but was written
-# from scratch.  It can only install one file at a time, a restriction
-# shared with many OS's install programs.
+# from scratch.
 
+nl='
+'
+IFS=" ""	$nl"
 
 # set DOITPROG to echo to test this script
 
 # Don't use :- since 4.3BSD and earlier shells don't like it.
-doit="${DOITPROG-}"
-
-
-# put in absolute paths if you don't have them in your path; or use env. vars.
-
-mvprog="${MVPROG-mv}"
-cpprog="${CPPROG-cp}"
-chmodprog="${CHMODPROG-chmod}"
-chownprog="${CHOWNPROG-chown}"
-chgrpprog="${CHGRPPROG-chgrp}"
-stripprog="${STRIPPROG-strip}"
-rmprog="${RMPROG-rm}"
-mkdirprog="${MKDIRPROG-mkdir}"
-
-transformbasename=""
-transform_arg=""
-instcmd="$mvprog"
-chmodcmd="$chmodprog 0755"
-chowncmd=""
-chgrpcmd=""
-stripcmd=""
-rmcmd="$rmprog -f"
-mvcmd="$mvprog"
-src=""
-dst=""
-dir_arg=""
-
-while [ x"$1" != x ]; do
-    case $1 in
-	-c) instcmd="$cpprog"
-	    shift
-	    continue;;
-
-	-d) dir_arg=true
-	    shift
-	    continue;;
-
-	-m) chmodcmd="$chmodprog $2"
-	    shift
-	    shift
-	    continue;;
-
-	-o) chowncmd="$chownprog $2"
-	    shift
-	    shift
-	    continue;;
-
-	-g) chgrpcmd="$chgrpprog $2"
-	    shift
-	    shift
-	    continue;;
-
-	-s) stripcmd="$stripprog"
-	    shift
-	    continue;;
-
-	-t=*) transformarg=`echo $1 | sed 's/-t=//'`
-	    shift
-	    continue;;
-
-	-b=*) transformbasename=`echo $1 | sed 's/-b=//'`
-	    shift
-	    continue;;
-
-	*)  if [ x"$src" = x ]
-	    then
-		src=$1
-	    else
-		# this colon is to work around a 386BSD /bin/sh bug
-		:
-		dst=$1
-	    fi
-	    shift
-	    continue;;
-    esac
-done
-
-if [ x"$src" = x ]
-then
-	echo "install:	no input file specified"
-	exit 1
+doit=${DOITPROG-}
+if test -z "$doit"; then
+  doit_exec=exec
 else
-	true
+  doit_exec=$doit
 fi
 
-if [ x"$dir_arg" != x ]; then
-	dst=$src
-	src=""
-	
-	if [ -d $dst ]; then
-		instcmd=:
-		chmodcmd=""
-	else
-		instcmd=mkdir
-	fi
-else
+# Put in absolute file names if you don't have them in your path;
+# or use environment vars.
+
+chgrpprog=${CHGRPPROG-chgrp}
+chmodprog=${CHMODPROG-chmod}
+chownprog=${CHOWNPROG-chown}
+cmpprog=${CMPPROG-cmp}
+cpprog=${CPPROG-cp}
+mkdirprog=${MKDIRPROG-mkdir}
+mvprog=${MVPROG-mv}
+rmprog=${RMPROG-rm}
+stripprog=${STRIPPROG-strip}
+
+posix_glob='?'
+initialize_posix_glob='
+  test "$posix_glob" != "?" || {
+    if (set -f) 2>/dev/null; then
+      posix_glob=
+    else
+      posix_glob=:
+    fi
+  }
+'
 
-# Waiting for this to be detected by the "$instcmd $src $dsttmp" command
-# might cause directories to be created, which would be especially bad 
-# if $src (and thus $dsttmp) contains '*'.
+posix_mkdir=
 
-	if [ -f $src -o -d $src ]
-	then
-		true
-	else
-		echo "install:  $src does not exist"
-		exit 1
-	fi
-	
-	if [ x"$dst" = x ]
-	then
-		echo "install:	no destination specified"
-		exit 1
-	else
-		true
-	fi
+# Desired mode of installed file.
+mode=0755
 
-# If destination is a directory, append the input filename; if your system
-# does not like double slashes in filenames, you may need to add some logic
+chgrpcmd=
+chmodcmd=$chmodprog
+chowncmd=
+mvcmd=$mvprog
+rmcmd="$rmprog -f"
+stripcmd=
 
-	if [ -d $dst ]
-	then
-		dst="$dst"/`basename $src`
-	else
-		true
-	fi
-fi
+src=
+dst=
+dir_arg=
+dst_arg=
 
-## this sed command emulates the dirname command
-dstdir=`echo $dst | sed -e 's,[^/]*$,,;s,/$,,;s,^$,.,'`
+copy_on_change=false
+no_target_directory=
 
-# Make sure that the destination directory exists.
-#  this part is taken from Noah Friedman's mkinstalldirs script
+usage="\
+Usage: $0 [OPTION]... [-T] SRCFILE DSTFILE
+   or: $0 [OPTION]... SRCFILES... DIRECTORY
+   or: $0 [OPTION]... -t DIRECTORY SRCFILES...
+   or: $0 [OPTION]... -d DIRECTORIES...
 
-# Skip lots of stat calls in the usual case.
-if [ ! -d "$dstdir" ]; then
-defaultIFS='	
-'
-IFS="${IFS-${defaultIFS}}"
+In the 1st form, copy SRCFILE to DSTFILE.
+In the 2nd and 3rd, copy all SRCFILES to DIRECTORY.
+In the 4th, create DIRECTORIES.
 
-oIFS="${IFS}"
-# Some sh's can't handle IFS=/ for some reason.
-IFS='%'
-set - `echo ${dstdir} | sed -e 's@/@%@g' -e 's@^%@/@'`
-IFS="${oIFS}"
+Options:
+     --help     display this help and exit.
+     --version  display version info and exit.
 
-pathcomp=''
+  -c            (ignored)
+  -C            install only if different (preserve the last data modification time)
+  -d            create directories instead of installing files.
+  -g GROUP      $chgrpprog installed files to GROUP.
+  -m MODE       $chmodprog installed files to MODE.
+  -o USER       $chownprog installed files to USER.
+  -s            $stripprog installed files.
+  -t DIRECTORY  install into DIRECTORY.
+  -T            report an error if DSTFILE is a directory.
 
-while [ $# -ne 0 ] ; do
-	pathcomp="${pathcomp}${1}"
-	shift
+Environment variables override the default commands:
+  CHGRPPROG CHMODPROG CHOWNPROG CMPPROG CPPROG MKDIRPROG MVPROG
+  RMPROG STRIPPROG
+"
 
-	if [ ! -d "${pathcomp}" ] ;
-        then
-		$mkdirprog "${pathcomp}"
-	else
-		true
-	fi
+while test $# -ne 0; do
+  case $1 in
+    -c) ;;
 
-	pathcomp="${pathcomp}/"
-done
-fi
+    -C) copy_on_change=true;;
 
-if [ x"$dir_arg" != x ]
-then
-	$doit $instcmd $dst &&
+    -d) dir_arg=true;;
 
-	if [ x"$chowncmd" != x ]; then $doit $chowncmd $dst; else true ; fi &&
-	if [ x"$chgrpcmd" != x ]; then $doit $chgrpcmd $dst; else true ; fi &&
-	if [ x"$stripcmd" != x ]; then $doit $stripcmd $dst; else true ; fi &&
-	if [ x"$chmodcmd" != x ]; then $doit $chmodcmd $dst; else true ; fi
-else
+    -g) chgrpcmd="$chgrpprog $2"
+	shift;;
 
-# If we're going to rename the final executable, determine the name now.
+    --help) echo "$usage"; exit $?;;
 
-	if [ x"$transformarg" = x ] 
-	then
-		dstfile=`basename $dst`
-	else
-		dstfile=`basename $dst $transformbasename | 
-			sed $transformarg`$transformbasename
-	fi
+    -m) mode=$2
+	case $mode in
+	  *' '* | *'	'* | *'
+'*	  | *'*'* | *'?'* | *'['*)
+	    echo "$0: invalid mode: $mode" >&2
+	    exit 1;;
+	esac
+	shift;;
 
-# don't allow the sed command to completely eliminate the filename
+    -o) chowncmd="$chownprog $2"
+	shift;;
 
-	if [ x"$dstfile" = x ] 
-	then
-		dstfile=`basename $dst`
-	else
-		true
-	fi
+    -s) stripcmd=$stripprog;;
 
-# Make a temp file name in the proper directory.
+    -t) dst_arg=$2
+	shift;;
 
-	dsttmp=$dstdir/#inst.$$#
+    -T) no_target_directory=true;;
 
-# Move or copy the file name to the temp name
+    --version) echo "$0 $scriptversion"; exit $?;;
 
-	$doit $instcmd $src $dsttmp &&
+    --)	shift
+	break;;
 
-	trap "rm -f ${dsttmp}" 0 &&
+    -*)	echo "$0: invalid option: $1" >&2
+	exit 1;;
 
-# and set any options; do chmod last to preserve setuid bits
+    *)  break;;
+  esac
+  shift
+done
 
-# If any of these fail, we abort the whole thing.  If we want to
-# ignore errors from any of these, just make sure not to ignore
-# errors from the above "$doit $instcmd $src $dsttmp" command.
+if test $# -ne 0 && test -z "$dir_arg$dst_arg"; then
+  # When -d is used, all remaining arguments are directories to create.
+  # When -t is used, the destination is already specified.
+  # Otherwise, the last argument is the destination.  Remove it from $@.
+  for arg
+  do
+    if test -n "$dst_arg"; then
+      # $@ is not empty: it contains at least $arg.
+      set fnord "$@" "$dst_arg"
+      shift # fnord
+    fi
+    shift # arg
+    dst_arg=$arg
+  done
+fi
 
-	if [ x"$chowncmd" != x ]; then $doit $chowncmd $dsttmp; else true;fi &&
-	if [ x"$chgrpcmd" != x ]; then $doit $chgrpcmd $dsttmp; else true;fi &&
-	if [ x"$stripcmd" != x ]; then $doit $stripcmd $dsttmp; else true;fi &&
-	if [ x"$chmodcmd" != x ]; then $doit $chmodcmd $dsttmp; else true;fi &&
+if test $# -eq 0; then
+  if test -z "$dir_arg"; then
+    echo "$0: no input file specified." >&2
+    exit 1
+  fi
+  # It's OK to call `install-sh -d' without argument.
+  # This can happen when creating conditional directories.
+  exit 0
+fi
 
-# Now rename the file to the real destination.
+if test -z "$dir_arg"; then
+  trap '(exit $?); exit' 1 2 13 15
+
+  # Set umask so as not to create temps with too-generous modes.
+  # However, 'strip' requires both read and write access to temps.
+  case $mode in
+    # Optimize common cases.
+    *644) cp_umask=133;;
+    *755) cp_umask=22;;
+
+    *[0-7])
+      if test -z "$stripcmd"; then
+	u_plus_rw=
+      else
+	u_plus_rw='% 200'
+      fi
+      cp_umask=`expr '(' 777 - $mode % 1000 ')' $u_plus_rw`;;
+    *)
+      if test -z "$stripcmd"; then
+	u_plus_rw=
+      else
+	u_plus_rw=,u+rw
+      fi
+      cp_umask=$mode$u_plus_rw;;
+  esac
+fi
 
-	$doit $rmcmd -f $dstdir/$dstfile &&
-	$doit $mvcmd $dsttmp $dstdir/$dstfile 
+for src
+do
+  # Protect names starting with `-'.
+  case $src in
+    -*) src=./$src;;
+  esac
+
+  if test -n "$dir_arg"; then
+    dst=$src
+    dstdir=$dst
+    test -d "$dstdir"
+    dstdir_status=$?
+  else
+
+    # Waiting for this to be detected by the "$cpprog $src $dsttmp" command
+    # might cause directories to be created, which would be especially bad
+    # if $src (and thus $dsttmp) contains '*'.
+    if test ! -f "$src" && test ! -d "$src"; then
+      echo "$0: $src does not exist." >&2
+      exit 1
+    fi
+
+    if test -z "$dst_arg"; then
+      echo "$0: no destination specified." >&2
+      exit 1
+    fi
+
+    dst=$dst_arg
+    # Protect names starting with `-'.
+    case $dst in
+      -*) dst=./$dst;;
+    esac
 
-fi &&
+    # If destination is a directory, append the input filename; won't work
+    # if double slashes aren't ignored.
+    if test -d "$dst"; then
+      if test -n "$no_target_directory"; then
+	echo "$0: $dst_arg: Is a directory" >&2
+	exit 1
+      fi
+      dstdir=$dst
+      dst=$dstdir/`basename "$src"`
+      dstdir_status=0
+    else
+      # Prefer dirname, but fall back on a substitute if dirname fails.
+      dstdir=`
+	(dirname "$dst") 2>/dev/null ||
+	expr X"$dst" : 'X\(.*[^/]\)//*[^/][^/]*/*$' \| \
+	     X"$dst" : 'X\(//\)[^/]' \| \
+	     X"$dst" : 'X\(//\)$' \| \
+	     X"$dst" : 'X\(/\)' \| . 2>/dev/null ||
+	echo X"$dst" |
+	    sed '/^X\(.*[^/]\)\/\/*[^/][^/]*\/*$/{
+		   s//\1/
+		   q
+		 }
+		 /^X\(\/\/\)[^/].*/{
+		   s//\1/
+		   q
+		 }
+		 /^X\(\/\/\)$/{
+		   s//\1/
+		   q
+		 }
+		 /^X\(\/\).*/{
+		   s//\1/
+		   q
+		 }
+		 s/.*/./; q'
+      `
+
+      test -d "$dstdir"
+      dstdir_status=$?
+    fi
+  fi
+
+  obsolete_mkdir_used=false
+
+  if test $dstdir_status != 0; then
+    case $posix_mkdir in
+      '')
+	# Create intermediate dirs using mode 755 as modified by the umask.
+	# This is like FreeBSD 'install' as of 1997-10-28.
+	umask=`umask`
+	case $stripcmd.$umask in
+	  # Optimize common cases.
+	  *[2367][2367]) mkdir_umask=$umask;;
+	  .*0[02][02] | .[02][02] | .[02]) mkdir_umask=22;;
+
+	  *[0-7])
+	    mkdir_umask=`expr $umask + 22 \
+	      - $umask % 100 % 40 + $umask % 20 \
+	      - $umask % 10 % 4 + $umask % 2
+	    `;;
+	  *) mkdir_umask=$umask,go-w;;
+	esac
+
+	# With -d, create the new directory with the user-specified mode.
+	# Otherwise, rely on $mkdir_umask.
+	if test -n "$dir_arg"; then
+	  mkdir_mode=-m$mode
+	else
+	  mkdir_mode=
+	fi
 
+	posix_mkdir=false
+	case $umask in
+	  *[123567][0-7][0-7])
+	    # POSIX mkdir -p sets u+wx bits regardless of umask, which
+	    # is incompatible with FreeBSD 'install' when (umask & 300) != 0.
+	    ;;
+	  *)
+	    tmpdir=${TMPDIR-/tmp}/ins$RANDOM-$$
+	    trap 'ret=$?; rmdir "$tmpdir/d" "$tmpdir" 2>/dev/null; exit $ret' 0
+
+	    if (umask $mkdir_umask &&
+		exec $mkdirprog $mkdir_mode -p -- "$tmpdir/d") >/dev/null 2>&1
+	    then
+	      if test -z "$dir_arg" || {
+		   # Check for POSIX incompatibilities with -m.
+		   # HP-UX 11.23 and IRIX 6.5 mkdir -m -p sets group- or
+		   # other-writeable bit of parent directory when it shouldn't.
+		   # FreeBSD 6.1 mkdir -m -p sets mode of existing directory.
+		   ls_ld_tmpdir=`ls -ld "$tmpdir"`
+		   case $ls_ld_tmpdir in
+		     d????-?r-*) different_mode=700;;
+		     d????-?--*) different_mode=755;;
+		     *) false;;
+		   esac &&
+		   $mkdirprog -m$different_mode -p -- "$tmpdir" && {
+		     ls_ld_tmpdir_1=`ls -ld "$tmpdir"`
+		     test "$ls_ld_tmpdir" = "$ls_ld_tmpdir_1"
+		   }
+		 }
+	      then posix_mkdir=:
+	      fi
+	      rmdir "$tmpdir/d" "$tmpdir"
+	    else
+	      # Remove any dirs left behind by ancient mkdir implementations.
+	      rmdir ./$mkdir_mode ./-p ./-- 2>/dev/null
+	    fi
+	    trap '' 0;;
+	esac;;
+    esac
+
+    if
+      $posix_mkdir && (
+	umask $mkdir_umask &&
+	$doit_exec $mkdirprog $mkdir_mode -p -- "$dstdir"
+      )
+    then :
+    else
+
+      # The umask is ridiculous, or mkdir does not conform to POSIX,
+      # or it failed possibly due to a race condition.  Create the
+      # directory the slow way, step by step, checking for races as we go.
+
+      case $dstdir in
+	/*) prefix='/';;
+	-*) prefix='./';;
+	*)  prefix='';;
+      esac
+
+      eval "$initialize_posix_glob"
+
+      oIFS=$IFS
+      IFS=/
+      $posix_glob set -f
+      set fnord $dstdir
+      shift
+      $posix_glob set +f
+      IFS=$oIFS
+
+      prefixes=
+
+      for d
+      do
+	test -z "$d" && continue
+
+	prefix=$prefix$d
+	if test -d "$prefix"; then
+	  prefixes=
+	else
+	  if $posix_mkdir; then
+	    (umask=$mkdir_umask &&
+	     $doit_exec $mkdirprog $mkdir_mode -p -- "$dstdir") && break
+	    # Don't fail if two instances are running concurrently.
+	    test -d "$prefix" || exit 1
+	  else
+	    case $prefix in
+	      *\'*) qprefix=`echo "$prefix" | sed "s/'/'\\\\\\\\''/g"`;;
+	      *) qprefix=$prefix;;
+	    esac
+	    prefixes="$prefixes '$qprefix'"
+	  fi
+	fi
+	prefix=$prefix/
+      done
+
+      if test -n "$prefixes"; then
+	# Don't fail if two instances are running concurrently.
+	(umask $mkdir_umask &&
+	 eval "\$doit_exec \$mkdirprog $prefixes") ||
+	  test -d "$dstdir" || exit 1
+	obsolete_mkdir_used=true
+      fi
+    fi
+  fi
+
+  if test -n "$dir_arg"; then
+    { test -z "$chowncmd" || $doit $chowncmd "$dst"; } &&
+    { test -z "$chgrpcmd" || $doit $chgrpcmd "$dst"; } &&
+    { test "$obsolete_mkdir_used$chowncmd$chgrpcmd" = false ||
+      test -z "$chmodcmd" || $doit $chmodcmd $mode "$dst"; } || exit 1
+  else
+
+    # Make a couple of temp file names in the proper directory.
+    dsttmp=$dstdir/_inst.$$_
+    rmtmp=$dstdir/_rm.$$_
+
+    # Trap to clean up those temp files at exit.
+    trap 'ret=$?; rm -f "$dsttmp" "$rmtmp" && exit $ret' 0
+
+    # Copy the file name to the temp name.
+    (umask $cp_umask && $doit_exec $cpprog "$src" "$dsttmp") &&
+
+    # and set any options; do chmod last to preserve setuid bits.
+    #
+    # If any of these fail, we abort the whole thing.  If we want to
+    # ignore errors from any of these, just make sure not to ignore
+    # errors from the above "$doit $cpprog $src $dsttmp" command.
+    #
+    { test -z "$chowncmd" || $doit $chowncmd "$dsttmp"; } &&
+    { test -z "$chgrpcmd" || $doit $chgrpcmd "$dsttmp"; } &&
+    { test -z "$stripcmd" || $doit $stripcmd "$dsttmp"; } &&
+    { test -z "$chmodcmd" || $doit $chmodcmd $mode "$dsttmp"; } &&
+
+    # If -C, don't bother to copy if it wouldn't change the file.
+    if $copy_on_change &&
+       old=`LC_ALL=C ls -dlL "$dst"	2>/dev/null` &&
+       new=`LC_ALL=C ls -dlL "$dsttmp"	2>/dev/null` &&
+
+       eval "$initialize_posix_glob" &&
+       $posix_glob set -f &&
+       set X $old && old=:$2:$4:$5:$6 &&
+       set X $new && new=:$2:$4:$5:$6 &&
+       $posix_glob set +f &&
+
+       test "$old" = "$new" &&
+       $cmpprog "$dst" "$dsttmp" >/dev/null 2>&1
+    then
+      rm -f "$dsttmp"
+    else
+      # Rename the file to the real destination.
+      $doit $mvcmd -f "$dsttmp" "$dst" 2>/dev/null ||
+
+      # The rename failed, perhaps because mv can't rename something else
+      # to itself, or perhaps because mv is so ancient that it does not
+      # support -f.
+      {
+	# Now remove or move aside any old file at destination location.
+	# We try this two ways since rm can't unlink itself on some
+	# systems and the destination file might be busy for other
+	# reasons.  In this case, the final cleanup might fail but the new
+	# file should still install successfully.
+	{
+	  test ! -f "$dst" ||
+	  $doit $rmcmd -f "$dst" 2>/dev/null ||
+	  { $doit $mvcmd -f "$dst" "$rmtmp" 2>/dev/null &&
+	    { $doit $rmcmd -f "$rmtmp" 2>/dev/null; :; }
+	  } ||
+	  { echo "$0: cannot unlink or rename $dst" >&2
+	    (exit 1); exit 1
+	  }
+	} &&
+
+	# Now rename the file to the real destination.
+	$doit $mvcmd "$dsttmp" "$dst"
+      }
+    fi || exit 1
+
+    trap '' 0
+  fi
+done
 
-exit 0
+# Local variables:
+# eval: (add-hook 'write-file-hooks 'time-stamp)
+# time-stamp-start: "scriptversion="
+# time-stamp-format: "%:y-%02m-%02d.%02H"
+# time-stamp-time-zone: "UTC"
+# time-stamp-end: "; # UTC"
+# End:
diff --git a/tracy/config/missing b/tracy/config/missing
index 6a37006e8f0a69ddbf5b383c882beb60cbe04d12..28055d2ae6f2a2c584afcd769d7881e11f62ecd9 100755
--- a/tracy/config/missing
+++ b/tracy/config/missing
@@ -1,6 +1,10 @@
 #! /bin/sh
 # Common stub for a few missing GNU programs while installing.
-# Copyright (C) 1996, 1997, 1999, 2000, 2002 Free Software Foundation, Inc.
+
+scriptversion=2009-04-28.21; # UTC
+
+# Copyright (C) 1996, 1997, 1999, 2000, 2002, 2003, 2004, 2005, 2006,
+# 2008, 2009 Free Software Foundation, Inc.
 # Originally by Fran,cois Pinard <pinard@iro.umontreal.ca>, 1996.
 
 # This program is free software; you can redistribute it and/or modify
@@ -14,9 +18,7 @@
 # GNU General Public License for more details.
 
 # You should have received a copy of the GNU General Public License
-# along with this program; if not, write to the Free Software
-# Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA
-# 02111-1307, USA.
+# along with this program.  If not, see <http://www.gnu.org/licenses/>.
 
 # As a special exception to the GNU General Public License, if you
 # distribute this file as part of a program that contains a
@@ -29,6 +31,8 @@ if test $# -eq 0; then
 fi
 
 run=:
+sed_output='s/.* --output[ =]\([^ ]*\).*/\1/p'
+sed_minuso='s/.* -o \([^ ]*\).*/\1/p'
 
 # In the cases where this matters, `missing' is being run in the
 # srcdir already.
@@ -38,18 +42,24 @@ else
   configure_ac=configure.in
 fi
 
-case "$1" in
+msg="missing on your system"
+
+case $1 in
 --run)
   # Try to run requested program, and just exit if it succeeds.
   run=
   shift
   "$@" && exit 0
+  # Exit code 63 means version mismatch.  This often happens
+  # when the user try to use an ancient version of a tool on
+  # a file that requires a minimum version.  In this case we
+  # we should proceed has if the program had been absent, or
+  # if --run hadn't been passed.
+  if test $? = 63; then
+    run=:
+    msg="probably too old"
+  fi
   ;;
-esac
-
-# If it does not exist, or fails to run (possibly an outdated version),
-# try to emulate it.
-case "$1" in
 
   -h|--h|--he|--hel|--help)
     echo "\
@@ -67,6 +77,7 @@ Supported PROGRAM values:
   aclocal      touch file \`aclocal.m4'
   autoconf     touch file \`configure'
   autoheader   touch file \`config.h.in'
+  autom4te     touch the output file, or create a stub one
   automake     touch all \`Makefile.in' files
   bison        create \`y.tab.[ch]', if possible, from existing .[ch]
   flex         create \`lex.yy.c', if possible, from existing .c
@@ -74,11 +85,18 @@ Supported PROGRAM values:
   lex          create \`lex.yy.c', if possible, from existing .c
   makeinfo     touch the output file
   tar          try tar, gnutar, gtar, then tar without non-portable flags
-  yacc         create \`y.tab.[ch]', if possible, from existing .[ch]"
+  yacc         create \`y.tab.[ch]', if possible, from existing .[ch]
+
+Version suffixes to PROGRAM as well as the prefixes \`gnu-', \`gnu', and
+\`g' are ignored when checking the name.
+
+Send bug reports to <bug-automake@gnu.org>."
+    exit $?
     ;;
 
   -v|--v|--ve|--ver|--vers|--versi|--versio|--version)
-    echo "missing 0.4 - GNU automake"
+    echo "missing $scriptversion (GNU Automake)"
+    exit $?
     ;;
 
   -*)
@@ -87,42 +105,69 @@ Supported PROGRAM values:
     exit 1
     ;;
 
-  aclocal*)
+esac
+
+# normalize program name to check for.
+program=`echo "$1" | sed '
+  s/^gnu-//; t
+  s/^gnu//; t
+  s/^g//; t'`
+
+# Now exit if we have it, but it failed.  Also exit now if we
+# don't have it and --version was passed (most likely to detect
+# the program).  This is about non-GNU programs, so use $1 not
+# $program.
+case $1 in
+  lex*|yacc*)
+    # Not GNU programs, they don't have --version.
+    ;;
+
+  tar*)
+    if test -n "$run"; then
+       echo 1>&2 "ERROR: \`tar' requires --run"
+       exit 1
+    elif test "x$2" = "x--version" || test "x$2" = "x--help"; then
+       exit 1
+    fi
+    ;;
+
+  *)
     if test -z "$run" && ($1 --version) > /dev/null 2>&1; then
        # We have it, but it failed.
        exit 1
+    elif test "x$2" = "x--version" || test "x$2" = "x--help"; then
+       # Could not run --version or --help.  This is probably someone
+       # running `$TOOL --version' or `$TOOL --help' to check whether
+       # $TOOL exists and not knowing $TOOL uses missing.
+       exit 1
     fi
+    ;;
+esac
 
+# If it does not exist, or fails to run (possibly an outdated version),
+# try to emulate it.
+case $program in
+  aclocal*)
     echo 1>&2 "\
-WARNING: \`$1' is missing on your system.  You should only need it if
+WARNING: \`$1' is $msg.  You should only need it if
          you modified \`acinclude.m4' or \`${configure_ac}'.  You might want
          to install the \`Automake' and \`Perl' packages.  Grab them from
          any GNU archive site."
     touch aclocal.m4
     ;;
 
-  autoconf)
-    if test -z "$run" && ($1 --version) > /dev/null 2>&1; then
-       # We have it, but it failed.
-       exit 1
-    fi
-
+  autoconf*)
     echo 1>&2 "\
-WARNING: \`$1' is missing on your system.  You should only need it if
+WARNING: \`$1' is $msg.  You should only need it if
          you modified \`${configure_ac}'.  You might want to install the
          \`Autoconf' and \`GNU m4' packages.  Grab them from any GNU
          archive site."
     touch configure
     ;;
 
-  autoheader)
-    if test -z "$run" && ($1 --version) > /dev/null 2>&1; then
-       # We have it, but it failed.
-       exit 1
-    fi
-
+  autoheader*)
     echo 1>&2 "\
-WARNING: \`$1' is missing on your system.  You should only need it if
+WARNING: \`$1' is $msg.  You should only need it if
          you modified \`acconfig.h' or \`${configure_ac}'.  You might want
          to install the \`Autoconf' and \`GNU m4' packages.  Grab them
          from any GNU archive site."
@@ -130,7 +175,7 @@ WARNING: \`$1' is missing on your system.  You should only need it if
     test -z "$files" && files="config.h"
     touch_files=
     for f in $files; do
-      case "$f" in
+      case $f in
       *:*) touch_files="$touch_files "`echo "$f" |
 				       sed -e 's/^[^:]*://' -e 's/:.*//'`;;
       *) touch_files="$touch_files $f.in";;
@@ -140,13 +185,8 @@ WARNING: \`$1' is missing on your system.  You should only need it if
     ;;
 
   automake*)
-    if test -z "$run" && ($1 --version) > /dev/null 2>&1; then
-       # We have it, but it failed.
-       exit 1
-    fi
-
     echo 1>&2 "\
-WARNING: \`$1' is missing on your system.  You should only need it if
+WARNING: \`$1' is $msg.  You should only need it if
          you modified \`Makefile.am', \`acinclude.m4' or \`${configure_ac}'.
          You might want to install the \`Automake' and \`Perl' packages.
          Grab them from any GNU archive site."
@@ -155,21 +195,16 @@ WARNING: \`$1' is missing on your system.  You should only need it if
 	   while read f; do touch "$f"; done
     ;;
 
-  autom4te)
-    if test -z "$run" && ($1 --version) > /dev/null 2>&1; then
-       # We have it, but it failed.
-       exit 1
-    fi
-
+  autom4te*)
     echo 1>&2 "\
-WARNING: \`$1' is needed, and you do not seem to have it handy on your
-         system.  You might have modified some files without having the
+WARNING: \`$1' is needed, but is $msg.
+         You might have modified some files without having the
          proper tools for further handling them.
-         You can get \`$1Help2man' as part of \`Autoconf' from any GNU
+         You can get \`$1' as part of \`Autoconf' from any GNU
          archive site."
 
-    file=`echo "$*" | sed -n 's/.*--output[ =]*\([^ ]*\).*/\1/p'`
-    test -z "$file" && file=`echo "$*" | sed -n 's/.*-o[ ]*\([^ ]*\).*/\1/p'`
+    file=`echo "$*" | sed -n "$sed_output"`
+    test -z "$file" && file=`echo "$*" | sed -n "$sed_minuso"`
     if test -f "$file"; then
 	touch $file
     else
@@ -183,111 +218,108 @@ WARNING: \`$1' is needed, and you do not seem to have it handy on your
     fi
     ;;
 
-  bison|yacc)
+  bison*|yacc*)
     echo 1>&2 "\
-WARNING: \`$1' is missing on your system.  You should only need it if
+WARNING: \`$1' $msg.  You should only need it if
          you modified a \`.y' file.  You may need the \`Bison' package
          in order for those modifications to take effect.  You can get
          \`Bison' from any GNU archive site."
     rm -f y.tab.c y.tab.h
-    if [ $# -ne 1 ]; then
+    if test $# -ne 1; then
         eval LASTARG="\${$#}"
-	case "$LASTARG" in
+	case $LASTARG in
 	*.y)
 	    SRCFILE=`echo "$LASTARG" | sed 's/y$/c/'`
-	    if [ -f "$SRCFILE" ]; then
+	    if test -f "$SRCFILE"; then
 	         cp "$SRCFILE" y.tab.c
 	    fi
 	    SRCFILE=`echo "$LASTARG" | sed 's/y$/h/'`
-	    if [ -f "$SRCFILE" ]; then
+	    if test -f "$SRCFILE"; then
 	         cp "$SRCFILE" y.tab.h
 	    fi
 	  ;;
 	esac
     fi
-    if [ ! -f y.tab.h ]; then
+    if test ! -f y.tab.h; then
 	echo >y.tab.h
     fi
-    if [ ! -f y.tab.c ]; then
+    if test ! -f y.tab.c; then
 	echo 'main() { return 0; }' >y.tab.c
     fi
     ;;
 
-  lex|flex)
+  lex*|flex*)
     echo 1>&2 "\
-WARNING: \`$1' is missing on your system.  You should only need it if
+WARNING: \`$1' is $msg.  You should only need it if
          you modified a \`.l' file.  You may need the \`Flex' package
          in order for those modifications to take effect.  You can get
          \`Flex' from any GNU archive site."
     rm -f lex.yy.c
-    if [ $# -ne 1 ]; then
+    if test $# -ne 1; then
         eval LASTARG="\${$#}"
-	case "$LASTARG" in
+	case $LASTARG in
 	*.l)
 	    SRCFILE=`echo "$LASTARG" | sed 's/l$/c/'`
-	    if [ -f "$SRCFILE" ]; then
+	    if test -f "$SRCFILE"; then
 	         cp "$SRCFILE" lex.yy.c
 	    fi
 	  ;;
 	esac
     fi
-    if [ ! -f lex.yy.c ]; then
+    if test ! -f lex.yy.c; then
 	echo 'main() { return 0; }' >lex.yy.c
     fi
     ;;
 
-  help2man)
-    if test -z "$run" && ($1 --version) > /dev/null 2>&1; then
-       # We have it, but it failed.
-       exit 1
-    fi
-
+  help2man*)
     echo 1>&2 "\
-WARNING: \`$1' is missing on your system.  You should only need it if
+WARNING: \`$1' is $msg.  You should only need it if
 	 you modified a dependency of a manual page.  You may need the
 	 \`Help2man' package in order for those modifications to take
 	 effect.  You can get \`Help2man' from any GNU archive site."
 
-    file=`echo "$*" | sed -n 's/.*-o \([^ ]*\).*/\1/p'`
-    if test -z "$file"; then
-	file=`echo "$*" | sed -n 's/.*--output=\([^ ]*\).*/\1/p'`
-    fi
-    if [ -f "$file" ]; then
+    file=`echo "$*" | sed -n "$sed_output"`
+    test -z "$file" && file=`echo "$*" | sed -n "$sed_minuso"`
+    if test -f "$file"; then
 	touch $file
     else
 	test -z "$file" || exec >$file
 	echo ".ab help2man is required to generate this page"
-	exit 1
+	exit $?
     fi
     ;;
 
-  makeinfo)
-    if test -z "$run" && (makeinfo --version) > /dev/null 2>&1; then
-       # We have makeinfo, but it failed.
-       exit 1
-    fi
-
+  makeinfo*)
     echo 1>&2 "\
-WARNING: \`$1' is missing on your system.  You should only need it if
+WARNING: \`$1' is $msg.  You should only need it if
          you modified a \`.texi' or \`.texinfo' file, or any other file
          indirectly affecting the aspect of the manual.  The spurious
          call might also be the consequence of using a buggy \`make' (AIX,
          DU, IRIX).  You might want to install the \`Texinfo' package or
          the \`GNU make' package.  Grab either from any GNU archive site."
-    file=`echo "$*" | sed -n 's/.*-o \([^ ]*\).*/\1/p'`
+    # The file to touch is that specified with -o ...
+    file=`echo "$*" | sed -n "$sed_output"`
+    test -z "$file" && file=`echo "$*" | sed -n "$sed_minuso"`
     if test -z "$file"; then
-      file=`echo "$*" | sed 's/.* \([^ ]*\) *$/\1/'`
-      file=`sed -n '/^@setfilename/ { s/.* \([^ ]*\) *$/\1/; p; q; }' $file`
+      # ... or it is the one specified with @setfilename ...
+      infile=`echo "$*" | sed 's/.* \([^ ]*\) *$/\1/'`
+      file=`sed -n '
+	/^@setfilename/{
+	  s/.* \([^ ]*\) *$/\1/
+	  p
+	  q
+	}' $infile`
+      # ... or it is derived from the source name (dir/f.texi becomes f.info)
+      test -z "$file" && file=`echo "$infile" | sed 's,.*/,,;s,.[^.]*$,,'`.info
     fi
+    # If the file does not exist, the user really needs makeinfo;
+    # let's fail without touching anything.
+    test -f $file || exit 1
     touch $file
     ;;
 
-  tar)
+  tar*)
     shift
-    if test -n "$run"; then
-      echo 1>&2 "ERROR: \`tar' requires --run"
-      exit 1
-    fi
 
     # We have already tried tar in the generic part.
     # Look for gnutar/gtar before invocation to avoid ugly error
@@ -300,13 +332,13 @@ WARNING: \`$1' is missing on your system.  You should only need it if
     fi
     firstarg="$1"
     if shift; then
-	case "$firstarg" in
+	case $firstarg in
 	*o*)
 	    firstarg=`echo "$firstarg" | sed s/o//`
 	    tar "$firstarg" "$@" && exit 0
 	    ;;
 	esac
-	case "$firstarg" in
+	case $firstarg in
 	*h*)
 	    firstarg=`echo "$firstarg" | sed s/h//`
 	    tar "$firstarg" "$@" && exit 0
@@ -323,10 +355,10 @@ WARNING: I can't seem to be able to run \`tar' with the given arguments.
 
   *)
     echo 1>&2 "\
-WARNING: \`$1' is needed, and you do not seem to have it handy on your
-         system.  You might have modified some files without having the
+WARNING: \`$1' is needed, and is $msg.
+         You might have modified some files without having the
          proper tools for further handling them.  Check the \`README' file,
-         it often tells you about the needed prerequirements for installing
+         it often tells you about the needed prerequisites for installing
          this package.  You may also peek at any GNU archive site, in case
          some other package would contain this missing \`$1' program."
     exit 1
@@ -334,3 +366,11 @@ WARNING: \`$1' is needed, and you do not seem to have it handy on your
 esac
 
 exit 0
+
+# Local variables:
+# eval: (add-hook 'write-file-hooks 'time-stamp)
+# time-stamp-start: "scriptversion="
+# time-stamp-format: "%:y-%02m-%02d.%02H"
+# time-stamp-time-zone: "UTC"
+# time-stamp-end: "; # UTC"
+# End:
diff --git a/tracy/config/mkinstalldirs b/tracy/config/mkinstalldirs
index 4f58503ea4e09c65165aa1ecaeac7c2c688648f3..4191a45dbd72ecd24c25b45a53e94ea0a4b5baf7 100755
--- a/tracy/config/mkinstalldirs
+++ b/tracy/config/mkinstalldirs
@@ -1,40 +1,162 @@
 #! /bin/sh
 # mkinstalldirs --- make directory hierarchy
-# Author: Noah Friedman <friedman@prep.ai.mit.edu>
-# Created: 1993-05-16
-# Public domain
 
-# $Id: mkinstalldirs,v 1.13 1999/01/05 03:18:55 bje Exp $
+scriptversion=2009-04-28.21; # UTC
+
+# Original author: Noah Friedman <friedman@prep.ai.mit.edu>
+# Created: 1993-05-16
+# Public domain.
+#
+# This file is maintained in Automake, please report
+# bugs to <bug-automake@gnu.org> or send patches to
+# <automake-patches@gnu.org>.
 
+nl='
+'
+IFS=" ""	$nl"
 errstatus=0
+dirmode=
+
+usage="\
+Usage: mkinstalldirs [-h] [--help] [--version] [-m MODE] DIR ...
+
+Create each directory DIR (with mode MODE, if specified), including all
+leading file name components.
+
+Report bugs to <bug-automake@gnu.org>."
+
+# process command line arguments
+while test $# -gt 0 ; do
+  case $1 in
+    -h | --help | --h*)         # -h for help
+      echo "$usage"
+      exit $?
+      ;;
+    -m)                         # -m PERM arg
+      shift
+      test $# -eq 0 && { echo "$usage" 1>&2; exit 1; }
+      dirmode=$1
+      shift
+      ;;
+    --version)
+      echo "$0 $scriptversion"
+      exit $?
+      ;;
+    --)                         # stop option processing
+      shift
+      break
+      ;;
+    -*)                         # unknown option
+      echo "$usage" 1>&2
+      exit 1
+      ;;
+    *)                          # first non-opt arg
+      break
+      ;;
+  esac
+done
 
 for file
 do
-   set fnord `echo ":$file" | sed -ne 's/^:\//#/;s/^://;s/\// /g;s/^#/\//;p'`
-   shift
+  if test -d "$file"; then
+    shift
+  else
+    break
+  fi
+done
+
+case $# in
+  0) exit 0 ;;
+esac
+
+# Solaris 8's mkdir -p isn't thread-safe.  If you mkdir -p a/b and
+# mkdir -p a/c at the same time, both will detect that a is missing,
+# one will create a, then the other will try to create a and die with
+# a "File exists" error.  This is a problem when calling mkinstalldirs
+# from a parallel make.  We use --version in the probe to restrict
+# ourselves to GNU mkdir, which is thread-safe.
+case $dirmode in
+  '')
+    if mkdir -p --version . >/dev/null 2>&1 && test ! -d ./--version; then
+      echo "mkdir -p -- $*"
+      exec mkdir -p -- "$@"
+    else
+      # On NextStep and OpenStep, the `mkdir' command does not
+      # recognize any option.  It will interpret all options as
+      # directories to create, and then abort because `.' already
+      # exists.
+      test -d ./-p && rmdir ./-p
+      test -d ./--version && rmdir ./--version
+    fi
+    ;;
+  *)
+    if mkdir -m "$dirmode" -p --version . >/dev/null 2>&1 &&
+       test ! -d ./--version; then
+      echo "mkdir -m $dirmode -p -- $*"
+      exec mkdir -m "$dirmode" -p -- "$@"
+    else
+      # Clean up after NextStep and OpenStep mkdir.
+      for d in ./-m ./-p ./--version "./$dirmode";
+      do
+        test -d $d && rmdir $d
+      done
+    fi
+    ;;
+esac
+
+for file
+do
+  case $file in
+    /*) pathcomp=/ ;;
+    *)  pathcomp= ;;
+  esac
+  oIFS=$IFS
+  IFS=/
+  set fnord $file
+  shift
+  IFS=$oIFS
+
+  for d
+  do
+    test "x$d" = x && continue
+
+    pathcomp=$pathcomp$d
+    case $pathcomp in
+      -*) pathcomp=./$pathcomp ;;
+    esac
 
-   pathcomp=
-   for d
-   do
-     pathcomp="$pathcomp$d"
-     case "$pathcomp" in
-       -* ) pathcomp=./$pathcomp ;;
-     esac
+    if test ! -d "$pathcomp"; then
+      echo "mkdir $pathcomp"
 
-     if test ! -d "$pathcomp"; then
-        echo "mkdir $pathcomp"
+      mkdir "$pathcomp" || lasterr=$?
 
-        mkdir "$pathcomp" || lasterr=$?
+      if test ! -d "$pathcomp"; then
+	errstatus=$lasterr
+      else
+	if test ! -z "$dirmode"; then
+	  echo "chmod $dirmode $pathcomp"
+	  lasterr=
+	  chmod "$dirmode" "$pathcomp" || lasterr=$?
 
-        if test ! -d "$pathcomp"; then
-  	  errstatus=$lasterr
-        fi
-     fi
+	  if test ! -z "$lasterr"; then
+	    errstatus=$lasterr
+	  fi
+	fi
+      fi
+    fi
 
-     pathcomp="$pathcomp/"
-   done
+    pathcomp=$pathcomp/
+  done
 done
 
 exit $errstatus
 
-# mkinstalldirs ends here
+# Local Variables:
+# mode: shell-script
+# sh-indentation: 2
+# eval: (add-hook 'write-file-hooks 'time-stamp)
+# time-stamp-start: "scriptversion="
+# time-stamp-format: "%:y-%02m-%02d.%02H"
+# time-stamp-time-zone: "UTC"
+# time-stamp-end: "; # UTC"
+# End:
diff --git a/tracy/configure.in b/tracy/configure.in
index f8cff0e7d3e6b43afbcbbdef5de93d0fbddbda9b..f975f6f5f16471f58fe6f6c89d32a2679b117704 100755
--- a/tracy/configure.in
+++ b/tracy/configure.in
@@ -1,17 +1,21 @@
 # Process this file with autoconf to produce a configure script.
 AC_INIT(tracy/src/t2elem.cc)
 AC_CONFIG_AUX_DIR(config)
-AM_INIT_AUTOMAKE(Tracy, 3.0)
+AM_INIT_AUTOMAKE(Tracy, 3.5)
 AM_CONFIG_HEADER(config.h)
 # Checks for programs.
 AC_PROG_AWK
-AC_PROG_CC
+# Check for compiler in this order
+# icc is on the Cluster
+# gcc otherwise MAC, Linux
+AC_PROG_CC([icc gcc])
 AM_PROG_CC_STDC
 AC_PROG_INSTALL
 AC_PROG_LN_S
 AC_PROG_CPP
 AC_PROG_RANLIB
 AC_PROG_CXX(gcc)
+AM_PROG_CC_C_O
 AC_PROG_F77(gfortran)
 
 # Checks for libraries.
diff --git a/tracy/tools/Input_checkcode.prm b/tracy/tools/Input_checkcode.prm
index f087ee2a5eea5e0dfc32f22c33084b0070cf7339..b20f1a9ffa054250c7ce24f586ef9fb3f26be06c 100644
--- a/tracy/tools/Input_checkcode.prm
+++ b/tracy/tools/Input_checkcode.prm
@@ -24,12 +24,20 @@ in_dir /Users/nadolski/codes/tracy/maille/soleil/
 #  lat_file  soleil_HU36_checkcode
   lat_file  solamor2_reglage_focalisation_chcvqt_thicksextu_LQPintermediaire_QFF
 #  lat_file  modele_complet_202_317_ksi_2_2_wiggler_slicing_SX8mod
-#  
-#
+
+# multipole error file
+  multipole_file multipole_error.dat
+
+# files for looking for the multipole of corrector (Machine current based)
+  fic_hcorr corh.txt
+  fic_vcorr corv.txt
+  fic_skew  corqt.txt
+  
+
 #*******boolean flag***********
 # VACCUUM CHAMBER PART
 # vacuum chamber file
-  chamber_file /Users/nadolski/codes/tracy/TracyIII/Tracy/tools/Chamber_example.dat    
+  chamber_file Chamber_example.dat    
 # read vacuum chamber from chamber_file, ChamberFlag must be true, if 
 # ReadChamberFlag is true
   ReadChamberFlag  false
@@ -71,56 +79,77 @@ in_dir /Users/nadolski/codes/tracy/maille/soleil/
 # TurnNumber number of turn for tracking  
 # emax maximum energy for tracking
   EnergyTuneShiftFlag  true 31 516 0.06 
-#
+
 ####
 # FMA calculate frequency map 
 ####
-  FmapFlag        false
-# experiment Fmap, FmapFlag must be true if ExperimentFMAFlag is true 
-# ExperimentFMAFlag flag Nbx Nby TurnNumber xmax(m) ymax(m) energyoffset diffusionflag 
-# Nbx Nby nuber of point in h and v planes
-# TurnNumber Number of turns for tracking
-# xmax, ymax maximum amplitude
-# energyoffset 
-# diffusionflag to compute tunediffusion 
-#
-  ExperimentFMAFlag true 31 21 516 0.025 0.005 0.0 true
-# detailed Fmap, FmapFlag must be true if DetailedFMAFlag is true
-  DetailedFMAFlag  true
-#
+# FMA calculate frequency map 
+#    Nbx Nby number of point in h and v planes
+#    TurnNumber Number of turns for tracking
+#    xmax(m), ymax(m) maximum amplitude
+#    energyoffset 
+#    diffusionflag to compute tunediffusion 
+ FmapFlag false 31 21 516 0.025 0.005 0.0 true
+
+#  FMA dp calculate frequency map
+#     Nbx Nbe number of point in h and energy planes
+#     TurnNumber Number of turns for tracking
+#     xmax (m), emax maximum amplitude
+#     y-amplitude (m) 
+#     diffusionflag to compute tunediffusion 
+ FmapdpFlag false 101 121 1026 25e-3 0.06 0.3e-3 true
+
 # error coupling
-  ErrorCouplingFlag  true
+#    flag, random seed number, RMS value of the rotation angle 
+#    of the quadrupole
+  ErrorCouplingFlag true  0  0.0007
+
 # coupling flag
   CouplingFlag  true
-#
+ 
 # calculate momentum acceptance for Touscheck lifetime
-# istart istop eminp emaxp nstepp eminn emaxn nstepn
-# 
-  MomentumAccFlag false 1 108 0.01 0.05 100 -0.01 -0.05 100
-#
-#### 
+#   Dim  istart istop eminp emaxp nstepp eminn emaxn nstepn
+#   Dim: 4D/6D tracking, default value is 6D
+  MomentumAccFlag false 4D 1 209 0.01 0.05 100 -0.01 -0.05 100
+
 #### MULTIPOLE FACTORY
-# include multipole error into the lattice
-  MultipoleFlag  true 
+ # read multipole error from a file and set them to the lattice
+ ReadMultipoleFlag true
+
+#******to be obsoleted************************
+# include multipole error into the lattice, the mutipole error
+#     of Horizontal and vertical correctors, and skew quadrupole
+#      is read from the files, the name of which are set at the 
+#       beginning of this script. 
+ MultipoleFlag false
 # set multipole with thin or thick lens model,
 # MultipoleFlag must be true  if ThinsextFlag is true 
   ThinsextFlag  false
-# files for looking for the multipole of corrector (Machine current based)
-  fic_hcorr /Users/nadolski/Documents/codes/tracy/maille/soleil/corh.txt
-  fic_vcorr /Users/nadolski/Documents/codes/tracy/maille/soleil/corv.txt
-  fic_skew  /Users/nadolski/Documents/codes/tracy/maille/soleil/corqt.txt
-#
+#**************************************************
+
+###
+### Touschek lifetime
+###
+# calculate Touschek lifetime
+# name, flag
+  TouschekFlag false
+# Intra Beam Scattering, TouschekFlag must be true 
+  IBSFlag  false
+# Track momentum acceptance and then get Touschek lifetime, TouschekFlag must be true 
+  TousTrackFlag false
+
 ###
 ### FITTING FACTORY
 ###
 # fit tune
-# name   flag targetnudx    targetnudz
-  FitTuneFlag   true  18.202 10.317
-#
+# name, flag, tuned quadrople,tuned quadrople,targetnudx    targetnudz
+#  FitTuneFlag   true  q7 q9   18.202 10.317
+  FitTune4Flag  true  qp7a qp7b  qp9a qp9b  18.202 10.317
+
 # fit chromaticity
-# name   flag targetksix    targetksiz
-  FitChromFlag  true   2.0    2.6
-#
+# name,flag, tuned sextupole, tuned sextupole, targetksix    targetksiz
+  FitChromFlag  true sx9 sx10  2.0    2.6
+
 ### OTHER
 # include girder error
   GirderErrorFlag  false
diff --git a/tracy/tools/Input_test.prm b/tracy/tools/Input_test.prm
index 13fe957ad736ea4865072ddeb13a7bb3f6e3afb0..0aa91f217e3724ac383a4cbf0e603fa34eb91499 100644
--- a/tracy/tools/Input_test.prm
+++ b/tracy/tools/Input_test.prm
@@ -28,14 +28,15 @@
 #******************************************************************
 #******files********
 # relative directory of the files in the script
- in_dir /home/zhang/codes/TracyIII/lattice/   
+# in_dir /home/zhang/codes/TracyIII/lattice/   
+ in_dir /Users/nadolski/codes/tracy/maille/soleil/
 
 # lattice file must be wihout .lat extension
   lat_file  solamor2_reglage_focalisation_chcvqt_thicksextu_LQPintermediaire_QFF  
 #  lat_file  solamor2_reglage_focalisation_chcvqt_thicksextu_LQPintermediaire_QFF_FullQuad
 
 # vacuum chamber file
-  chamber_file example_Chamber.dat    
+  chamber_file Chamber_example.dat
 
 # multipole error file
   multipole_file multipole_error.dat
diff --git a/tracy/tools/Makefile.am b/tracy/tools/Makefile.am
index 6ba66a7b69b471c1e42b408650d19fb9c8f6535c..bcc75bebc05d2be5ff08b120c9c3871a2e999eb6 100644
--- a/tracy/tools/Makefile.am
+++ b/tracy/tools/Makefile.am
@@ -1,16 +1,15 @@
 #SUBDIRS = ptc
 
 #bin_PROGRAMS      = max4 
-#bin_PROGRAMS      = soltracy 
-bin_PROGRAMS      = testtracy
-#bin_PROGRAMS      = soltracy testtracy 
+bin_PROGRAMS      = soltracy3 
+#bin_PROGRAMS      = soltracy3 testtracy 
 #bin_PROGRAMS      = max4 track_fft dynap leac
 
 #max4_SOURCES      = max4.cc nrutil.c nrcheck.c nrlinwww.c   nrframe.c
 # Normal
-#soltracy_SOURCES  = soltracy.cc nrutil.c nrcheck.c nrlinwww.c   nrframe.c
+#soltracy3_SOURCES  = soltracy.cc nrutil.c nrcheck.c nrlinwww.c   nrframe.c
 # With no library
-soltracy_SOURCES  = soltracy.cc nrutil.c nrcheck.c nrlinwww.c nrframe.c ../tracy/src/tracy_lib.cc
+soltracy3_SOURCES  = soltracy.cc nrutil.c nrcheck.c nrlinwww.c nrframe.c ../tracy/src/tracy_lib.cc
 testtracy_SOURCES = testtracy.cc nrutil.c nrcheck.c nrlinwww.c nrframe.c ../tracy/src/tracy_lib.cc
 
 # these work with tracy-3.5-20090922
@@ -28,11 +27,3 @@ testtracy_SOURCES = testtracy.cc nrutil.c nrcheck.c nrlinwww.c nrframe.c ../trac
 LIBS     = -L$(NUM_REC)/lib -lrecipes_c_gcc \
 	   -lstdc++ -lgfortran
 INCLUDES = -I$(TRACY_LIB)/tracy/inc -I$(NUM_REC)/inc
-
-# METIS MAC
-FFLAGS   = -g -O2  -Wall -fbounds-check
-CXXFLAGS = -g -O2  -Wall -fno-implicit-templates
-
-#ISEI
-#FFLAGS   = -O2 -Wall -fbounds-check
-#CXXFLAGS = -O2 -Wall -fno-implicit-templates
diff --git a/tracy/tools/checkcode.sh b/tracy/tools/checkcode.sh
index a5dde86bc65f1fe76622d74664fa9f755aa1d1c7..d91336d483b7583072779c3e2e82a1b7c261559b 100755
--- a/tracy/tools/checkcode.sh
+++ b/tracy/tools/checkcode.sh
@@ -1,10 +1,12 @@
 #!/bin/bash
+#set -x # for debugging
 
 if [ $# -ne 1 ] 
 then                    # affiche l'usage
     echo "Missing parameter" 
     echo "Use: $0 diff for comparing result" 
     echo "Use: $0 compute for computing result" 
+    echo "Use: $0 overwrite for writing _new files to _ref files" 
     exit 1
 fi
 
@@ -16,7 +18,7 @@ then
 fi
 
 if [ $1 != "help" ] && [ $1 != "--help" ] && [ $1 != "compute" ] &&
- [ $1 != "diff" ]
+ [ $1 != "diff" ] && [ $1 != "overwrite" ]
 then 
     echo "Wrong Parameter"
     echo "Use: $0 diff for comparing result" 
@@ -27,7 +29,7 @@ fi
 # compute and save result in _new
 if [ $1 == "compute" ]
 then 
-soltracy Input_checkcode.prm
+soltracy3 Input_checkcode.prm
 
 CMD='mv'
 
@@ -51,4 +53,29 @@ $CMD flat_file_error_ref.dat flat_file_error_new.dat
 $CMD linlat_ref.out linlat_new.out
 $CMD chambre_ref.out chambre_new.out
 $CMD flat_file_ref.dat flat_file_new.dat
-fi
\ No newline at end of file
+fi
+
+# overwrite reference file with new files
+if [ $1 == "overwrite" ]
+then 
+
+echo "$@" | fmt 
+echo -n "$0: execute that command line? [yN](N) "
+read ans 
+case "$ans" in
+    [yY]*) 
+    CMD='mv'
+echo "overwrite reference files"
+$CMD nudx_new.out nudx_ref.out
+$CMD nudz_new.out nudz_ref.out
+$CMD nudp_new.out nudp_ref.out
+$CMD flat_file_error_new.dat flat_file_error_ref.dat
+$CMD linlat_new.out linlat_ref.out
+$CMD chambre_new.out chambre_ref.out
+$CMD flat_file_new.dat flat_file_ref.dat
+;;
+    *|"") echo "$0: NOT executing: $*" | fmt ;;
+esac
+
+fi 
+
diff --git a/tracy/tools/lance_tracy3.sh b/tracy/tools/lance_tracy3.sh
index f0ac2223f5389bc8a0e00cc0af46467601c29c68..ff0ec0d19e2612d1efefe8c21acd863e2c5a023a 100755
--- a/tracy/tools/lance_tracy3.sh
+++ b/tracy/tools/lance_tracy3.sh
@@ -1,4 +1,4 @@
-#!/bin/bash
+#!/bin/sh
 # 30 Septembre 2010, Laurent S. nadolski, Synchrotron SOLEIL
 #Option pour voir les details
 #set -x
diff --git a/tracy/tools/nrcheck.c b/tracy/tools/nrcheck.c
index aefae7ee360d670eb12e7f2bef3ce08cff1167a5..f0909ad962a553320f6b5eafeb5b472659cc6e6e 100644
--- a/tracy/tools/nrcheck.c
+++ b/tracy/tools/nrcheck.c
@@ -169,7 +169,7 @@ void File_DNR( FILE *fileptr, int argnum )
 	} else {
 		i = ferror(fileptr);
 		if (i) {
-			sprintf( ms, "file error %d(?) (arg %d)", argnum);
+			sprintf( ms, "file error %d(?) (arg %d)", argnum, argnum);
 			nrerror_DNR( ms );
 		}
 	}
diff --git a/tracy/tools/soltracy.cc b/tracy/tools/soltracy.cc
index 8fc3809378fec00cc391c74c7d25eadcd7b9cb2e..f6d8a1eb698bfcffbe82da2675f4bff245820c0e 100644
--- a/tracy/tools/soltracy.cc
+++ b/tracy/tools/soltracy.cc
@@ -2,35 +2,34 @@
 
 int no_tps = ORDER; // arbitrary TPSA order is defined locally
 
-extern bool  freq_map;
+extern bool freq_map;
 
 #include "tracy_lib.h"
 
-
 //***************************************************************************************
 //
 //  MAIN CODE
 //
 //****************************************************************************************
- int main(int argc, char *argv[])
-{
-  const long  seed = 1121;
-  iniranf(seed); setrancut(2.0);
+int main(int argc, char *argv[]) {
+  const long seed = 1121;
+  iniranf(seed);
+  setrancut(2.0);
 
   // turn on globval.Cavity_on and globval.radiation to get proper synchr radiation damping
   // IDs accounted too if: wiggler model and symplectic integrator (method = 1)
-  globval.H_exact     = false; 
-/*The following values are set in the Read_lattice( ) in soleilcommon.cc*/
-//  globval.quad_fringe = false;              // quadrupole fringe field
- // globval.radiation   = false;             // synchrotron radiation
- // globval.emittance   = false;             // emittance
- // globval.pathlength  = false; 
-//  globval.bpm         = 0;
-  
-//  const double  x_max_FMA = 10e-3,  delta_FMA = 10e-2;
-//  const int     n_x = 801, n_dp = 80, n_tr = 2048;
-  
-  double nux=0, nuz=0, ksix=0, ksiz=0;
+  globval.H_exact = false;
+  /*The following values are set in the Read_lattice( ) in soleilcommon.cc*/
+  //  globval.quad_fringe = false;              // quadrupole fringe field
+  // globval.radiation   = false;             // synchrotron radiation
+  // globval.emittance   = false;             // emittance
+  // globval.pathlength  = false;
+  //  globval.bpm         = 0;
+
+  //  const double  x_max_FMA = 10e-3,  delta_FMA = 10e-2;
+  //  const int     n_x = 801, n_dp = 80, n_tr = 2048;
+
+  double nux = 0, nuy = 0, ksix = 0, ksiy = 0;
 
   bool chroma;
   double dP = 0.0;
@@ -38,379 +37,377 @@ extern bool  freq_map;
   char str1[S_SIZE];
 
   // for time handling
-  uint32_t         start, stop;
-
- 
- /************************************************************************
-    read in files and flags
-  *************************************************************************/
-  if (argc > 1){
-    read_script(argv[1], true);}
-  else{
-       fprintf(stdout, "Not enough parameters\nSyntax is program parameterfile\n");
-       exit_(1);
+  uint32_t start, stop;
+
+  /************************************************************************
+   read in files and flags
+   *************************************************************************/
+  if (argc > 1) {
+    read_script(argv[1], true);
+  } else {
+    fprintf(stdout, "Not enough parameters\nSyntax is program parameterfile\n");
+    exit_(1);
   }
 
- /************************************************************************
-    writes flat file with all the design values of the lattice, very important file for debug
- *************************************************************************/ 
-  prtmfile("flat_file.dat"); 
-  
-  
+  /************************************************************************
+   writes flat file with all the design values of the lattice, very important file for debug
+   *************************************************************************/
+  prtmfile("flat_file.dat");
+
+  // print cod
+  getcod(dP, lastpos);
+  prt_cod("cod.out", globval.bpm, true);
+
   // Flag factory
-    
+
   //set RF voltage  
-    if (RFvoltageFlag == true){
-       printf("\nSetting RF voltage:\n");
-       printf("    Old RF voltage is: %lf [MV]\n",get_RFVoltage(ElemIndex("cav"))/1e6);
-       set_RFVoltage(ElemIndex("cav"), RFvolt); 
-       printf("    New RF voltage is: %lf [MV]\n",get_RFVoltage(ElemIndex("cav"))/1e6);
-    }
-    
-    
-    // Chamber factory
+  if (RFvoltageFlag == true) {
+    printf("\nSetting RF voltage:\n");
+    printf("    Old RF voltage is: %lf [MV]\n", get_RFVoltage(ElemIndex("cav"))
+        / 1e6);
+    set_RFVoltage(ElemIndex("cav"), RFvolt);
+    printf("    New RF voltage is: %lf [MV]\n", get_RFVoltage(ElemIndex("cav"))
+        / 1e6);
+  }
+
+  // Chamber factory
   if (ChamberFlag == false)
-     ChamberOff(); // turn off vacuum chamber setting, use the default one
+    ChamberOff(); // turn off vacuum chamber setting, use the default one
   else if (ChamberNoU20Flag == true)
-     DefineChNoU20();  // using vacuum chamber setting but without undulator U20
+    DefineChNoU20(); // using vacuum chamber setting but without undulator U20
   else if (ReadChamberFlag == true)
-     ReadCh(chamber_file); /* read vacuum chamber from a file "Apertures.dat" , soleil version*/
+    ReadCh(chamber_file); /* read vacuum chamber from a file "Apertures.dat" , soleil version*/
   PrintCh(); // print chamber into chamber.out
- 
+
   //get_matching_params_scl(); // get tunes and beta functions at entrance
   get_alphac2(); // compute up to 3rd order mcf
   //cout << endl << "computing tune shifts" << endl;
   //dnu_dA(10e-3, 5e-3, 0.002);
   //get_ksi2(0.0); // this gets the chromas and writes them into chrom2.out
 
- 
-  // compute tunes by tracking (should be the same as by DA)
+
+  // compute tunes by tracking (should be the same as by tps)
   if (TuneTracFlag == true) {
-    GetTuneTrac(1026L, 0.0, &nux, &nuz);
-    fprintf(stdout,"From tracking: nux = % f nuz = % f \n",nux,nuz);
+    GetTuneTrac(1026L, 0.0, &nux, &nuy);
+    fprintf(stdout, "From tracking: nux = % f nuz = % f \n", nux, nuy);
   }
 
   // compute chromaticities by tracking (should be the same as by DA)
-  if (ChromTracFlag == true){
-	start = stampstart();
-	GetChromTrac(2L, 1026L, 1e-5, &ksix, &ksiz);
-	stop = stampstop(start);
+  if (ChromTracFlag == true) {
+    start = stampstart();
+    GetChromTrac(2L, 1026L, 1e-5, &ksix, &ksiy);
+    stop = stampstop(start);
 
-    fprintf(stdout,"From tracking: ksix= % f ksiz= % f \n",ksix,ksiz);
+    fprintf(stdout, "From tracking: ksix= % f ksiz= % f \n", ksix, ksiy);
   }
 
+  //generic function, to fit tunes using 1 family of quadrupoles
+  if (FitTuneFlag == true) {
+    double qf_bn = 0.0, qd_bn = 0.0;
+    double qf_bn_fit = 0.0, qd_bn_fit = 0.0;
 
-   //generic function, to fit tunes using 1 family of quadrupoles
-   if (FitTuneFlag == true){
-     double qf_bn = 0.0,qd_bn = 0.0;
-     double qf_bn_fit = 0.0, qd_bn_fit = 0.0;
-   
     /* quadrupole field strength before fitting*/
-    qf_bn = Cell[Elem_GetPos(ElemIndex(qf), 1)].Elem.M->PB[HOMmax+2];
-    qd_bn = Cell[Elem_GetPos(ElemIndex(qd), 1)].Elem.M->PB[HOMmax+2];
- 
+    qf_bn = Cell[Elem_GetPos(ElemIndex(qf), 1)].Elem.M->PB[HOMmax + 2];
+    qd_bn = Cell[Elem_GetPos(ElemIndex(qd), 1)].Elem.M->PB[HOMmax + 2];
+
     /* fitting tunes*/
-    fprintf(stdout, "\n Fitting tunes: %s %s, targetnux = %f, targetnuz = %f \n",qf,qd,targetnux,targetnuz);
-    FitTune(ElemIndex(qf),ElemIndex(qd),targetnux, targetnuz);
-    
+    fprintf(stdout,
+        "\n Fitting tunes: %s %s, targetnux = %f, targetnuz = %f \n", qf, qd,
+        targetnux, targetnuz);
+    FitTune(ElemIndex(qf), ElemIndex(qd), targetnux, targetnuz);
+
     /* integrated field strength after fitting*/
-    qf_bn_fit = Cell[Elem_GetPos(ElemIndex(qf), 1)].Elem.M->PB[HOMmax+2];
-    qd_bn_fit = Cell[Elem_GetPos(ElemIndex(qd), 1)].Elem.M->PB[HOMmax+2]; 
+    qf_bn_fit = Cell[Elem_GetPos(ElemIndex(qf), 1)].Elem.M->PB[HOMmax + 2];
+    qd_bn_fit = Cell[Elem_GetPos(ElemIndex(qd), 1)].Elem.M->PB[HOMmax + 2];
     /* print out the quadrupole strengths before and after the fitting*/
-    printf("Before the fitting, the quadrupole field strength is: \n");
-    printf(" %s = %f,    %s = %f\n",qf,qf_bn,qd,qd_bn);   
-    printf("After the fitting, the quadrupole field strength is: \n");
-    printf(" %s = %f,    %s = %f\n",qf,qf_bn_fit,qd,qd_bn_fit);
-	
-    /* Compute and get Twiss parameters */		
-    Ring_GetTwiss(chroma=true, 0.0);  
-    printglob();                      /* print parameter list */
+    printf("Before the fitting, the quadrupole field strengths are: \n");
+    printf(" %s = %f,    %s = %f\n", qf, qf_bn, qd, qd_bn);
+    printf("After the fitting, the quadrupole field strengths are: \n");
+    printf(" %s = %f,    %s = %f\n", qf, qf_bn_fit, qd, qd_bn_fit);
+
+    /* Compute and get Twiss parameters */
+    Ring_GetTwiss(chroma = true, 0.0);
+    printglob(); /* print parameter list */
   }
-  
-  /* sepcific for soleil ring in which the quadrupole is cut into 2 parts*/
-  if (FitTune4Flag == true){
-    double qf1_bn = 0.0, qf2_bn = 0.0,qd1_bn = 0.0,qd2_bn = 0.0;
-    double qf1_bn_fit = 0.0, qf2_bn_fit = 0.0,qd1_bn_fit = 0.0,qd2_bn_fit = 0.0;
-   
+
+  /* specific for soleil ring in which the quadrupole is cut into 2 parts*/
+  if (FitTune4Flag == true) {
+    double qf1_bn = 0.0, qf2_bn = 0.0, qd1_bn = 0.0, qd2_bn = 0.0;
+    double qf1_bn_fit = 0.0, qf2_bn_fit = 0.0, qd1_bn_fit = 0.0, qd2_bn_fit =
+        0.0;
+
     /* quadrupole field strength before fitting*/
-    qf1_bn = Cell[Elem_GetPos(ElemIndex(qf1), 1)].Elem.M->PB[HOMmax+2];
-    qf2_bn = Cell[Elem_GetPos(ElemIndex(qf2), 1)].Elem.M->PB[HOMmax+2];
-    qd1_bn = Cell[Elem_GetPos(ElemIndex(qd1), 1)].Elem.M->PB[HOMmax+2];
-    qd2_bn = Cell[Elem_GetPos(ElemIndex(qd2), 1)].Elem.M->PB[HOMmax+2];
- 
+    qf1_bn = Cell[Elem_GetPos(ElemIndex(qf1), 1)].Elem.M->PB[HOMmax + 2];
+    qf2_bn = Cell[Elem_GetPos(ElemIndex(qf2), 1)].Elem.M->PB[HOMmax + 2];
+    qd1_bn = Cell[Elem_GetPos(ElemIndex(qd1), 1)].Elem.M->PB[HOMmax + 2];
+    qd2_bn = Cell[Elem_GetPos(ElemIndex(qd2), 1)].Elem.M->PB[HOMmax + 2];
+
     /* fitting tunes*/
-    fprintf(stdout, "\n Fitting tunes for Soleil ring: %s %s %s %s, targetnux = %f, targetnuz = %f \n",qf1,qf2,qd1,qd2,targetnux,targetnuz);
-    FitTune4(ElemIndex(qf1),ElemIndex(qf2),ElemIndex(qd1),ElemIndex(qd2),targetnux, targetnuz);
-    
+    fprintf(
+        stdout,
+        "\n Fitting tunes for Soleil ring: %s %s %s %s, targetnux = %f, targetnuz = %f \n",
+        qf1, qf2, qd1, qd2, targetnux, targetnuz);
+    FitTune4(ElemIndex(qf1), ElemIndex(qf2), ElemIndex(qd1), ElemIndex(qd2),
+        targetnux, targetnuz);
+
     /* integrated field strength after fitting*/
-    qf1_bn_fit = Cell[Elem_GetPos(ElemIndex(qf1), 1)].Elem.M->PB[HOMmax+2];
-    qf2_bn_fit = Cell[Elem_GetPos(ElemIndex(qf2), 1)].Elem.M->PB[HOMmax+2];
-    qd1_bn_fit = Cell[Elem_GetPos(ElemIndex(qd1), 1)].Elem.M->PB[HOMmax+2];
-    qd2_bn_fit = Cell[Elem_GetPos(ElemIndex(qd2), 1)].Elem.M->PB[HOMmax+2]; 
+    qf1_bn_fit = Cell[Elem_GetPos(ElemIndex(qf1), 1)].Elem.M->PB[HOMmax + 2];
+    qf2_bn_fit = Cell[Elem_GetPos(ElemIndex(qf2), 1)].Elem.M->PB[HOMmax + 2];
+    qd1_bn_fit = Cell[Elem_GetPos(ElemIndex(qd1), 1)].Elem.M->PB[HOMmax + 2];
+    qd2_bn_fit = Cell[Elem_GetPos(ElemIndex(qd2), 1)].Elem.M->PB[HOMmax + 2];
     /* print out the quadrupole strengths before and after the fitting*/
-    printf("Before the fitting, the quadrupole field strength is: \n");
-    printf("    %s = %f,    %s = %f,    %s = %f,    %s = %f\n",qf1,qf1_bn, qf2,qf2_bn,qd1,qd1_bn,qd2,qd2_bn);   
-    printf("After the fitting, the quadrupole field strength is: \n");
-    printf("    %s = %f,    %s = %f,    %s = %f,    %s = %f\n",qf1,qf1_bn_fit, qf2,qf2_bn_fit,qd1,qd1_bn_fit,qd2,qd2_bn_fit);
-	
-    /* Compute and get Twiss parameters */		
-    Ring_GetTwiss(chroma=true, 0.0);  
-    printglob();                      /* print parameter list */
+    printf("Before the fitting, the quadrupole field strengths are: \n");
+    printf("    %s = %f,    %s = %f,    %s = %f,    %s = %f\n", qf1, qf1_bn,
+        qf2, qf2_bn, qd1, qd1_bn, qd2, qd2_bn);
+    printf("After the fitting, the quadrupole field strengths are: \n");
+    printf("    %s = %f,    %s = %f,    %s = %f,    %s = %f\n", qf1,
+        qf1_bn_fit, qf2, qf2_bn_fit, qd1, qd1_bn_fit, qd2, qd2_bn_fit);
+
+    /* Compute and get Twiss parameters */
+    Ring_GetTwiss(chroma = true, 0.0);
+    printglob(); /* print parameter list */
   }
 
   /* fit the chromaticities*/
-  if (FitChromFlag == true){
-    
+  if (FitChromFlag == true) {
+
     double sxm1_bn = 0.0, sxm2_bn = 0.0;
     double sxm1_bn_fit = 0.0, sxm2_bn_fit = 0.0;
-    sxm1_bn = Cell[Elem_GetPos(ElemIndex(sxm1), 1)].Elem.M->PB[HOMmax+3];
-    sxm2_bn = Cell[Elem_GetPos(ElemIndex(sxm2), 1)].Elem.M->PB[HOMmax+3];
-    
+    sxm1_bn = Cell[Elem_GetPos(ElemIndex(sxm1), 1)].Elem.M->PB[HOMmax + 3];
+    sxm2_bn = Cell[Elem_GetPos(ElemIndex(sxm2), 1)].Elem.M->PB[HOMmax + 3];
+
     /* fit the chromaticites*/
-    fprintf(stdout, "\n Fitting chromaticities: %s %s, targetksix = %f,  targetksiz = %f\n",sxm1,sxm2,targetksix,targetksiz);
-    FitChrom(ElemIndex(sxm1),ElemIndex(sxm2), targetksix, targetksiz);
-    
-    sxm1_bn_fit = Cell[Elem_GetPos(ElemIndex(sxm1), 1)].Elem.M->PB[HOMmax+3];
-    sxm2_bn_fit = Cell[Elem_GetPos(ElemIndex(sxm2), 1)].Elem.M->PB[HOMmax+3];
+    fprintf(
+        stdout,
+        "\n Fitting chromaticities: %s %s, targetksix = %f,  targetksiz = %f\n",
+        sxm1, sxm2, targetksix, targetksiz);
+    FitChrom(ElemIndex(sxm1), ElemIndex(sxm2), targetksix, targetksiz);
+
+    sxm1_bn_fit = Cell[Elem_GetPos(ElemIndex(sxm1), 1)].Elem.M->PB[HOMmax + 3];
+    sxm2_bn_fit = Cell[Elem_GetPos(ElemIndex(sxm2), 1)].Elem.M->PB[HOMmax + 3];
     /* print out the sextupole strengths before and after the fitting*/
-    printf("Before the fitting, the sextupole field strength is: \n");
-    printf("    %s = %f,    %s = %f\n",sxm1,sxm1_bn, sxm2,sxm2_bn);   
-    printf("After the fitting, the sextupole field strength is: \n");
-    printf("    %s = %f,    %s = %f\n",sxm1,sxm1_bn_fit, sxm2,sxm2_bn_fit); 
-   
-    Ring_GetTwiss(chroma=true, 0.0);  /* Compute and get Twiss parameters */
-    printglob();                      /* print parameter list */
+    printf("Before the fitting, the sextupole field strengths are \n");
+    printf("    %s = %f,    %s = %f\n", sxm1, sxm1_bn, sxm2, sxm2_bn);
+    printf("After the fitting, the sextupole field strengths are: \n");
+    printf("    %s = %f,    %s = %f\n", sxm1, sxm1_bn_fit, sxm2, sxm2_bn_fit);
+
+    Ring_GetTwiss(chroma = true, 0.0); /* Compute and get Twiss parameters */
+    printglob(); /* print parameter list */
   }
 
   // coupling calculation
-   if (CouplingFlag == true){
-     Ring_GetTwiss(chroma=true, 0.0);  /* Compute and get Twiss parameters */
-     printlatt();                      /* dump linear lattice functions into "linlat.dat" */
-     GetEmittance(ElemIndex("cav"), true);
-     Coupling_Edwards_Teng();
-     printglob();   /* print parameter list */
-   }
+  if (CouplingFlag == true) {
+    Ring_GetTwiss(chroma = true, 0.0); /* Compute and get Twiss parameters */
+    printlatt(); /* dump linear lattice functions into "linlat.dat" */
+    GetEmittance(ElemIndex("cav"), true);
+    Coupling_Edwards_Teng();
+    printglob(); /* print parameter list */
+  }
 
   // add coupling by random rotating of the quadrupoles
-  if (ErrorCouplingFlag == true){
-    SetErr(err_seed,err_rms);
-    Ring_GetTwiss(chroma=true, 0.0);  /* Compute and get Twiss parameters */
-    printlatt();                      /* dump linear lattice functions into "linlat.dat" */
+  if (ErrorCouplingFlag == true) {
+    SetErr(err_seed, err_rms);
+    Ring_GetTwiss(chroma = true, 0.0); /* Compute and get Twiss parameters */
+    printlatt(); /* dump linear lattice functions into "linlat.dat" */
     Coupling_Edwards_Teng();
     GetEmittance(ElemIndex("cav"), true);
-    printglob();   /* print parameter list */
+    printglob(); /* print parameter list */
   }
 
   // WARNING Fit tunes and chromaticities before applying errors !!!!
   //set multipoles in all magnets
   // read multipole error from a file
-  if (ReadMultipoleFlag == true){
-      fprintf(stdout, "\n Read Multipoles file for lattice with thick sextupoles \n");
-      ReadFieldErr(multipole_file);
-      //first print the full lattice with error as a flat file
-      prtmfile("flat_file_error.dat"); // writes flat file   /* very important file for debug*/
-      Ring_GetTwiss(chroma=true, 0.0);  /* Compute and get Twiss parameters */
-      printglob();
+  if (ReadMultipoleFlag == true) {
+    fprintf(stdout,
+        "\n Read Multipoles file for lattice with thick sextupoles \n");
+    ReadFieldErr(multipole_file);
+    //first print the full lattice with error as a flat file
+    prtmfile("flat_file_error.dat"); // writes flat file   /* very important file for debug*/
+    Ring_GetTwiss(chroma = true, 0.0); /* Compute and get Twiss parameters */
+    printglob();
   }
-  
-  
+
   //Old version to multipole errors in soleil lattice, is obsoleted
-  if (MultipoleFlag == true ){
-    if (ThinsextFlag ==true){
-      fprintf(stdout, "\n Setting Multipoles for lattice with thin sextupoles \n");
-      Multipole_thinsext(fic_hcorr,fic_vcorr,fic_skew);  /* for thin sextupoles */
+  if (MultipoleFlag == true) {
+    if (ThinsextFlag == true) {
+      fprintf(stdout,
+          "\n Setting Multipoles for lattice with thin sextupoles \n");
+      Multipole_thinsext(fic_hcorr, fic_vcorr, fic_skew); /* for thin sextupoles */
       prtmfile("flat_file_error.dat"); // writes flat file   /* very important file for debug*/
-      Ring_GetTwiss(chroma=true, 0.0);  /* Compute and get Twiss parameters */
-      printglob(); 
-     }
-    else{
-      fprintf(stdout, "\n Setting Multipoles for lattice with thick sextupoles \n");
-      Multipole_thicksext(fic_hcorr,fic_vcorr,fic_skew);  /* for thick sextupoles */
+      Ring_GetTwiss(chroma = true, 0.0); /* Compute and get Twiss parameters */
+      printglob();
+    } else {
+      fprintf(stdout,
+          "\n Setting Multipoles for lattice with thick sextupoles \n");
+      Multipole_thicksext(fic_hcorr, fic_vcorr, fic_skew); /* for thick sextupoles */
       prtmfile("flat_file_error.dat"); // writes flat file   /* very important file for debug*/
-      Ring_GetTwiss(chroma=true, 0.0);  /* Compute and get Twiss parameters */
-      printglob(); 
+      Ring_GetTwiss(chroma = true, 0.0); /* Compute and get Twiss parameters */
+      printglob();
     }
   }
 
- 
-  
- /******************************************************************************************/
- // COMPUTATION PART after setting the model
- /******************************************************************************************/
-
-  
-
-// computes TuneShift with amplitudes
-  if (AmplitudeTuneShiftFlag == true){
-    if (ChamberFlag == true ){
-    	NuDx(_AmplitudeTuneShift_nxpoint,
-	         _AmplitudeTuneShift_nypoint, _AmplitudeTuneShift_nturn,
-	         _AmplitudeTuneShift_xmax, _AmplitudeTuneShift_ymax,
-	         _AmplitudeTuneShift_delta);
+  /******************************************************************************************/
+  // COMPUTATION PART after setting the model
+  /******************************************************************************************/
+
+  // computes TuneShift with amplitudes
+  if (AmplitudeTuneShiftFlag == true) {
+    if (ChamberFlag == true) {
+      NuDx(_AmplitudeTuneShift_nxpoint, _AmplitudeTuneShift_nypoint,
+          _AmplitudeTuneShift_nturn, _AmplitudeTuneShift_xmax,
+          _AmplitudeTuneShift_ymax, _AmplitudeTuneShift_delta);
       //NuDx(31L,21L,516L,0.025,0.005,dP);
-      }
-      else{ // Utility ?
-        NuDx(50L,30L,516L,0.035,0.02,dP);
-      }
+    } else { // Utility ?
+      NuDx(50L, 30L, 516L, 0.035, 0.02, dP);
+    }
 
   }
-  if (EnergyTuneShiftFlag == true){
-    if (ChamberFlag == true ){
-    	NuDp(_EnergyTuneShift_npoint,
-    	     _EnergyTuneShift_nturn, _EnergyTuneShift_deltamax);
+  if (EnergyTuneShiftFlag == true) {
+    if (ChamberFlag == true) {
+      NuDp(_EnergyTuneShift_npoint, _EnergyTuneShift_nturn,
+          _EnergyTuneShift_deltamax);
       //NuDp(31L,1026L,0.06);
-      }
-      else{ // utility ?
-        NuDp(31L,1026L,0.06);
-      }
+    } else { // utility ?
+      NuDp(31L, 1026L, 0.06);
+    }
 
   }
 
- // Computes FMA
-  if (FmapFlag == true){
-	fmap( _FmapFlag_nxpoint, _FmapFlag_nypoint,
-          		_FmapFlag_nturn, _FmapFlag_xmax, _FmapFlag_ymax,
-          		_FmapFlag_delta, _FmapFlag_diffusion);
-      }
- 
-// Compute FMA dp 
-  if (FmapdpFlag == true){
-	fmapdp( _FmapdpFlag_nxpoint, _FmapdpFlag_nepoint,
-          		_FmapdpFlag_nturn, _FmapdpFlag_xmax, _FmapdpFlag_emax,
-          		_FmapdpFlag_z, _FmapdpFlag_diffusion);
-      }     
-      
-      
-  if (CodeComparaisonFlag){
-          fmap(200,100,1026,-32e-3,7e-3,0.0,true);
+  // Computes FMA
+  if (FmapFlag == true) {
+    fmap(_FmapFlag_nxpoint, _FmapFlag_nypoint, _FmapFlag_nturn, _FmapFlag_xmax,
+        _FmapFlag_ymax, _FmapFlag_delta, _FmapFlag_diffusion);
   }
 
-  // MOMENTUM ACCEPTANCE
-  if (MomentumAccFlag == true){
-    	  
-          bool cavityflag, radiationflag;
-	  /* record the initial values*/
-	  cavityflag = globval.Cavity_on;  
-          radiationflag = globval.radiation;
-          
-	  /* set the dimension for the momentum tracking*/
-	  if(strncmp("6D",TrackDim,2)==0){
-	    globval.Cavity_on = true;
-	    globval.radiation = true;
-	  }
-	  else if(strncmp("4D",TrackDim,2)==0){
-	    globval.Cavity_on = false;
-	    globval.radiation = false;
-	  }
-	  else{
-	    printf("MomentumAccFlag: Error!!! DimTrack must be '4D' or '6D'\n");
-	    exit_(1);
-	  };
-	  
-	  /* calculate momentum accepetance*/
-	  MomentumAcceptance(
-	  _MomentumAccFlag_istart, _MomentumAccFlag_istop,
-	  _MomentumAccFlag_deltaminp, _MomentumAccFlag_deltamaxp, _MomentumAccFlag_nstepp,
-	  _MomentumAccFlag_deltaminn, _MomentumAccFlag_deltamaxn, _MomentumAccFlag_nstepn);
-  
-	  /* restore the initial values*/
-	  globval.Cavity_on = cavityflag;  
-          globval.radiation = radiationflag;
+  // Compute FMA dp
+  if (FmapdpFlag == true) {
+    fmapdp(_FmapdpFlag_nxpoint, _FmapdpFlag_nepoint, _FmapdpFlag_nturn,
+        _FmapdpFlag_xmax, _FmapdpFlag_emax, _FmapdpFlag_z,
+        _FmapdpFlag_diffusion);
   }
 
+  if (CodeComparaisonFlag) {
+    fmap(200, 100, 1026, -32e-3, 7e-3, 0.0, true);
+  }
+
+  // MOMENTUM ACCEPTANCE
+  if (MomentumAccFlag == true) {
+
+    bool cavityflag, radiationflag;
+    /* record the initial values*/
+    cavityflag = globval.Cavity_on;
+    radiationflag = globval.radiation;
+
+    /* set the dimension for the momentum tracking*/
+    if (strncmp("6D", TrackDim, 2) == 0) {
+      globval.Cavity_on = true;
+      globval.radiation = true;
+    } else if (strncmp("4D", TrackDim, 2) == 0) {
+      globval.Cavity_on = false;
+      globval.radiation = false;
+    } else {
+      printf("MomentumAccFlag: Error!!! DimTrack must be '4D' or '6D'\n");
+      exit_(1);
+    };
+
+    /* calculate momentum accepetance*/
+    MomentumAcceptance(_MomentumAccFlag_istart, _MomentumAccFlag_istop,
+        _MomentumAccFlag_deltaminp, _MomentumAccFlag_deltamaxp,
+        _MomentumAccFlag_nstepp, _MomentumAccFlag_deltaminn,
+        _MomentumAccFlag_deltamaxn, _MomentumAccFlag_nstepn);
+
+    /* restore the initial values*/
+    globval.Cavity_on = cavityflag;
+    globval.radiation = radiationflag;
+  }
 
   // induced amplitude 
-  if (InducedAmplitudeFlag == true){
-      InducedAmplitude(193L);  
+  if (InducedAmplitudeFlag == true) {
+    InducedAmplitude(193L);
   }
-  
-  if (EtaFlag == true){
-  // compute cod and twiss parameters for different energy offsets    
-    for (int ii=0; ii<=40; ii++) { 
-    dP = -0.02+ 0.001*ii;
-    Ring_GetTwiss(chroma=false, dP);   /* Compute and get Twiss parameters */
-    printlatt();                      /* dump linear lattice functions into "linlat.dat" */
-    getcod (dP, lastpos);
-//     printcod();
-    prt_cod("cod.out", globval.bpm, true);
-    //system("mv linlat.out linlat_ooo.out"); 
-    sprintf(str1, "mv cod.out cod_%02d.out", ii); 
-    system(str1);
-    sprintf(str1, "mv linlat.out linlat_%02d.out", ii); 
-    system(str1);
+
+  if (EtaFlag == true) {
+    // compute cod and twiss parameters for different energy offsets
+    for (int ii = 0; ii <= 40; ii++) {
+      dP = -0.02 + 0.001 * ii;
+      Ring_GetTwiss(chroma = false, dP); /* Compute and get Twiss parameters */
+      printlatt(); /* dump linear lattice functions into "linlat.dat" */
+      getcod(dP, lastpos);
+      //     printcod();
+      prt_cod("cod.out", globval.bpm, true);
+      //system("mv linlat.out linlat_ooo.out");
+      sprintf(str1, "mv cod.out cod_%02d.out", ii);
+      system(str1);
+      sprintf(str1, "mv linlat.out linlat_%02d.out", ii);
+      system(str1);
     }
-}    
-  
-
-  if (PhaseSpaceFlag == true){
-		start = stampstart();
-		Phase(0.001,0,0.001,0,0.001,0, 1);
-	    printf("the simulation time for phase space in tracy 3 is \n");
-		stop = stampstop(start);
   }
-  
 
+  if (PhaseSpaceFlag == true) {
+    start = stampstart();
+    Phase(0.001, 0, 0.001, 0, 0.001, 0, 1);
+    printf("the simulation time for phase space in tracy 3 is \n");
+    stop = stampstop(start);
+  }
+
+  //  ????????????? NSRL version, Check with Soleil version "MomentumAcceptance"
+  // IBS & TOUSCHEK
+  int k, n_turns;
+  double sigma_s, sigma_delta, tau, alpha_z, beta_z, gamma_z, eps[3];
+  FILE *outf;
+  const double Qb = 5e-9; // e charge in one bunch
 
- //  ????????????? NSRL version, Check with Soleil version "MomentumAcceptance"
- // IBS & TOUSCHEK  
-  int     k, n_turns;
-  double  sigma_s, sigma_delta, tau, alpha_z, beta_z, gamma_z, eps[3];
-  FILE    *outf;
-  const double  Qb = 5e-9;   // e charge in one bunch 
-  
   if (TouschekFlag == true) {
-    double  sum_delta[globval.Cell_nLoc+1][2];
-    double  sum2_delta[globval.Cell_nLoc+1][2];
-    
+    double sum_delta[globval.Cell_nLoc + 1][2];
+    double sum2_delta[globval.Cell_nLoc + 1][2];
+
     GetEmittance(ElemIndex("cav"), true);
-    
+
     // initialize momentum aperture arrays
-    for(k = 0; k <= globval.Cell_nLoc; k++){
-      sum_delta[k][0] = 0.0; sum_delta[k][1] = 0.0;
-      sum2_delta[k][0] = 0.0; sum2_delta[k][1] = 0.0;
+    for (k = 0; k <= globval.Cell_nLoc; k++) {
+      sum_delta[k][0] = 0.0;
+      sum_delta[k][1] = 0.0;
+      sum2_delta[k][0] = 0.0;
+      sum2_delta[k][1] = 0.0;
     }
-    
+
     globval.eps[Y_] = 0.008e-9;
-     n_turns = 40;               
-    
-    
+    n_turns = 40;
+
     // get the twiss parameters
-    alpha_z =
-             -globval.Ascr[ct_][ct_]*globval.Ascr[delta_][ct_]
-             -globval.Ascr[ct_][delta_]*globval.Ascr[delta_][delta_];
+    alpha_z = -globval.Ascr[ct_][ct_] * globval.Ascr[delta_][ct_]
+        - globval.Ascr[ct_][delta_] * globval.Ascr[delta_][delta_];
     beta_z = sqr(globval.Ascr[ct_][ct_]) + sqr(globval.Ascr[ct_][delta_]);
-    gamma_z = (1+sqr(alpha_z))/beta_z;
-    
-    sigma_delta = sqrt(gamma_z*globval.eps[Z_]);
-    sigma_s = sqrt(beta_z*globval.eps[Z_]);//50e-3
-    beta_z = sqr(sigma_s)/globval.eps[Z_];
-    alpha_z = sqrt(beta_z*gamma_z-1);
+    gamma_z = (1 + sqr(alpha_z)) / beta_z;
+
+    sigma_delta = sqrt(gamma_z * globval.eps[Z_]);
+    sigma_s = sqrt(beta_z * globval.eps[Z_]);//50e-3
+    beta_z = sqr(sigma_s) / globval.eps[Z_];
+    alpha_z = sqrt(beta_z * gamma_z - 1);
 
     // INCLUDE LC (LC changes sigma_s and eps_z, but has no influence on sigma_delta)
     if (false) {
-      double  newLength, bunchLengthening;
+      double newLength, bunchLengthening;
       newLength = 50e-3;
-      bunchLengthening = newLength/sigma_s;
+      bunchLengthening = newLength / sigma_s;
       sigma_s = newLength;
-      globval.eps[Z_] = globval.eps[Z_]*bunchLengthening;
-      beta_z = beta_z*bunchLengthening;
-      gamma_z = gamma_z/bunchLengthening;
-      alpha_z = sqrt(beta_z*gamma_z-1);  // this doesn't change
+      globval.eps[Z_] = globval.eps[Z_] * bunchLengthening;
+      beta_z = beta_z * bunchLengthening;
+      gamma_z = gamma_z / bunchLengthening;
+      alpha_z = sqrt(beta_z * gamma_z - 1); // this doesn't change
     }
-    
+
     Touschek(Qb, globval.delta_RF, globval.eps[X_], globval.eps[Y_],
-	     sigma_delta, sigma_s);
-    
-    
+        sigma_delta, sigma_s);
+
     // Intra Beam Scattering(IBS)
-    if (IBSFlag == true) {       
+    if (IBSFlag == true) {
       // initialize eps_IBS with eps_SR
-      for(k = 0; k < 3; k++)
-	eps[k] = globval.eps[k];
-      for(k = 0; k < 20; k++) //prototype (looping because IBS routine doesn't check convergence)
-	IBS(Qb, globval.eps, eps, alpha_z, beta_z);
-     }
-    
+      for (k = 0; k < 3; k++)
+        eps[k] = globval.eps[k];
+      for (k = 0; k < 20; k++) //prototype (looping because IBS routine doesn't check convergence)
+        IBS(Qb, globval.eps, eps, alpha_z, beta_z);
+    }
 
     // TOUSCHEK TRACKING
     // Calculate Touschek lifetime
@@ -419,26 +416,25 @@ extern bool  freq_map;
     // at each element location which is tracked over n turns, 
     //the vacuum chamber is read from the file "chamber_file"  
     // finally, write the momentum acceptance to file "mom_aper.out".
-    if (TousTrackFlag == true) {       
+    if (TousTrackFlag == true) {
       globval.Aperture_on = true;
-      ReadCh(chamber_file); 
-//      LoadApers("/home/simon/projects/src/lattice/Apertures.dat", 1, 1);
-      tau = Touschek(Qb, globval.delta_RF, false,
-		     globval.eps[X_], globval.eps[Y_],
-		     sigma_delta, sigma_s,
-		     n_turns, true, sum_delta, sum2_delta); //the TRUE flag requires apertures loaded
-      
-      printf("Touschek lifetime = %10.3e hrs\n", tau/3600.0);
-      
+      ReadCh(chamber_file);
+      //      LoadApers("/home/simon/projects/src/lattice/Apertures.dat", 1, 1);
+      tau = Touschek(Qb, globval.delta_RF, false, globval.eps[X_],
+          globval.eps[Y_], sigma_delta, sigma_s, n_turns, true, sum_delta,
+          sum2_delta); //the TRUE flag requires apertures loaded
+
+      printf("Touschek lifetime = %10.3e hrs\n", tau / 3600.0);
+
       outf = file_write("mom_aper.out");
-      for(k = 0; k <= globval.Cell_nLoc; k++)
-	fprintf(outf, "%4d %7.2f %5.3f %6.3f\n",
-		k, Cell[k].S, 1e2*sum_delta[k][0], 1e2*sum_delta[k][1]);
+      for (k = 0; k <= globval.Cell_nLoc; k++)
+        fprintf(outf, "%4d %7.2f %5.3f %6.3f\n", k, Cell[k].S, 1e2
+            * sum_delta[k][0], 1e2 * sum_delta[k][1]);
       fclose(outf);
     }
-  
+
   }
-  
+
   return 0;
-}    
+}
 
diff --git a/tracy/tools/testtracy.cc b/tracy/tools/testtracy.cc
index 8ac5b639e162f1a6934e6625dc9407f7eb5a051f..9cf76bfd506f835f1824ce8bc590d2c1a8ecd5be 100644
--- a/tracy/tools/testtracy.cc
+++ b/tracy/tools/testtracy.cc
@@ -5,9 +5,148 @@ int no_tps = ORDER; // arbitrary TPSA order is defined locally
 extern bool  freq_map;
 
 #include "tracy_lib.h"
-//#include "time.h"
-#include <sys/time.h>
 
+
+double get_RFVoltage(const int Fnum){
+
+    double V_RF = 0.0;
+    bool prt = true;
+
+	V_RF = Cell[Elem_GetPos(Fnum, 1)].Elem.C->Pvolt; //RF voltage in Volts
+    if (prt) fprintf(stdout, "RF voltage of cavity %s is %f MV \n",
+    		Cell[Elem_GetPos(Fnum, 1)].Elem.PName, V_RF/1e6);
+	return V_RF;
+}
+
+void set_RFVoltage(const int Fnum, const double V_RF){
+	int k, n = 0;
+
+	n = GetnKid(Fnum);
+	for (k=1; k <=n; k++){
+		Cell[Elem_GetPos(Fnum, k)].Elem.C->Pvolt = V_RF; // in Volts
+	}
+	fprintf(stdout, "Setting cavity %s to %f MV \n",
+			Cell[Elem_GetPos(Fnum, 1)].Elem.PName, V_RF/1e6);
+};
+
+void compare_cod(void)
+{
+   const double dPmin = 1e-10, dPmax = 1e-6;
+   int k;
+   const int kmax = 20;
+   double dp, dpstep = dPmax/kmax;
+   FILE * outf;
+   const char fic[] = "compare_cod.out";
+   long lastpos = 0L;
+   Vector        vector_findcod;
+
+   /* Opening file */
+   if ((outf = fopen(fic, "w")) == NULL) {
+     fprintf(stdout, "compare_cod: error while opening file %s\n", fic);
+     exit_(1);
+   }
+   fprintf(stdout,"\n");
+
+   for (k = 0; k <= kmax; k++){
+	   dp = dPmin + k*dpstep;
+	   getcod(dp, lastpos); // get cod for printout
+	   CopyVec(6, globval.CODvect, vector_findcod);
+	   findcod(dp);
+//	    fprintf(stdout,"%14.6e %14.6e %14.6e %14.6e %14.6e %14.6e %14.6e %14.6e %14.6e\n",
+//	            dp, globval.CODvect[0], vector_findcod[0], globval.CODvect[1],vector_findcod[1],
+//	            globval.CODvect[2], vector_findcod[2], globval.CODvect[3], vector_findcod[3]);
+	    fprintf(stdout,"%14.6e %14.6e %14.6e %14.6e %14.6e %14.6e %14.6e %14.6e %14.6e\n",
+	            dp,
+	            globval.CODvect[0], (globval.CODvect[0]-vector_findcod[0])/globval.CODvect[0],
+	            globval.CODvect[1], (globval.CODvect[1]-vector_findcod[1])/globval.CODvect[1],
+	            globval.CODvect[2], (globval.CODvect[2]-vector_findcod[2])/globval.CODvect[2],
+	            globval.CODvect[3], (globval.CODvect[3]-vector_findcod[3])/globval.CODvect[3]);
+   }
+   fclose(outf);
+}
+
+#define LOG10 log(10.0)
+
+void Getchrom2(double dP)
+{
+	  long lastpos = 0L;
+	  double dPlocal = 0.0, expo = 0.0, TEMP = 0.0, TEMPX = 0.0, TEMPZ = 0.0;
+	  Vector2 alpha={0.0,0.0}, beta={0.0,0.0}, gamma={0.0,0.0}, nu={0.0,0.0},
+	          nu0={0.0,0.0}, Chrom={0.0,0.0};
+	  trace = false;
+	  if (dP != 0.0) {
+	    fprintf(stderr,"Ring_Getchrom: Warning this is NOT the CHROMA, dP=%e\n",dP);
+	  }
+
+	  /* initialization */
+	  globval.Chrom[0] = 1e38;
+	  globval.Chrom[1] = 1e38;
+
+	  expo = log(globval.dPcommon) / LOG10;
+	  do
+	  {
+	    Chrom[0] = globval.Chrom[0];
+	    Chrom[1] = globval.Chrom[1];
+
+	    dPlocal = exp(expo*LOG10);
+
+	    /* Get cod for energy dP - dPlocal*/
+	    GetCOD(globval.CODimax, globval.CODeps, dP - dPlocal*0.5,
+	                 lastpos);
+
+	    if (!status.codflag)
+	    { /* if no cod */
+	      fprintf(stderr,"Ring_Getchrom:  Lattice is unstable for dP - dPlocal=% .5e\n",
+	              dP - dPlocal*0.5);
+	      return;
+	    }
+
+	    /* get tunes for energy dP - dPlocal/2 from oneturn matrix */
+	    Cell_GetABGN(globval.OneTurnMat, alpha, beta, gamma, nu0);
+
+	    /* Get cod for energy dP + dPlocal*/
+	    GetCOD(globval.CODimax, globval.CODeps, dP + dPlocal*0.5,
+	                lastpos);
+
+	    if (!status.codflag) { /* if no cod */
+	      fprintf(stderr,"Ring_Getchrom  Lattice is unstable for dP + dPlocal=% .5e \n",
+	              dP + dPlocal*0.5);
+	      return;
+	    }
+	    /* get tunes for energy dP + dPlocal/2 from oneturn matrix */
+	    Cell_GetABGN(globval.OneTurnMat, alpha, beta, gamma, nu);
+
+	    if (!globval.stable) {
+	      printf("Ring_Getchrom:  Lattice is unstable\n");
+	    }
+
+	    /* Get chromaticities by numerical differentiation*/
+	    globval.Chrom[0] = (nu[0] - nu0[0]) / dPlocal;
+	    globval.Chrom[1] = (nu[1] - nu0[1]) / dPlocal;
+
+	    TEMP=sqrt(
+	    fabs(globval.Chrom[0]*globval.Chrom[0]- Chrom[0]*Chrom[0])
+	     +fabs(globval.Chrom[1]*globval.Chrom[1]- Chrom[1]*Chrom[1])
+	    );
+	    TEMPX = sqrt(fabs(globval.Chrom[0]*globval.Chrom[0]- Chrom[0]*Chrom[0]));
+	    TEMPZ = sqrt(fabs(globval.Chrom[1]*globval.Chrom[1]- Chrom[1]*Chrom[1]));
+	    // TEST CHROMA convergence
+	  if (trace) {
+	  fprintf(stdout,"\nexpo % e xix = % e xiz = % e TEMP = %e TEMPX %+e TEMPZ %+e\n",
+	      expo,Chrom[0],Chrom[1],TEMP, TEMPX, TEMPZ);
+	  fprintf(stdout,"expo % e nux = % e nuz = % e dPlocal= %+e\n",
+	      expo,nu0[0],nu0[1],dP-0.5*dPlocal);
+	  fprintf(stdout,"expo % e nux = % e nuz = % e dPlocal= %+e\n",
+	      expo,nu[0],nu[1],dP+0.5*dPlocal);
+	    }
+	  fprintf(stdout, "%+e %+.12e %+.12e %+.12e %+.12e\n", dPlocal,
+			  globval.Chrom[0], fabs(globval.Chrom[0]-Chrom[0])/Chrom[0],
+			  globval.Chrom[1], fabs(globval.Chrom[1]-Chrom[1])/Chrom[1]);
+	  expo += 0.1;
+	  } while (expo<-2);
+	  status.chromflag = true;
+
+}
 //***************************************************************************************
 //
 //  MAIN CODE
@@ -16,89 +155,55 @@ extern bool  freq_map;
  int main(int argc, char *argv[])
 {
   const long  seed = 1121;
-  const bool All = TRUE;
   iniranf(seed); setrancut(2.0);
 
   // turn on globval.Cavity_on and globval.radiation to get proper synchr radiation damping
   // IDs accounted too if: wiggler model and symplectic integrator (method = 1)
   globval.H_exact     = false; 
-  globval.quad_fringe = false;                // quadrupole fringe field
-  
-  globval.radiation   = false;                // synchrotron radiation
-  globval.emittance   = false;                 // emittance
+  globval.quad_fringe = false;              // quadrupole fringe field
+  globval.radiation   = false;             // synchrotron radiation
+  globval.emittance   = false;             // emittance
   globval.pathlength  = false; 
 //  globval.bpm         = 0;
   
- 
-  // overview, on energy: 25-15
-  //const double  x_max_FMA = 20e-3, y_max_FMA = 10e-3; //const x_max_FMA = 25e-3, y_max_FMA = 15e-3;
-  //const int     n_x = 80, n_y = 80, n_tr = 2048;
-  // overview, off energy: 10-10
-  const double  x_max_FMA = 10e-3, delta_FMA = 10e-2;
-  const int     n_x = 80, n_dp = 80, n_tr = 2048;
-  //
-  // zoom, on energy: 8-2.5
-  //const double  x_max_FMA = 8e-3, y_max_FMA = 2.5e-3;
-  //const int     n_x = 64, n_y = 15, n_tr = 2048;
-  // zoom, off energy: 7-3
-  //const double  x_max_FMA = 3e-3, delta_FMA = 7e-2;
-  //const int     n_x = 28, n_dp = 56, n_tr = 2048;
+//  const double  x_max_FMA = 10e-3,  delta_FMA = 10e-2;
+//  const int     n_x = 801, n_dp = 80, n_tr = 2048;
   
   double nux=0, nuz=0, ksix=0, ksiz=0;
-  
+
   bool chroma;
   double dP = 0.0;
   long lastpos = -1L;
   char str1[S_SIZE];
-  
+
+  // for time handling
+  uint32_t         start, stop;
+
   /************************************************************************
       start read in files and flags
   *************************************************************************/
-  read_script(argv[1], true);
+  if (argc > 1){
+  read_script(argv[1], true);}
+  else{
+	  fprintf(stdout, "Not enough parameters\nSyntax is program parameterfile\n");
+	  return 1;
+  }
+
 
 
  /************************************************************************
     end  read in files and flags
   *************************************************************************/
-    
-  
-  
-  
-  
-  
-//  if (true)
-//  //  Read_Lattice("/home/nadolski/codes/tracy/maille/soleil/solamor2_tracy3"); 
-//    Read_Lattice(argv[1]); //sets some globval params
-//  else
-//    rdmfile("flat_file.dat"); //instead of reading lattice file, get data from flat file 
-
-  //no_sxt(); //turns off sextupoles
- // Ring_GetTwiss(true, 0e-2); //gettwiss computes one-turn matrix arg=(w or w/o chromat, dp/p) 
-  //get_matching_params_scl();
-  //get_alphac2();
-  //GetEmittance(ElemIndex("cav"), true);
-  
-//prt_lat("linlat.out", globval.bpm, true);  /* print lattice file for nsrl-ii*/
-prtmfile("flat_file.dat"); // writes flat file   /* very important file for debug*/
-//prt_chrom_lat(); //writes chromatic functions into chromlat.out
-//  printlatt();  /* print out lattice functions */
- 
-
-/* print lattice file */
-//  prt_lat("linlatBNL.out", globval.bpm, All); // BNL print for all elements
+  prtmfile("flat_file.dat"); // writes flat file   /* very important file for debug*/
   printlatt();  /* SOLEIL print out lattice functions */
   printglob();
   
-  
-  
-    // Flag factory
-//  bool TuneTracFlag = true; 
-//  bool ChromTracFlag = true;
-  
-  
-  //*************************************************************
-  //=============================================================
+  double V_RF;
+  V_RF = get_RFVoltage(ElemIndex("cav"));
+  set_RFVoltage(ElemIndex("cav"), 3e6); // 3 MV
+  V_RF = get_RFVoltage(ElemIndex("cav"));
 
+    // Flag factory
     
     // Chamber factory
   if (ChamberFlag == false)
@@ -106,10 +211,15 @@ prtmfile("flat_file.dat"); // writes flat file   /* very important file for debu
   else if (ChamberNoU20Flag == true)
      DefineChNoU20();  // using vacuum chamber setting but without undulator U20
   else if (ReadChamberFlag == true)
-     ReadCh(chamber_file); /* read vacuum chamber from a file "chamber_file" , soleil version*/
-//LoadApers("Apertures.dat", 1.0, 1.0);  /* read vacuum chamber definition for bnl */
-  PrintCh();
+     ReadCh(chamber_file); /* read vacuum chamber from a file "Apertures.dat" , soleil version*/
+  PrintCh(); // print chamber into chamber.out
  
+  //get_matching_params_scl(); // get tunes and beta functions at entrance
+  get_alphac2(); // compute up to 3rd order mcf
+  //cout << endl << "computing tune shifts" << endl;
+  //dnu_dA(10e-3, 5e-3, 0.002);
+  //get_ksi2(0.0); // this gets the chromas and writes them into chrom2.out
+
  
   // compute tunes by tracking (should be the same as by DA)
   if (TuneTracFlag == true) {
@@ -119,7 +229,10 @@ prtmfile("flat_file.dat"); // writes flat file   /* very important file for debu
 
   // compute chromaticities by tracking (should be the same as by DA)
   if (ChromTracFlag == true){
-    GetChromTrac(2L, 1026L, 1e-5, &ksix, &ksiz);
+	start = stampstart();
+	GetChromTrac(2L, 1026L, 1e-5, &ksix, &ksiz);
+	stop = stampstop(start);
+
     fprintf(stdout,"From tracking: ksix= % f ksiz= % f \n",ksix,ksiz);
   }
 
@@ -138,12 +251,11 @@ prtmfile("flat_file.dat"); // writes flat file   /* very important file for debu
     printglob();                      /* print parameter list */
   }
 
-    //SetKLpar(ElemIndex("QT"), 1, 2L,   0.001026770838382);
-  
   // coupling calculation
    if (CouplingFlag == true){
      Ring_GetTwiss(chroma=true, 0.0);  /* Compute and get Twiss parameters */
      printlatt();                      /* dump linear lattice functions into "linlat.dat" */
+     GetEmittance(ElemIndex("cav"), true);
      Coupling_Edwards_Teng();
      printglob();   /* print parameter list */
    }
@@ -154,6 +266,7 @@ prtmfile("flat_file.dat"); // writes flat file   /* very important file for debu
     Ring_GetTwiss(chroma=true, 0.0);  /* Compute and get Twiss parameters */
     printlatt();                      /* dump linear lattice functions into "linlat.dat" */
     Coupling_Edwards_Teng();
+    GetEmittance(ElemIndex("cav"), true);
     printglob();   /* print parameter list */
   }
 
@@ -162,41 +275,63 @@ prtmfile("flat_file.dat"); // writes flat file   /* very important file for debu
   if (MultipoleFlag == true ){
     if (ThinsextFlag ==true){
       fprintf(stdout, "\n Setting Multipoles for lattice with thin sextupoles \n");
-      Multipole_thinsext();  /* for thin sextupoles */
-      
+      Multipole_thinsext(fic_hcorr,fic_vcorr,fic_skew);  /* for thin sextupoles */
       Ring_GetTwiss(chroma=true, 0.0);  /* Compute and get Twiss parameters */
       printglob(); 
      }
     else{
       fprintf(stdout, "\n Setting Multipoles for lattice with thick sextupoles \n");
-      Multipole_thicksext();  /* for thick sextupoles */
-      
+      Multipole_thicksext(fic_hcorr,fic_vcorr,fic_skew);  /* for thick sextupoles */
       Ring_GetTwiss(chroma=true, 0.0);  /* Compute and get Twiss parameters */
       printglob(); 
     }
   }
-                       /* print parameter list */
-  
 
-  // PX2 chicane
-//  if (PX2Flag ==true){
-//  setPX2chicane(); 
-//  //get closed orbit    
-//  getcod (0.0, &lastpos);
-//  printcod();
-//  Ring_GetTwiss(chroma=true, 0.0);  /* Compute and get Twiss parameters */
-//  printglob();                      /* print parameter list */
-//  }
-  
+ /******************************************************************************************/
+ // COMPUTATION PART after setting the model
+ /******************************************************************************************/
+
+  //first print the full lattice with error as a flat file
+  prtmfile("flat_file_error.dat"); // writes flat file   /* very important file for debug*/
+
+// computes TuneShift with amplitudes
+  if (AmplitudeTuneShiftFlag == true){
+    if (ChamberFlag == true ){
+    	NuDx(_AmplitudeTuneShift_nxpoint,
+	         _AmplitudeTuneShift_nypoint, _AmplitudeTuneShift_nturn,
+	         _AmplitudeTuneShift_xmax, _AmplitudeTuneShift_ymax,
+	         _AmplitudeTuneShift_delta);
+      //NuDx(31L,21L,516L,0.025,0.005,dP);
+      }
+      else{ // Utility ?
+        NuDx(50L,30L,516L,0.035,0.02,dP);
+      }
+
+  }
+  if (EnergyTuneShiftFlag == true){
+    if (ChamberFlag == true ){
+    	NuDp(_EnergyTuneShift_npoint,
+    	     _EnergyTuneShift_nturn, _EnergyTuneShift_deltamax);
+      //NuDp(31L,1026L,0.06);
+      }
+      else{ // utility ?
+        NuDp(31L,1026L,0.06);
+      }
+
+  }
+
  // Computes FMA
   if (FmapFlag == true){
     if (ChamberFlag == true ){
       if (ExperimentFMAFlag == true)
-         fmap(40,12,258,-20e-3,5e-3,0.0,true); // for experimental
+          fmap( _FmapFlag_nxpoint, _FmapFlag_nypoint,
+          		_FmapFlag_nturn, _FmapFlag_xmax, _FmapFlag_ymax,
+          		_FmapFlag_delta, _FmapFlag_diffusion);
+    	  //fmap(40,12,258,-20e-3,5e-3,0.0,true); // for experimental
       if (DetailedFMAFlag == true)
         fmap(100,50,1026,20e-3,5e-3,0.0,true);
       }
-      else{
+      else{ // Utility
         if (ExperimentFMAFlag == true)
           fmap(40,12,258,-32e-3,5e-3,0.0,true);
         if (DetailedFMAFlag == true)
@@ -205,34 +340,18 @@ prtmfile("flat_file.dat"); // writes flat file   /* very important file for debu
   }
   
   if (CodeComparaisonFlag){
-          // SOLEIL
-          fmap(100,50,1026,32e-3,7e-3,0.0,true);
-          //fmap(200,100,1026,-32e-3,7e-3,0.0,true);
+          fmap(200,100,1026,-32e-3,7e-3,0.0,true);
   }
 
+  // MOMENTUM ACCEPTANCE
   if (MomentumAccFlag == true){
-    //MomentumAcceptance(10L, 28L, 0.01, 0.05, 4L, -0.01, -0.05, 4L);
-     MomentumAcceptance(1L, 28L, 0.01, 0.05, 40L, -0.01, -0.05, 40L);
-  //  MomentumAcceptance(1L, 108L, 0.01, 0.05, 100L, -0.01, -0.05, 100L);
+	  MomentumAcceptance(
+	  _MomentumAccFlag_istart, _MomentumAccFlag_istop,
+	  _MomentumAccFlag_deltaminp, _MomentumAccFlag_deltamaxp, _MomentumAccFlag_nstepp,
+	  _MomentumAccFlag_deltaminn, _MomentumAccFlag_deltamaxn, _MomentumAccFlag_nstepn);
+	 // MomentumAcceptance(1L, 108L, 0.01, 0.05, 100L, -0.01, -0.05, 100L);
   }
 
-  // computes Tuneshift with amplitudes
-  if (TuneShiftFlag == true){
-    if (ChamberFlag == true ){
-      NuDx(31L,21L,516L,0.025,0.005,dP);
-      //NuDp(31L,516L,0.06);
-      //NuDp(31L,1026L,0.06);
-      }
-      else{
-        NuDx(50L,30L,516L,0.035,0.02,dP);
-        NuDp(31L,1026L,0.06);
-      }
-
-  }
- 
-//  if (SigmaFlag == true){printsigma();
-//  }
-//  
 
   // induced amplitude 
   if (InducedAmplitudeFlag == true){
@@ -258,136 +377,16 @@ prtmfile("flat_file.dat"); // writes flat file   /* very important file for debu
   
 
   if (PhaseSpaceFlag == true){
-     int   t_sec,t_usec,t_msec; 
-     struct timeval tv,tv1;
-     struct timezone tz,tz1 ;
-     struct tm *tm,*tm1;
-     gettimeofday(&tv, &tz);
-     tm=localtime(&tv.tv_sec);
-     
-     t_sec = - tm->tm_sec;
-     printf(" %d:%02d:%02d %d \n", tm->tm_hour, tm->tm_min,
-             tm->tm_sec, tv.tv_usec);
-
-      Phase(0.001,0,0.001,0,0.001,0, 1);
-      
-       gettimeofday(&tv1, &tz1);
-       tm1=localtime(&tv1.tv_sec);
-     
-       t_sec += tm->tm_sec;
-       t_usec = tv1.tv_usec -  tv.tv_usec; 
-       t_msec = t_sec*1000 + t_usec/1000;
-         
-       
-      printf(" %d:%02d:%02d %d \n", tm1->tm_hour, tm1->tm_min,
-             tm1->tm_sec, tv1.tv_usec);
-      
-     
-       printf("%d %d %d \n",t_sec*1000,t_usec/1000, t_msec);
-     printf("the simulation time for phase space in tracy 3 is %ld milliseconds\n",t_msec);  
-   
-  } 
-  
-  //
-  // IBS & TOUSCHEK
-  //
-  int     k, n_turns;
-  double  sigma_s, sigma_delta, tau, alpha_z, beta_z, gamma_z, eps[3];
-  FILE    *outf;
-  const double  Qb = 5e-9;   // e charge in one bunch 
-  
-  if (TouschekFlag == true) {
-    double  sum_delta[globval.Cell_nLoc+1][2];
-    double  sum2_delta[globval.Cell_nLoc+1][2];
-    
-    GetEmittance(ElemIndex("cav"), true);
-    
-    // initialize momentum aperture arrays
-    for(k = 0; k <= globval.Cell_nLoc; k++){
-      sum_delta[k][0] = 0.0; sum_delta[k][1] = 0.0;
-      sum2_delta[k][0] = 0.0; sum2_delta[k][1] = 0.0;
-    }
-    //sigma_delta = 7.70e-04;      //410:7.70e-4,  411:9.57e-4,  412:9.12e-4
-    //globval.eps[X_] = 0.326e-9;  //410:3.26e-10, 411:2.63e-10, 412:2.01e-10
-    globval.eps[Y_] = 0.008e-9;
-    //sigma_s = 9.73e-3;           //410:9.73e-3,  411:12.39e-3, 412:12.50e-3/10.33e-3
-    //globval.eps[Z_] = sigma_delta*sigma_s;
-    //globval.delta_RF given by cav voltage in lattice file
-     //globval.delta_RF = 6.20e-2; //410:6.196e-2, 411:5.285e-2, 412:4.046e-2/5.786e-2
-   // n_turns = 490;               //410:490(735), 411:503(755), 412:439(659)/529(794)
-     n_turns = 40;               //410:490(735), 411:503(755), 412:439(659)/529(794)
-    
-    
-    // get the twiss parameters
-    alpha_z =
-             -globval.Ascr[ct_][ct_]*globval.Ascr[delta_][ct_]
-             -globval.Ascr[ct_][delta_]*globval.Ascr[delta_][delta_];
-    beta_z = sqr(globval.Ascr[ct_][ct_]) + sqr(globval.Ascr[ct_][delta_]);
-    gamma_z = (1+sqr(alpha_z))/beta_z;
-    
-    sigma_delta = sqrt(gamma_z*globval.eps[Z_]);
-    sigma_s = sqrt(beta_z*globval.eps[Z_]);//50e-3
-    beta_z = sqr(sigma_s)/globval.eps[Z_];
-    alpha_z = sqrt(beta_z*gamma_z-1);
-
-    // INCLUDE LC (LC changes sigma_s and eps_z, but has no influence on sigma_delta)
-    if (false) {
-      double  newLength, bunchLengthening;
-      newLength = 50e-3;
-      bunchLengthening = newLength/sigma_s;
-      sigma_s = newLength;
-      globval.eps[Z_] = globval.eps[Z_]*bunchLengthening;
-      beta_z = beta_z*bunchLengthening;
-      gamma_z = gamma_z/bunchLengthening;
-      alpha_z = sqrt(beta_z*gamma_z-1);  // this doesn't change
-    }
-    
-    //globval.eps[X_] = 0.362e-9;
-    //sigma_delta = 1.04e-3;
-    //sigma_s = 14.8e-3;
-    Touschek(Qb, globval.delta_RF, globval.eps[X_], globval.eps[Y_],
-	     sigma_delta, sigma_s);
-    
-    
-    // Intra Beam Scattering(IBS)
-    if (IBSFlag == true) {       
-      // initialize eps_IBS with eps_SR
-      for(k = 0; k < 3; k++)
-	eps[k] = globval.eps[k];
-      for(k = 0; k < 20; k++) //prototype (looping because IBS routine doesn't check convergence)
-	IBS(Qb, globval.eps, eps, alpha_z, beta_z);
-     }
-    
-
-    // TOUSCHEK TRACKING
-    // Calculate Touschek lifetime
-    // with the momentum acceptance which is determined by 
-    // the RF acceptance delta_RF and the momentum aperture 
-    // at each element location which is tracked over n turns, 
-    //the vacuum chamber is read from the file "chamber_file"  
-    // finally, write the momentum acceptance to file "mom_aper.out".
-    if (TousTrackFlag == true) {       
-      globval.Aperture_on = true;
-      ReadCh(chamber_file); 
-//      LoadApers("/home/simon/projects/src/lattice/Apertures.dat", 1, 1);
-      tau = Touschek(Qb, globval.delta_RF, false,
-		     globval.eps[X_], globval.eps[Y_],
-		     sigma_delta, sigma_s,
-		     n_turns, true, sum_delta, sum2_delta); //the TRUE flag requires apertures loaded
-      
-      printf("Touschek lifetime = %10.3e hrs\n", tau/3600.0);
-      
-      outf = file_write("mom_aper.out");
-      for(k = 0; k <= globval.Cell_nLoc; k++)
-	fprintf(outf, "%4d %7.2f %5.3f %6.3f\n",
-		k, Cell[k].S, 1e2*sum_delta[k][0], 1e2*sum_delta[k][1]);
-      fclose(outf);
-    }
-  
+		start = stampstart();
+		Phase(0.001,0,0.001,0,0.001,0, 1);
+	    printf("the simulation time for phase space in tracy 3 is \n");
+		stop = stampstop(start);
   }
   
-  
-  
+  //compare_cod();
+  Getchrom2(0.0);
+  return 0;
+
    /*********************************************************************************
          Delicated for max4 lattice. To load alignment error files and do correction
   ----------------------------------------------------------------------------------
diff --git a/tracy/tracy/inc/radia2tracy.h b/tracy/tracy/inc/radia2tracy.h
index d821faa37a3c4b53e080944cf15aaae5f655cf7f..f7ea768f0cbd4ec08f3c2b669178f9a4e2c25442 100644
--- a/tracy/tracy/inc/radia2tracy.h
+++ b/tracy/tracy/inc/radia2tracy.h
@@ -20,7 +20,7 @@ template<typename T>
 void SplineInterpolation2(T &X, T &Z, T &thetax, T &thetaz,
 			  CellType &Cell, bool &out);
 
-void Matrices4Spline(InsertionType *WITH);
+void Matrices4Spline(InsertionType *WITH, int Order);
 
 template<typename T>
 void spline(const double x[], const T y[], int const n,
diff --git a/tracy/tracy/inc/tracy_global.h b/tracy/tracy/inc/tracy_global.h
index b45859a3fe8a6ec098842eb0f58b379fa597e8f8..b044732c2e71a856519353573af98d50f0254765 100644
--- a/tracy/tracy/inc/tracy_global.h
+++ b/tracy/tracy/inc/tracy_global.h
@@ -153,21 +153,27 @@ struct FieldMapType {
 struct InsertionType {
   int Pmethod;      /* Integration Method */
   int PN;           /* number of integration steps */
-  char fname1[100]; /* Filename for insertion description: first ordre */
-  char fname2[100]; /* Filename for insertion description: second ordre */
-  int nx;           /* Horizontal point number */
-  int nz;           /* Vertical point number */
-  double scaling;   /* static scaling factor as in BETA ESRF*/
+  char fname1[100]; /* Filename for insertion description: first order */
+  char fname2[100]; /* Filename for insertion description: second order */
+  int nx1;           /* Horizontal point number */
+  int nx2;           /* Horizontal point number */
+  int nz1;           /* Vertical point number */
+  int nz2;           /* Vertical point number */
+  double scaling1;   /* static scaling factor as in BETA ESRF first order*/
+  double scaling2;   /* static scaling factor as in BETA ESRF second order*/
   bool linear;      /* if true linear interpolation else spline */
   bool firstorder;  /* true if first order kick map loaded */
   bool secondorder; /* true if second order kick map loaded */
-  double tabx[IDXMAX]; /* spacing in H-plane */
-  double tabz[IDZMAX]; /* spacing in V-plane */
-  double thetax[IDZMAX][IDXMAX], thetax1[IDZMAX][IDXMAX]; /* 1 for 1st order */
-  double thetaz[IDZMAX][IDXMAX], thetaz1[IDZMAX][IDXMAX];
-  double **tx, **tz, **f2x, **f2z;
-  double **tx1, **tz1, **f2x1, **f2z1; // a voir
-  double *tab1, *tab2; // tab of x and z meshes from Radia code
+  double tabx1[IDXMAX]; /* spacing in H-plane */
+  double tabz1[IDZMAX]; /* spacing in V-plane */
+  double tabx2[IDXMAX]; /* spacing in H-plane */
+  double tabz2[IDZMAX]; /* spacing in V-plane */
+  double thetax2[IDZMAX][IDXMAX], thetax1[IDZMAX][IDXMAX]; /* 1 for 1st order */
+  double thetaz2[IDZMAX][IDXMAX], thetaz1[IDZMAX][IDXMAX];
+  double **tx2, **tz2, **f2x2, **f2z2; // used for splie2 and splin2 (Spline interpolation)
+  double **tx1, **tz1, **f2x1, **f2z1; // used for splie2 and splin2
+  double *TabxOrd1, *TabzOrd1; // tab of x and z meshes from Radia code in increasing order
+  double *TabxOrd2, *TabzOrd2; // tab of x and z meshes from Radia code in increasing order
   
   /* Displacement Error */
   Vector2 PdSsys;   /* systematic [m]  */
@@ -178,12 +184,6 @@ struct InsertionType {
   double PdTsys;    /* systematic [deg] */
   double PdTrms;    /* rms [deg] */
   double PdTrnd;    /* random number */
-//  /* Strength */
-//  double Plperiod;  /* Length Period [m] */
-//  int Pnperiod;    /* Number of periods */
-//  double PBoBrho;   /* B/Brho */
-//  double PKx;       /* kx */
-//  mpolArray PBW;
   Matrix K55;        /* Transport matrix:kick part */
   Matrix D55;        /* Transport matrix:drift part */
   Matrix KD55;       /* Transport matrix:concatenation of kicks and drifts */
diff --git a/tracy/tracy/src/Makefile.am b/tracy/tracy/src/Makefile.am
index 9b0524e0421bf837bff7133c2f991f2c62504ba9..7a6a30c85d6c686dc4b5087701b219490060f90b 100755
--- a/tracy/tracy/src/Makefile.am
+++ b/tracy/tracy/src/Makefile.am
@@ -1,12 +1,17 @@
 lib_LIBRARIES          = libtracy.a libtracy_ptc.a
 
 libtracy_a_SOURCES     = tracy_lib.cc
+libtracy_a_CXXFLAGS    = -fPIC $(AM_CXXFLAGS)
 
 libtracy_ptc_a_SOURCES = tracy_ptc_lib.cc
+libtracy_ptc_a_CXXFLAGS    = -fPIC $(AM_CXXFLAGS)
 
 INCLUDES = -I../inc -I$(NUM_REC)/inc
 #INCLUDES = -I../inc -I$(NUM_REC)/inc \
 #	   -I/usr/include/c++/3.3.6
 
-CXXFLAGS = -g -O0 -Wall -fno-implicit-templates -fPIC
-#CXXFLAGS = -g -O2 -Wall -frepo
+# MAC METIS
+#CXXFLAGS = -g -O2 -Wall -fno-implicit-templates -fPIC
+
+# ISEI
+#CXXFLAGS = -O2 -Wall -fno-implicit-templates -fPIC
diff --git a/tracy/tracy/src/Makefile.ref b/tracy/tracy/src/Makefile.ref
deleted file mode 100755
index 30b62ee4fc5d965afdf4fcc64d0dbbfbeebe4df1..0000000000000000000000000000000000000000
--- a/tracy/tracy/src/Makefile.ref
+++ /dev/null
@@ -1,10 +0,0 @@
-lib_LIBRARIES = libtracy.a
-
-libtracy_a_SOURCES = tracy_lib.cc \
-                     ../../TPSA/TPSALib.f ../../TPSA/LieLib.f
-
-INCLUDES = -I../inc -I$(NUM_REC)/inc \
-	   -I/usr/include/c++/3.3.6
-
-CXXFLAGS = -g -O2 -Wall -fno-implicit-templates
-#CXXFLAGS = -g -O2 -Wall -frepo
diff --git a/tracy/tracy/src/nsls-ii_lib.cc b/tracy/tracy/src/nsls-ii_lib.cc
index 4833dfea43c393dc717518e45059ab1809cc6e66..5f90c09bfea0aed752bc0f81beb5d96c5b982687 100644
--- a/tracy/tracy/src/nsls-ii_lib.cc
+++ b/tracy/tracy/src/nsls-ii_lib.cc
@@ -2233,7 +2233,7 @@ void set_ID_scl(const int Fnum, const int Knum, const double scl)
     }
     break;
   case Insertion:
-    Cell[Elem_GetPos(Fnum, Knum)].Elem.ID->scaling = scl;
+    Cell[Elem_GetPos(Fnum, Knum)].Elem.ID->scaling1 = scl;
     break;
   case FieldMap:
     Cell[Elem_GetPos(Fnum, Knum)].Elem.FM->scl = scl;
@@ -3118,7 +3118,7 @@ void get_IDs(void)
       break;
     case Insertion:
       printf("found ID family:   %s %12.5e\n",
-	     ElemFam[k].ElemF.PName, ElemFam[k].ElemF.ID->scaling);
+	     ElemFam[k].ElemF.PName, ElemFam[k].ElemF.ID->scaling1);
       n_ID_Fams++; ID_Fams[n_ID_Fams-1] = k + 1;
       break;
     case FieldMap:
@@ -4882,10 +4882,11 @@ void get_alphac2(void)
       alphac[n-1] = x[ct_]/Cell.S;
   }
   pol_fit(n, delta, alphac, 3, b, sigma);
-  printf("\n");
   printf("Momentum compact factor:\n");
-  printf("alphac = %10.3e + %10.3e*delta + %10.3e*delta^2\n\n",
+  printf("   alphac = %10.3e + %10.3e*delta + %10.3e*delta^2\n",
 	 b[1], b[2], b[3]);
+  printf("   alpha1 = %10.3e  alpha2 = %10.3e  alpha3= %10.3e\n\n",
+     b[1], b[2]/2, b[3]/3);
 }
 
 
diff --git a/tracy/tracy/src/physlib.cc b/tracy/tracy/src/physlib.cc
index 863775cc231bbe5984eb951bad927d662e22e470..53497a0b6c35b34d2c67a3f4770be8849d3b2752 100644
--- a/tracy/tracy/src/physlib.cc
+++ b/tracy/tracy/src/physlib.cc
@@ -1,101 +1,91 @@
 /* Tracy-2
 
-   J. Bengtsson, CBP, LBL      1990 - 1994   Pascal version
-                 SLS, PSI      1995 - 1997
-   M. Boege      SLS, PSI      1998          C translation
-   L. Nadolski   SOLEIL        2002          Link to NAFF, Radia field maps
-   J. Bengtsson  NSLS-II, BNL  2004 -        
-
-*/
+ J. Bengtsson, CBP, LBL      1990 - 1994   Pascal version
+ SLS, PSI      1995 - 1997
+ M. Boege      SLS, PSI      1998          C translation
+ L. Nadolski   SOLEIL        2002          Link to NAFF, Radia field maps
+ J. Bengtsson  NSLS-II, BNL  2004 -
 
+ */
 
 /**************************/
 /* Routines for printing  */
 /**************************/
 
 /**** same as asctime in C without the \n at the end****/
-char *asctime2(const struct tm *timeptr)
-{
+char *asctime2(const struct tm *timeptr) {
     // terminated with \0.
-    static char wday_name[7][4] = {
-        "Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"
-    };
+    static char wday_name[7][4] = { "Sun", "Mon", "Tue", "Wed", "Thu", "Fri",
+            "Sat" };
     // terminated with \0.
-    static char mon_name[12][4] = {
-        "Jan", "Feb", "Mar", "Apr", "May", "Jun",
-        "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"
-    };
+    static char mon_name[12][4] = { "Jan", "Feb", "Mar", "Apr", "May", "Jun",
+            "Jul", "Aug", "Sep", "Oct", "Nov", "Dec" };
     static char result[26];
 
     sprintf(result, "%.3s %.3s%3d %.2d:%.2d:%.2d %d",
-        wday_name[timeptr->tm_wday],
-        mon_name[timeptr->tm_mon],
-        timeptr->tm_mday, timeptr->tm_hour,
-        timeptr->tm_min, timeptr->tm_sec,
-        1900 + timeptr->tm_year);
+            wday_name[timeptr->tm_wday], mon_name[timeptr->tm_mon],
+            timeptr->tm_mday, timeptr->tm_hour, timeptr->tm_min,
+            timeptr->tm_sec, 1900 + timeptr->tm_year);
     return result;
 }
 
 /** Get time and date **/
-struct tm* GetTime()
-{
-  struct tm *whattime;
-  /* Get time and date */
-  time_t aclock;
-  time(&aclock);                 /* Get time in seconds */
-  whattime = localtime(&aclock);  /* Convert time to struct */
-  return whattime;
+struct tm* GetTime() {
+    struct tm *whattime;
+    /* Get time and date */
+    time_t aclock;
+    time(&aclock); /* Get time in seconds */
+    whattime = localtime(&aclock); /* Convert time to struct */
+    return whattime;
 }
 /****************************************************************************
  * uint32_t stampstart()
 
 
-   Purpose: record time in millliseconds
+ Purpose: record time in millliseconds
 
-   Input:
-       none
+ Input:
+ none
 
-   Output:
-       non
+ Output:
+ non
 
-   Return:
-       time in milliseconds
+ Return:
+ time in milliseconds
 
-   Global variables:
-       none
+ Global variables:
+ none
 
-   specific functions:
-       none
+ specific functions:
+ none
 
-   Comments:
-       to be used with stampstop()
+ Comments:
+ to be used with stampstop()
 
-****************************************************************************/
+ ****************************************************************************/
 
-uint32_t stampstart(void)
-{
-	struct timeval  tv;
-	struct timezone tz;
-	struct tm      *tm;
-	uint32_t         start;
-	const bool timedebug = false;
+uint32_t stampstart(void) {
+    struct timeval tv;
+    struct timezone tz;
+    struct tm *tm;
+    uint32_t start;
+    const bool timedebug = false;
 
-	// get the time
-	gettimeofday(&tv, &tz);
-	tm = localtime(&tv.tv_sec);
+    // get the time
+    gettimeofday(&tv, &tz);
+    tm = localtime(&tv.tv_sec);
 
-	// print detailed time in milliseconds
+    // print detailed time in milliseconds
     if (timedebug)
-	printf("TIMESTAMP-START\t  %d:%02d:%02d:%d (~%d ms)\n", tm->tm_hour,
-	       tm->tm_min, tm->tm_sec, tv.tv_usec,
-	       tm->tm_hour * 3600 * 1000 + tm->tm_min * 60 * 1000 +
-	       tm->tm_sec * 1000 + tv.tv_usec / 1000);
+        printf("TIMESTAMP-START\t  %d:%02d:%02d:%d (~%d ms)\n", tm->tm_hour,
+                tm->tm_min, tm->tm_sec, tv.tv_usec, tm->tm_hour * 3600 * 1000
+                        + tm->tm_min * 60 * 1000 + tm->tm_sec * 1000
+                        + tv.tv_usec / 1000);
 
+    start = tm->tm_hour * 3600 * 1000 + tm->tm_min * 60 * 1000 + tm->tm_sec
+            * 1000 + tv.tv_usec / 1000;
 
-	start = tm->tm_hour * 3600 * 1000 + tm->tm_min * 60 * 1000 +
-		tm->tm_sec * 1000 + tv.tv_usec / 1000;
-
-	return (start);
+    return (start);
 
 }
 
@@ -103,3408 +93,3269 @@ uint32_t stampstart(void)
 /****************************************************************************
  * uint32_t stampstop(uint32_t start)
 
-   Purpose: compute time elapsed since start time
+ Purpose: compute time elapsed since start time
 
-   Input:
-       start starting time i millisecond
+ Input:
+ start starting time i millisecond
 
-   Output:
-       none
+ Output:
+ none
 
-   Return:
-       none
+ Return:
+ none
 
-   Global variables:
-       none
+ Global variables:
+ none
 
-   specific functions:
-       none
+ specific functions:
+ none
 
-   Comments:
-       to be used with stampstart
+ Comments:
+ to be used with stampstart
 
-****************************************************************************/
-uint32_t stampstop(uint32_t start)
-{
+ ****************************************************************************/
+uint32_t stampstop(uint32_t start) {
+
+    struct timeval tv;
+    struct timezone tz;
+    struct tm *tm;
+    uint32_t stop;
+    const bool timedebug = false;
+    bool prt = false;
+    // get the time
+    gettimeofday(&tv, &tz);
+    tm = localtime(&tv.tv_sec);
 
-	struct timeval  tv;
-	struct timezone tz;
-	struct tm      *tm;
-	uint32_t         stop;
-	const bool timedebug = false;
-	bool prt = false;
-	// get the time
-	gettimeofday(&tv, &tz);
-	tm = localtime(&tv.tv_sec);
-
-	stop = tm->tm_hour * 3600 * 1000 + tm->tm_min * 60 * 1000 +
-		tm->tm_sec * 1000 + tv.tv_usec / 1000;
-
-	// print detailed time in milliseconds
-	if (timedebug){
-	printf("TIMESTAMP-END\t  %d:%02d:%02d:%d (~%d ms) \n", tm->tm_hour,
-	       tm->tm_min, tm->tm_sec, tv.tv_usec,
-	       tm->tm_hour * 3600 * 1000 + tm->tm_min * 60 * 1000 +
-	       tm->tm_sec * 1000 + tv.tv_usec / 1000);
-	printf("ELAPSED\t  %d ms\n", stop - start);
-	}
-
-	uint32_t delta, hour, minute, second, millisecond;
-	delta = stop - start;
-	hour = delta/3600000;
-	minute = (delta-3600000*hour)/60000;
-	second = (delta-3600000*hour-minute*60000)/1000;
-	millisecond = delta-3600000*hour-minute*60000-second*1000;
-         
-	if(prt)
-	printf("ELAPSED\t  %d h %d min %d s %d ms\n",
-			hour, minute, second, millisecond);
-
-	return (stop);
+    stop = tm->tm_hour * 3600 * 1000 + tm->tm_min * 60 * 1000 + tm->tm_sec
+            * 1000 + tv.tv_usec / 1000;
+
+    // print detailed time in milliseconds
+    if (timedebug) {
+        printf("TIMESTAMP-END\t  %d:%02d:%02d:%d (~%d ms) \n", tm->tm_hour,
+                tm->tm_min, tm->tm_sec, tv.tv_usec, tm->tm_hour * 3600 * 1000
+                        + tm->tm_min * 60 * 1000 + tm->tm_sec * 1000
+                        + tv.tv_usec / 1000);
+        printf("ELAPSED\t  %d ms\n", stop - start);
+    }
+
+    uint32_t delta, hour, minute, second, millisecond;
+    delta = stop - start;
+    hour = delta / 3600000;
+    minute = (delta - 3600000 * hour) / 60000;
+    second = (delta - 3600000 * hour - minute * 60000) / 1000;
+    millisecond = delta - 3600000 * hour - minute * 60000 - second * 1000;
+
+    if (prt)
+        printf("ELAPSED\t  %d h %d min %d s %d ms\n", hour, minute, second,
+                millisecond);
+
+    return (stop);
 
 }
 /****************************************************************************/
 /* void printglob(void)
 
-   Purpose:
-       Print global variables on screen
-       Print tunes and chromaticities
-       Print Oneturn matrix
-
-   Input:
-       none
-
-   Output:
-       output on the screen
-
-   Return:
-       none
-
-   Global variables:
-       globval
-
-   Specific functions:
-       none
-
-   Comments:
-       26/03/03 Oneturn matrix added
-       26/03/03 RF acceptance added
-       10/05/03 Momentum compaction factor added
-       16/05/03 Correction for a asymmetrical vaccum vessel
-       20/06/03 Add corrector, skew quad and bpm number
-       27/10/03 Add flag for radiation and chambre
-       
-       Comments copied from Tracy 2.7(soleil),Written by L.Nadolski.
-       
-****************************************************************************/
-void printglob(void)
-{
-  printf("\n***************************************************************"
-	 "***************\n");
-  printf("\n");
-  printf("  dPcommon     =  %9.3e  dPparticle   =  %9.3e"
-	 "  Energy [GeV] = %.3f\n",
-         globval.dPcommon, globval.dPparticle, globval.Energy);
-  printf("  MaxAmplx [m] = %9.3e  MaxAmply [m] = %9.3e"
-	 "  RFAccept [%%] = \xB1%4.2f\n",
-         Cell[0].maxampl[X_][1], Cell[0].maxampl[Y_][1],
-	 globval.delta_RF*1e2);
-  printf("  MatMeth      =  %s     ", globval.MatMeth ? "TRUE " : "FALSE");
-  printf(" Cavity_On    =  %s    ", globval.Cavity_on ? "TRUE " : "FALSE");
-  printf("  Radiation_On = %s     \n",
-	 globval.radiation ? "TRUE " : "FALSE");
-  printf("  bpm          =  %3d        qt           = %3d        ",
-	 GetnKid(globval.bpm),GetnKid(globval.qt) );
-  printf(" Chambre_On   = %s     \n", status.chambre ? "TRUE " : "FALSE");
-  printf("  hcorr        =  %3d        vcorr        = %3d\n\n",
-	 GetnKid(globval.hcorr), GetnKid(globval.vcorr));
-  printf("  alphac       =   %8.4e\n", globval.Alphac); 
-  printf("  nux          =  %13.6f      nuz  =  %13.6f",
-         globval.TotalTune[X_], globval.TotalTune[Y_]);
-  if (globval.Cavity_on)
-    printf("  omega  = %13.9f\n", globval.Omega);
-  else {
+ Purpose:
+ Print global variables on screen
+ Print tunes and chromaticities
+ Print Oneturn matrix
+
+ Input:
+ none
+
+ Output:
+ output on the screen
+
+ Return:
+ none
+
+ Global variables:
+ globval
+
+ Specific functions:
+ none
+
+ Comments:
+ 26/03/03 Oneturn matrix added
+ 26/03/03 RF acceptance added
+ 10/05/03 Momentum compaction factor added
+ 16/05/03 Correction for a asymmetrical vaccum vessel
+ 20/06/03 Add corrector, skew quad and bpm number
+ 27/10/03 Add flag for radiation and chambre
+
+ Comments copied from Tracy 2.7(soleil),Written by L.Nadolski.
+
+ ****************************************************************************/
+void printglob(void) {
+    printf("\n***************************************************************"
+        "***************\n");
     printf("\n");
-    printf("  ksix         = %13.6f                ksiz = %13.6f\n",
-            globval.Chrom[X_], globval.Chrom[Y_]);
-  }
-  printf("\n");
-  printf("  OneTurn matrix:\n");
-  printf("\n");
-  prtmat(ss_dim, globval.OneTurnMat);
-  fflush(stdout);
-}
+    printf("  dPcommon     =  %9.3e  dPparticle   =  %9.3e"
+        "  Energy [GeV] = %.3f\n", globval.dPcommon, globval.dPparticle,
+            globval.Energy);
+    printf("  MaxAmplx [m] = %9.3e   MaxAmply [m] = %9.3e"
+        "   RFAccept [%%] = +/- %4.2f\n", Cell[0].maxampl[X_][1],
+            Cell[0].maxampl[Y_][1], globval.delta_RF * 1e2);
+    printf("  MatMeth      =  %s     ", globval.MatMeth ? "TRUE " : "FALSE");
+    printf(" Cavity_On    =  %s    ", globval.Cavity_on ? "TRUE " : "FALSE");
+    printf("  Radiation_On = %s     \n", globval.radiation ? "TRUE " : "FALSE");
+    printf("  bpm          =  %3d        qt           = %3d        ", GetnKid(
+            globval.bpm), GetnKid(globval.qt));
+    printf(" Chambre_On   = %s     \n", status.chambre ? "TRUE " : "FALSE");
+    printf("  hcorr        =  %3d        vcorr        = %3d\n\n", GetnKid(
+            globval.hcorr), GetnKid(globval.vcorr));
+    printf("  alphac       =   %8.4e\n", globval.Alphac);
+    printf("  nux          =   %8.6f      nuy  =  %8.6f",
+            globval.TotalTune[X_], globval.TotalTune[Y_]);
+    if (globval.Cavity_on)
+        printf("  omega  = %13.9f\n", globval.Omega);
+    else {
+        printf("\n");
+        printf("  ksix         =    %8.6f     ksiy  =   %8.6f\n",
+                globval.Chrom[X_], globval.Chrom[Y_]);
+    }
+    printf("\n");
+    printf("  OneTurn matrix:\n");
+    printf("\n");
+    prtmat(ss_dim, globval.OneTurnMat);
 
+    printf("\nTwiss parameters at entrance:\n");
+    printf(
+            "   Betax [m] = % 9.3e  Alphax = % 9.3e Etax [m] = % 9.3e Etaxp = % 9.3e\n"
+                "   Betay [m] = % 9.3e  Alphay = % 9.3e Etay [m] = % 9.3e Etayp = % 9.3e\n\n",
+            Cell[1].Beta[X_], Cell[1].Alpha[X_], Cell[1].Eta[X_],
+            Cell[1].Etap[X_], Cell[1].Beta[Y_], Cell[1].Alpha[Y_],
+            Cell[1].Eta[Y_], Cell[1].Etap[Y_]);
 
+    fflush( stdout);
+}
 
 /****************************************************************************/
 /* void printlatt(void)
 
-   Purpose:
-       Print twiss parameters into file linlat.out
-       name, position, alpha, beta, phase, dispersion and  its derivative
-       
-   Input:
-       none
+ Purpose:
+ Print twiss parameters into file linlat.out
+ name, position, alpha, beta, phase, dispersion and  its derivative
 
-   Output:
-       none
+ Input:
+ none
 
-   Return:
-       none
+ Output:
+ none
 
-   Global variables:
-       globval
+ Return:
+ none
 
-   Specific functions:
-       getelem
+ Global variables:
+ globval
 
-   Comments:
-       28/04/03 outfile end with .out extension instead of .dat
-       Twiss parameters are computed at the end of elements
+ Specific functions:
+ getelem
 
-****************************************************************************/
-//void printlatt(void)
-void printlatt(void)
-{
-  long int i = 0;
-  FILE *outf;
-  const char fic[] = "linlat.out";
-  struct tm *newtime;
-
-  /* Get time and date */
-  newtime = GetTime();
-
-  if ((outf = fopen(fic,"w")) == NULL) 
-  	{
-    	fprintf(stdout, "printlatt: Error while opening file %s \n",fic);
-    	exit(1);
-  	}
+ Comments:
+ 28/04/03 outfile end with .out extension instead of .dat
+ Twiss parameters are computed at the end of elements
 
-  fprintf(outf,"# TRACY III v. SYNCHROTRON SOLEIL -- %s -- %s \n", fic, asctime2(newtime));
-  fprintf(outf,
-    "#       name           s      alphax  betax   nux   etax   etapx  alphay  betay   nuy     etay        etapy\n");
-  fprintf(outf,
-    "#                     [m]              [m]           [m]                   [m]             [m]\n");
-  fprintf(outf,
-    "#                     exit        \n");
+ ****************************************************************************/
+//void printlatt(void)
+void printlatt(void) {
+    long int i = 0;
+    FILE *outf;
+    const char fic[] = "linlat.out";
+    struct tm *newtime;
+
+    /* Get time and date */
+    newtime = GetTime();
+
+    if ((outf = fopen(fic, "w")) == NULL) {
+        fprintf(stdout, "printlatt: Error while opening file %s \n", fic);
+        exit(1);
+    }
 
-  for (i = 1L; i <= globval.Cell_nLoc; i++)
-  	{
-    	fprintf(outf, "%4ld:%.*s% 8.4f% 8.3f% 7.3f% 7.3f% 7.3f% 7.3f% 8.3f% 7.3f% 7.3f% 12.3e% 12.3e\n",
-        i, SymbolLength, Cell[i].Elem.PName, 
-	Cell[i].S, Cell[i].Alpha[X_], Cell[i].Beta[X_], Cell[i].Nu[X_], Cell[i].Eta[X_], 
-	Cell[i].Etap[X_], Cell[i].Alpha[Y_], Cell[i].Beta[Y_], Cell[i].Nu[Y_],
-	      Cell[i].Eta[Y_], Cell[i].Etap[Y_]);
-  	}
- fclose(outf);
+    fprintf(outf, "# TRACY III v. SYNCHROTRON SOLEIL -- %s -- %s \n", fic,
+            asctime2(newtime));
+    fprintf(
+            outf,
+            "#       name           s      alphax  betax   nux   etax   etapx  alphay  betay   nuy     etay        etapy\n");
+    fprintf(
+            outf,
+            "#                     [m]              [m]           [m]                   [m]             [m]\n");
+    fprintf(outf, "#                     exit        \n");
+
+    for (i = 1L; i <= globval.Cell_nLoc; i++) {
+        fprintf(
+                outf,
+                "%4ld:%.*s% 8.4f% 8.3f% 7.3f% 7.3f% 7.3f% 7.3f% 8.3f% 7.3f% 7.3f% 12.3e% 12.3e\n",
+                i, SymbolLength, Cell[i].Elem.PName, Cell[i].S,
+                Cell[i].Alpha[X_], Cell[i].Beta[X_], Cell[i].Nu[X_],
+                Cell[i].Eta[X_], Cell[i].Etap[X_], Cell[i].Alpha[Y_],
+                Cell[i].Beta[Y_], Cell[i].Nu[Y_], Cell[i].Eta[Y_],
+                Cell[i].Etap[Y_]);
+    }
+    fclose(outf);
 }
 
+double int_curly_H1(long int n) {
+    /* Integration with Simpson's Rule */
 
+    double curly_H;
+    Vector2 alpha[3], beta[3], nu[3], eta[3], etap[3];
 
+    // only works for matrix style calculations
+    get_twiss3(n, alpha, beta, nu, eta, etap);
 
+    curly_H = (get_curly_H(alpha[0][X_], beta[0][X_], eta[0][X_], etap[0][X_])
+            + 4.0 * get_curly_H(alpha[1][X_], beta[1][X_], eta[1][X_],
+                    etap[1][X_]) + get_curly_H(alpha[2][X_], beta[2][X_],
+            eta[2][X_], etap[2][X_])) / 6.0;
 
+    return curly_H;
+}
 
-double int_curly_H1(long int n)
-{
-  /* Integration with Simpson's Rule */
+void prt_sigma(void) {
+    long int i;
+    double code = 0.0;
+    FILE *outf;
 
-  double    curly_H;
-  Vector2   alpha[3], beta[3], nu[3], eta[3], etap[3];
+    outf = file_write("../out/sigma.out");
 
-  // only works for matrix style calculations
-  get_twiss3(n, alpha, beta, nu, eta, etap);
+    fprintf(outf, "#  name     s   sqrt(sx)   sqrt(sx')  sqrt(sy)  sqrt(sy')\n");
+    fprintf(outf, "#           [m]   [mm]       [mrad]     [mm]     [mrad]\n");
+    fprintf(outf, "#\n");
 
-  curly_H = (get_curly_H(alpha[0][X_], beta[0][X_], eta[0][X_], etap[0][X_])
-            +4.0*get_curly_H(alpha[1][X_], beta[1][X_],
-                             eta[1][X_], etap[1][X_])
-	    + get_curly_H(alpha[2][X_], beta[2][X_], eta[2][X_], etap[2][X_]))
-	    /6.0;
+    for (i = 0; i <= globval.Cell_nLoc; i++) {
+        switch (Cell[i].Elem.Pkind) {
+        case drift:
+            code = 0.0;
+            break;
+        case Mpole:
+            if (Cell[i].Elem.M->Pirho != 0)
+                code = 0.5;
+            else if (Cell[i].Elem.M->PBpar[Quad + HOMmax] != 0)
+                code = sgn(Cell[i].Elem.M->PBpar[Quad + HOMmax]);
+            else if (Cell[i].Elem.M->PBpar[Sext + HOMmax] != 0)
+                code = 1.5 * sgn(Cell[i].Elem.M->PBpar[Sext + HOMmax]);
+            else if (Cell[i].Fnum == globval.bpm)
+                code = 2.0;
+            else
+                code = 0.0;
+            break;
+        default:
+            code = 0.0;
+            break;
+        }
+        fprintf(outf, "%4ld %.*s %6.2f %4.1f %9.3e %9.3e %9.3e %9.3e\n", i,
+                SymbolLength, Cell[i].Elem.PName, Cell[i].S, code, 1e3 * sqrt(
+                        Cell[i].sigma[x_][x_]), 1e3 * sqrt(fabs(
+                        Cell[i].sigma[x_][px_])), 1e3 * sqrt(
+                        Cell[i].sigma[y_][y_]), 1e3 * sqrt(fabs(
+                        Cell[i].sigma[y_][py_])));
+    }
 
-  return curly_H;
+    fclose(outf);
 }
 
+void recalc_S(void) {
+    long int k;
+    double S_tot;
 
-void prt_sigma(void)
-{
-  long int  i;
-  double    code = 0.0;
-  FILE      *outf;
-
-  outf = file_write("../out/sigma.out");
-
-  fprintf(outf, "#  name     s   sqrt(sx)   sqrt(sx')  sqrt(sy)  sqrt(sy')\n");
-  fprintf(outf, "#           [m]   [mm]       [mrad]     [mm]     [mrad]\n");
-  fprintf(outf, "#\n");
-
-  for (i = 0; i <= globval.Cell_nLoc; i++) {
-    switch (Cell[i].Elem.Pkind) {
-    case drift:
-      code = 0.0;
-      break;
-    case Mpole:
-      if (Cell[i].Elem.M->Pirho != 0)
-	code = 0.5;
-      else if (Cell[i].Elem.M->PBpar[Quad+HOMmax] != 0)
-	code = sgn(Cell[i].Elem.M->PBpar[Quad+HOMmax]);
-      else if (Cell[i].Elem.M->PBpar[Sext+HOMmax] != 0)
-	code = 1.5*sgn(Cell[i].Elem.M->PBpar[Sext+HOMmax]);
-      else if (Cell[i].Fnum == globval.bpm)
-	code = 2.0;
-      else
-	code = 0.0;
-      break;
-    default:
-      code = 0.0;
-      break;
-    }
-    fprintf(outf, "%4ld %.*s %6.2f %4.1f %9.3e %9.3e %9.3e %9.3e\n",
-            i, SymbolLength, Cell[i].Elem.PName, Cell[i].S, code,
-            1e3*sqrt(Cell[i].sigma[x_][x_]),
-	    1e3*sqrt(fabs(Cell[i].sigma[x_][px_])),
-	    1e3*sqrt(Cell[i].sigma[y_][y_]),
-	    1e3*sqrt(fabs(Cell[i].sigma[y_][py_])));
-  }
-
-  fclose(outf);
-}
-
-
-void recalc_S(void)
-{
-  long int  k;
-  double    S_tot;
+    S_tot = 0.0;
+    for (k = 0; k <= globval.Cell_nLoc; k++) {
+        S_tot += Cell[k].Elem.PL;
+        Cell[k].S = S_tot;
+    }
+}
 
-  S_tot = 0.0;
-  for (k = 0; k <= globval.Cell_nLoc; k++) {
-    S_tot += Cell[k].Elem.PL; Cell[k].S = S_tot;
-  }
+bool getcod(double dP, long &lastpos) {
+    return GetCOD(globval.CODimax, globval.CODeps, dP, lastpos);
 }
 
+void get_twiss3(long int loc, Vector2 alpha[], Vector2 beta[], Vector2 nu[],
+        Vector2 eta[], Vector2 etap[]) {
+    /* Get Twiss functions at magnet entrance-, center-, and exit. */
 
-bool getcod(double dP, long &lastpos)
-{
-  return GetCOD(globval.CODimax, globval.CODeps, dP, lastpos);
-}
+    long int j, k;
+    Vector2 dnu;
+    Matrix Ascr0, Ascr1;
 
+    // Lattice functions at the magnet entrance
+    for (k = 0; k <= 1; k++) {
+        alpha[0][k] = Cell[loc - 1].Alpha[k];
+        beta[0][k] = Cell[loc - 1].Beta[k];
+        nu[0][k] = Cell[loc - 1].Nu[k];
+        eta[0][k] = Cell[loc - 1].Eta[k];
+        etap[0][k] = Cell[loc - 1].Etap[k];
+    }
 
-void get_twiss3(long int loc,
-		Vector2 alpha[], Vector2 beta[], Vector2 nu[],
-		Vector2 eta[], Vector2 etap[])
-{
-  /* Get Twiss functions at magnet entrance-, center-, and exit. */
-
-  long int  j, k;
-  Vector2   dnu;
-  Matrix    Ascr0, Ascr1;
-
-  // Lattice functions at the magnet entrance
-  for (k = 0; k <= 1; k++) {
-    alpha[0][k] = Cell[loc-1].Alpha[k]; beta[0][k] = Cell[loc-1].Beta[k];
-    nu[0][k] = Cell[loc-1].Nu[k];
-    eta[0][k] = Cell[loc-1].Eta[k]; etap[0][k] = Cell[loc-1].Etap[k];
-  }
-
-  UnitMat(5, Ascr0);
-  for (k = 0; k <= 1; k++) {
-    Ascr0[2*k][2*k] = sqrt(Cell[loc-1].Beta[k]); Ascr0[2*k][2*k+1] = 0.0;
-    Ascr0[2*k+1][2*k] = -Cell[loc-1].Alpha[k]/Ascr0[2*k][2*k];
-    Ascr0[2*k+1][2*k+1] = 1/Ascr0[2*k][2*k];
-  }
-  Ascr0[0][4] = eta[0][X_]; Ascr0[1][4] = etap[0][X_];
-  Ascr0[2][4] = eta[1][Y_]; Ascr0[3][4] = etap[1][Y_];
-  CopyMat(5, Ascr0, Ascr1); MulLMat(5, Cell[loc].Elem.M->AU55, Ascr1);
-  dnu[0] = (atan(Ascr1[0][1]/Ascr1[0][0])-atan(Ascr0[0][1]/Ascr0[0][0]))
-           /(2.0*M_PI);
-  dnu[1] = (atan(Ascr1[2][3]/Ascr1[2][2])-atan(Ascr0[2][3]/Ascr0[2][2]))
-           /(2.0*M_PI);
-
-  // Lattice functions at the magnet center
-  for (k = 0; k <= 1; k++) {
-    alpha[1][k] = -Ascr1[2*k][2*k]*Ascr1[2*k+1][2*k]
-                  - Ascr1[2*k][2*k+1]*Ascr1[2*k+1][2*k+1];
-    beta[1][k] = pow(Ascr1[2*k][2*k], 2.0) + pow(Ascr1[2*k][2*k+1], 2);
-    nu[1][k] = nu[0][k] + dnu[k];
-    j = 2*k + 1; eta[1][k] = Ascr1[j-1][4]; etap[1][k] = Ascr1[j][4];
-  }
-
-  CopyMat(5, Ascr1, Ascr0); MulLMat(5, Cell[loc].Elem.M->AD55, Ascr1);
-  dnu[0] = (atan(Ascr1[0][1]/Ascr1[0][0])-atan(Ascr0[0][1]/Ascr0[0][0]))
-           /(2.0*M_PI);
-  dnu[1] = (atan(Ascr1[2][3]/Ascr1[2][2])-atan(Ascr0[2][3]/Ascr0[2][2]))
-           /(2.0*M_PI);
-
-  // Lattice functions at the magnet exit
-  for (k = 0; k <= 1; k++) {
-    alpha[2][k] = -Ascr1[2*k][2*k]*Ascr1[2*k+1][2*k]
-                  - Ascr1[2*k][2*k+1]*Ascr1[2*k+1][2*k+1];
-    beta[2][k] = pow(Ascr1[2*k][2*k], 2.0) + pow(Ascr1[2*k][2*k+1], 2);
-    nu[2][k] = nu[1][k] + dnu[k];
-    j = 2*k + 1; eta[2][k] = Ascr1[j-1][4]; etap[2][k] = Ascr1[j][4];
-  }
-}
-
-
-void getabn(Vector2 &alpha, Vector2 &beta, Vector2 &nu)
-{
-  Vector2 gamma;
-  Cell_GetABGN(globval.OneTurnMat, alpha, beta, gamma, nu);
+    UnitMat(5, Ascr0);
+    for (k = 0; k <= 1; k++) {
+        Ascr0[2 * k][2 * k] = sqrt(Cell[loc - 1].Beta[k]);
+        Ascr0[2 * k][2 * k + 1] = 0.0;
+        Ascr0[2 * k + 1][2 * k] = -Cell[loc - 1].Alpha[k] / Ascr0[2 * k][2 * k];
+        Ascr0[2 * k + 1][2 * k + 1] = 1 / Ascr0[2 * k][2 * k];
+    }
+    Ascr0[0][4] = eta[0][X_];
+    Ascr0[1][4] = etap[0][X_];
+    Ascr0[2][4] = eta[1][Y_];
+    Ascr0[3][4] = etap[1][Y_];
+    CopyMat(5, Ascr0, Ascr1);
+    MulLMat(5, Cell[loc].Elem.M->AU55, Ascr1);
+    dnu[0]
+            = (atan(Ascr1[0][1] / Ascr1[0][0])
+                    - atan(Ascr0[0][1] / Ascr0[0][0])) / (2.0 * M_PI);
+    dnu[1]
+            = (atan(Ascr1[2][3] / Ascr1[2][2])
+                    - atan(Ascr0[2][3] / Ascr0[2][2])) / (2.0 * M_PI);
+
+    // Lattice functions at the magnet center
+    for (k = 0; k <= 1; k++) {
+        alpha[1][k] = -Ascr1[2 * k][2 * k] * Ascr1[2 * k + 1][2 * k] - Ascr1[2
+                * k][2 * k + 1] * Ascr1[2 * k + 1][2 * k + 1];
+        beta[1][k] = pow(Ascr1[2 * k][2 * k], 2.0) + pow(
+                Ascr1[2 * k][2 * k + 1], 2);
+        nu[1][k] = nu[0][k] + dnu[k];
+        j = 2 * k + 1;
+        eta[1][k] = Ascr1[j - 1][4];
+        etap[1][k] = Ascr1[j][4];
+    }
+
+    CopyMat(5, Ascr1, Ascr0);
+    MulLMat(5, Cell[loc].Elem.M->AD55, Ascr1);
+    dnu[0]
+            = (atan(Ascr1[0][1] / Ascr1[0][0])
+                    - atan(Ascr0[0][1] / Ascr0[0][0])) / (2.0 * M_PI);
+    dnu[1]
+            = (atan(Ascr1[2][3] / Ascr1[2][2])
+                    - atan(Ascr0[2][3] / Ascr0[2][2])) / (2.0 * M_PI);
+
+    // Lattice functions at the magnet exit
+    for (k = 0; k <= 1; k++) {
+        alpha[2][k] = -Ascr1[2 * k][2 * k] * Ascr1[2 * k + 1][2 * k] - Ascr1[2
+                * k][2 * k + 1] * Ascr1[2 * k + 1][2 * k + 1];
+        beta[2][k] = pow(Ascr1[2 * k][2 * k], 2.0) + pow(
+                Ascr1[2 * k][2 * k + 1], 2);
+        nu[2][k] = nu[1][k] + dnu[k];
+        j = 2 * k + 1;
+        eta[2][k] = Ascr1[j - 1][4];
+        etap[2][k] = Ascr1[j][4];
+    }
 }
 
+void getabn(Vector2 &alpha, Vector2 &beta, Vector2 &nu) {
+    Vector2 gamma;
+    Cell_GetABGN(globval.OneTurnMat, alpha, beta, gamma, nu);
+}
 
 void TraceABN(long i0, long i1, const Vector2 &alpha, const Vector2 &beta,
-              const Vector2 &eta, const Vector2 &etap, const double dP)
-{
-  long          i, j;
-  double        sb;
-  ss_vect<tps>  Ascr;
-
-  UnitMat(6, globval.Ascr);
-  for (i = 1; i <= 2; i++) {
-    sb = sqrt(beta[i-1]); j = i*2 - 1;
-    globval.Ascr[j-1][j-1] = sb;               globval.Ascr[j-1][j] = 0.0;
-    globval.Ascr[j][j - 1] = -(alpha[i-1]/sb); globval.Ascr[j][j] = 1/sb;
-  }
-  globval.Ascr[0][4] = eta[0]; globval.Ascr[1][4] = etap[0];
-  globval.Ascr[2][4] = eta[1]; globval.Ascr[3][4] = etap[1];
+        const Vector2 &eta, const Vector2 &etap, const double dP) {
+    long i, j;
+    double sb;
+    ss_vect<tps> Ascr;
+
+    UnitMat(6, globval.Ascr);
+    for (i = 1; i <= 2; i++) {
+        sb = sqrt(beta[i - 1]);
+        j = i * 2 - 1;
+        globval.Ascr[j - 1][j - 1] = sb;
+        globval.Ascr[j - 1][j] = 0.0;
+        globval.Ascr[j][j - 1] = -(alpha[i - 1] / sb);
+        globval.Ascr[j][j] = 1 / sb;
+    }
+    globval.Ascr[0][4] = eta[0];
+    globval.Ascr[1][4] = etap[0];
+    globval.Ascr[2][4] = eta[1];
+    globval.Ascr[3][4] = etap[1];
 
-  for (i = 0; i < 6; i++)
-    globval.CODvect[i] = 0.0;
-  globval.CODvect[4] = dP;
+    for (i = 0; i < 6; i++)
+        globval.CODvect[i] = 0.0;
+    globval.CODvect[4] = dP;
 
-  if (globval.MatMeth)
-    Cell_Twiss_M(i0, i1, globval.Ascr, false, false, dP);
-  else {
-    for (i = 0; i <= 5; i++) {
-      Ascr[i] = tps(globval.CODvect[i]);
-      for (j = 0; j <= 5; j++)
-	Ascr[i] += globval.Ascr[i][j]*tps(0.0, j+1);
+    if (globval.MatMeth)
+        Cell_Twiss_M(i0, i1, globval.Ascr, false, false, dP);
+    else {
+        for (i = 0; i <= 5; i++) {
+            Ascr[i] = tps(globval.CODvect[i]);
+            for (j = 0; j <= 5; j++)
+                Ascr[i] += globval.Ascr[i][j] * tps(0.0, j + 1);
+        }
+        Cell_Twiss(i0, i1, Ascr, false, false, dP);
     }
-    Cell_Twiss(i0, i1, Ascr, false, false, dP);
-  }
 
 }
 
 /****************************************************************************/
 /* void FitTune(long qf, long qd, double nux, double nuy)
 
-   Purpose:
-       Fit tunes to the target values using quadrupoles "qf" and "qd"
-   Input:
-       qf : tuned quadrupole
-       qd : tuned quadrupole
-       nux: target horizontal tune
-       nuy: target vertical tune
-   Output:
-       none
+ Purpose:
+ Fit tunes to the target values using quadrupoles "qf" and "qd"
+ Input:
+ qf : tuned quadrupole
+ qd : tuned quadrupole
+ nux: target horizontal tune
+ nuy: target vertical tune
+ Output:
+ none
 
-   Return:
-       none
+ Return:
+ none
 
-   Global variables:
-      
-   specific functions:
+ Global variables:
 
-   Comments:     
+ specific functions:
 
-****************************************************************************/
-void FitTune(long qf, long qd, double nux, double nuy)
-{
-  long      i;
-  iVector2  nq = {0,0};
-  Vector2   nu = {0.0, 0.0};
-  fitvect   qfbuf, qdbuf;
+ Comments:
 
-  /* Get elements for the first quadrupole family */
-  nq[X_] = GetnKid(qf);
-  for (i = 1; i <= nq[X_]; i++)
-    qfbuf[i-1] = Elem_GetPos(qf, i);
+ ****************************************************************************/
+void FitTune(long qf, long qd, double nux, double nuy) {
+    long i;
+    iVector2 nq = { 0, 0 };
+    Vector2 nu = { 0.0, 0.0 };
+    fitvect qfbuf, qdbuf;
 
-  /* Get elements for the second quadrupole family */
-  nq[Y_] = GetnKid(qd);
-  for (i = 1; i <= nq[Y_]; i++)
-    qdbuf[i - 1] = Elem_GetPos(qd, i);
+    /* Get elements for the first quadrupole family */
+    nq[X_] = GetnKid(qf);
+    for (i = 1; i <= nq[X_]; i++)
+        qfbuf[i - 1] = Elem_GetPos(qf, i);
 
-  nu[X_] = nux; nu[Y_] = nuy;
+    /* Get elements for the second quadrupole family */
+    nq[Y_] = GetnKid(qd);
+    for (i = 1; i <= nq[Y_]; i++)
+        qdbuf[i - 1] = Elem_GetPos(qd, i);
 
-  /* fit tunes */
-  Ring_Fittune(nu, nueps, nq, qfbuf, qdbuf, nudkL, nuimax);
+    nu[X_] = nux;
+    nu[Y_] = nuy;
+
+    /* fit tunes */
+    Ring_Fittune(nu, nueps, nq, qfbuf, qdbuf, nudkL, nuimax);
 }
 
 /****************************************************************************/
 /* void FitChrom(long sf, long sd, double ksix, double ksiy)
 
-   Purpose:
-       Fit chromaticities to the target values using sextupoles "sf" and "sd"
-   Input:
-       sf  : tuned sextupole
-       sd  : tuned sextupole
-       ksix: target horizontal chromaticity
-       ksiy: target vertical chromaticity
-   Output:
-       none
+ Purpose:
+ Fit chromaticities to the target values using sextupoles "sf" and "sd"
+ Input:
+ sf  : tuned sextupole
+ sd  : tuned sextupole
+ ksix: target horizontal chromaticity
+ ksiy: target vertical chromaticity
+ Output:
+ none
 
-   Return:
-       none
+ Return:
+ none
 
-   Global variables:
-      
-   specific functions:
+ Global variables:
 
-   Comments:     
+ specific functions:
 
-****************************************************************************/
+ Comments:
 
-void FitChrom(long sf, long sd, double ksix, double ksiy)
-{
-  long      i;
-  iVector2  ns = {0,0};
-  fitvect   sfbuf, sdbuf;
-  Vector2   ksi ={0.0, 0.0};
+ ****************************************************************************/
 
-  /* Get elements for the first sextupole family */
-  ns[X_] = GetnKid(sf);
-  for (i = 1; i <= ns[X_]; i++)
-    sfbuf[i-1] = Elem_GetPos(sf, i);
+void FitChrom(long sf, long sd, double ksix, double ksiy) {
+    long i;
+    iVector2 ns = { 0, 0 };
+    fitvect sfbuf, sdbuf;
+    Vector2 ksi = { 0.0, 0.0 };
 
-  /* Get elements for the second sextupole family */
-  ns[Y_] = GetnKid(sd);
-  for (i = 1; i <= ns[Y_]; i++)
-    sdbuf[i-1] = Elem_GetPos(sd, i);
+    /* Get elements for the first sextupole family */
+    ns[X_] = GetnKid(sf);
+    for (i = 1; i <= ns[X_]; i++)
+        sfbuf[i - 1] = Elem_GetPos(sf, i);
 
-  ksi[X_] = ksix; ksi[Y_] = ksiy;
+    /* Get elements for the second sextupole family */
+    ns[Y_] = GetnKid(sd);
+    for (i = 1; i <= ns[Y_]; i++)
+        sdbuf[i - 1] = Elem_GetPos(sd, i);
 
-  /* Fit chromaticities */
-  /*    Ring_Fitchrom(ksi, ksieps, ns, sfbuf, sdbuf, 1.0, 1);*/
-  Ring_Fitchrom(ksi, ksieps, ns, sfbuf, sdbuf, ksidkpL, ksiimax);
-}
+    ksi[X_] = ksix;
+    ksi[Y_] = ksiy;
 
+    /* Fit chromaticities */
+    /*    Ring_Fitchrom(ksi, ksieps, ns, sfbuf, sdbuf, 1.0, 1);*/
+    Ring_Fitchrom(ksi, ksieps, ns, sfbuf, sdbuf, ksidkpL, ksiimax);
+}
 
-void FitDisp(long q, long pos, double eta)
-{
-  long     i, nq;
-  fitvect  qbuf;
+void FitDisp(long q, long pos, double eta) {
+    long i, nq;
+    fitvect qbuf;
 
-  /* Get elements for the quadrupole family */
-  nq = GetnKid(q);
-  for (i = 1; i <= nq; i++)
-    qbuf[i-1] = Elem_GetPos(q, i);
+    /* Get elements for the quadrupole family */
+    nq = GetnKid(q);
+    for (i = 1; i <= nq; i++)
+        qbuf[i - 1] = Elem_GetPos(q, i);
 
-  Ring_FitDisp(pos, eta, dispeps, nq, qbuf, dispdkL, dispimax);
+    Ring_FitDisp(pos, eta, dispeps, nq, qbuf, dispdkL, dispimax);
 }
 
-
 #define nfloq           4
 
-void getfloqs(Vector &x)
-{
-  // Transform to Floquet space
-  LinTrans(nfloq, globval.Ascrinv, x);
+void getfloqs(Vector &x) {
+    // Transform to Floquet space
+    LinTrans(nfloq, globval.Ascrinv, x);
 }
 
 #undef nfloq
 
-
 #define ntrack          4
 
 // 4D tracking in normal or Floquet space over nmax turns
 
-void track(const char *file_name,
-	   double ic1, double ic2, double ic3, double ic4, double dp,
-	   long int nmax, long int &lastn, long int &lastpos, int floqs,
-	   double f_rf)
-{
-  /* Single particle tracking around closed orbit:
-
-          Output                floqs
-
-        Phase Space               0     [x, px, y, py, delta, ct]  
-	Floquet Space             1     [x^, px^, y^, py^, delta, ct]
-	Action-Angle Variables    2     [2Jx, phx, 2Jy, phiy, delta, ct]
-
-  */
-  long int   i;
-  double     twoJx, twoJy, phix, phiy, scl_1 = 1.0, scl_2 = 1.0;
-  Vector     x0, x1, x2, xf;
-  FILE       *outf;
-
-  bool  prt = false;
-
-  if ((floqs == 0)) {
-    scl_1 = 1e3; scl_2 = 1e3;
-    x0[x_] = ic1; x0[px_] = ic2; x0[y_] = ic3; x0[py_] = ic4;
-  } else if ((floqs == 1)) {
-    scl_1 = 1.0; scl_2 = 1.0;
-    x0[x_] = ic1; x0[px_] = ic2; x0[y_] = ic3; x0[py_] = ic4;
-    LinTrans(4, globval.Ascr, x0);
-  } else if (floqs == 2) {
-    scl_1 = 1e6; scl_2 = 1.0;
-    x0[x_] = sqrt(ic1)*cos(ic2); x0[px_] = -sqrt(ic1)*sin(ic2);
-    x0[y_] = sqrt(ic3)*cos(ic4); x0[py_] = -sqrt(ic3)*sin(ic4);
-    LinTrans(4, globval.Ascr, x0);
-  }
-
-  outf = file_write(file_name);
-  fprintf(outf, "# Tracking with TRACY");
-  getcod(dp, lastpos);
-  if (floqs == 0)
-    fprintf(outf, "\n");
-  else if (floqs == 1) {
-    Ring_GetTwiss(false, dp);
-    fprintf(outf, "# (Floquet space)\n");
-  } else if (floqs == 2) {
-    Ring_GetTwiss(false, dp);
-    fprintf(outf, "# (Action-Angle variables)\n");
-  }
-  fprintf(outf, "#\n");
-  fprintf(outf, "#%3d%6ld% .1E% .1E% .1E% .1E% 7.5f% 7.5f\n",
-	  1, nmax, 1e0, 1e0, 0e0, 0e0, globval.TotalTune[0],
-	  globval.TotalTune[1]);
-  if (floqs == 0) {
-    fprintf(outf, "#    N       x            p_x            y            p_y");
-    fprintf(outf, "          delta          cdt\n");
-    fprintf(outf, "#           [mm]         [mrad]"
-	    "         [mm]         [mrad]");
-  } else if  (floqs == 1) {
-    fprintf(outf, "#    N     x^          px^          y^          py^");
-    fprintf(outf, "          delta          cdt");
-    fprintf(outf, "#                              "
-	    "                            ");
-  } else if  (floqs == 2) {
-    fprintf(outf, "#    N     2Jx          phi_x          2Jy          phi_y");
-    fprintf(outf, "          delta          cdt\n");
-    fprintf(outf, "#                              "
-	    "                            ");
-  }
-  if (f_rf == 0.0){
-    fprintf(outf, "         [%%]           [mm]\n");
-    fprintf(outf, "#\n");
-    fprintf(outf, "%4d %23.16e %23.16e %23.16e %23.16e %23.16e %23.16e\n",
-	    0, scl_1*ic1, scl_2*ic2, scl_1*ic3, scl_2*ic4, 1e2*dp, 
-	    1e3*globval.CODvect[ct_]);
-  } else {
-    fprintf(outf, "         [%%]           [deg]\n");
+void track(const char *file_name, double ic1, double ic2, double ic3,
+        double ic4, double dp, long int nmax, long int &lastn,
+        long int &lastpos, int floqs, double f_rf) {
+    /* Single particle tracking around closed orbit:
+
+     Output                floqs
+
+     Phase Space               0     [x, px, y, py, delta, ct]
+     Floquet Space             1     [x^, px^, y^, py^, delta, ct]
+     Action-Angle Variables    2     [2Jx, phx, 2Jy, phiy, delta, ct]
+
+     */
+    long int i;
+    double twoJx, twoJy, phix, phiy, scl_1 = 1.0, scl_2 = 1.0;
+    Vector x0, x1, x2, xf;
+    FILE *outf;
+
+    bool prt = false;
+
+    if ((floqs == 0)) {
+        scl_1 = 1e3;
+        scl_2 = 1e3;
+        x0[x_] = ic1;
+        x0[px_] = ic2;
+        x0[y_] = ic3;
+        x0[py_] = ic4;
+    } else if ((floqs == 1)) {
+        scl_1 = 1.0;
+        scl_2 = 1.0;
+        x0[x_] = ic1;
+        x0[px_] = ic2;
+        x0[y_] = ic3;
+        x0[py_] = ic4;
+        LinTrans(4, globval.Ascr, x0);
+    } else if (floqs == 2) {
+        scl_1 = 1e6;
+        scl_2 = 1.0;
+        x0[x_] = sqrt(ic1) * cos(ic2);
+        x0[px_] = -sqrt(ic1) * sin(ic2);
+        x0[y_] = sqrt(ic3) * cos(ic4);
+        x0[py_] = -sqrt(ic3) * sin(ic4);
+        LinTrans(4, globval.Ascr, x0);
+    }
+
+    outf = file_write(file_name);
+    fprintf(outf, "# Tracking with TRACY");
+    getcod(dp, lastpos);
+    if (floqs == 0)
+        fprintf(outf, "\n");
+    else if (floqs == 1) {
+        Ring_GetTwiss(false, dp);
+        fprintf(outf, "# (Floquet space)\n");
+    } else if (floqs == 2) {
+        Ring_GetTwiss(false, dp);
+        fprintf(outf, "# (Action-Angle variables)\n");
+    }
     fprintf(outf, "#\n");
-    fprintf(outf, "%4d %23.16e %23.16e %23.16e %23.16e %23.16e %23.16e\n",
-	    0, scl_1*ic1, scl_2*ic2, scl_1*ic3, scl_2*ic4, 1e2*dp, 
-	    2.0*f_rf*180.0*globval.CODvect[ct_]/c0);
-  }
-  x2[x_] = x0[x_] + globval.CODvect[x_];
-  x2[px_] = x0[px_] + globval.CODvect[px_];
-  x2[y_] = x0[y_] + globval.CODvect[y_];
-  x2[py_] = x0[py_] + globval.CODvect[py_];
-  if (globval.Cavity_on) {
-    x2[delta_] = dp + globval.CODvect[delta_]; x2[ct_] = globval.CODvect[ct_];
-  } else {
-    x2[delta_] = dp; x2[ct_] = 0.0;
-  }
-
-  lastn = 0;
-
-  if (prt) {
-    printf("\n");
-    printf("track:\n");
-    printf("%4ld %7.3f %7.3f %7.3f %7.3f %7.3f %7.3f\n",
-	   lastn, 1e3*x2[x_], 1e3*x2[px_], 1e3*x2[y_], 1e3*x2[py_],
-	   1e2*x2[delta_], 1e3*x2[ct_]);
-  }
-    
-  if (globval.MatMeth) Cell_Concat(dp);
-
-  do {
-    (lastn)++;
-    for (i = 0; i < nv_; i++)
-      x1[i] = x2[i];
-
-    if (globval.MatMeth) {
-      Cell_fPass(x2, lastpos);
+    fprintf(outf, "#%3d%6ld% .1E% .1E% .1E% .1E% 7.5f% 7.5f\n", 1, nmax, 1e0,
+            1e0, 0e0, 0e0, globval.TotalTune[0], globval.TotalTune[1]);
+    if (floqs == 0) {
+        fprintf(outf,
+                "#    N       x            p_x            y            p_y");
+        fprintf(outf, "          delta          cdt\n");
+        fprintf(outf, "#           [mm]         [mrad]"
+            "         [mm]         [mrad]");
+    } else if (floqs == 1) {
+        fprintf(outf, "#    N     x^          px^          y^          py^");
+        fprintf(outf, "          delta          cdt");
+        fprintf(outf, "#                              "
+            "                            ");
+    } else if (floqs == 2) {
+        fprintf(outf,
+                "#    N     2Jx          phi_x          2Jy          phi_y");
+        fprintf(outf, "          delta          cdt\n");
+        fprintf(outf, "#                              "
+            "                            ");
+    }
+    if (f_rf == 0.0) {
+        fprintf(outf, "         [%%]           [mm]\n");
+        fprintf(outf, "#\n");
+        fprintf(outf, "%4d %23.16e %23.16e %23.16e %23.16e %23.16e %23.16e\n",
+                0, scl_1 * ic1, scl_2 * ic2, scl_1 * ic3, scl_2 * ic4,
+                1e2 * dp, 1e3 * globval.CODvect[ct_]);
     } else {
-      Cell_Pass(0, globval.Cell_nLoc, x2, lastpos);
-    }
-
-    for (i = x_; i <= py_; i++)
-      xf[i] = x2[i] - globval.CODvect[i];
-
-    for (i = delta_; i <= ct_; i++)
-      if (globval.Cavity_on && (i != ct_)) 
-	xf[i] = x2[i] - globval.CODvect[i];
-      else
-	xf[i] = x2[i];
-
-    if (floqs == 1)
-      getfloqs(xf);
-    else if (floqs == 2) {
-      getfloqs(xf);
-      twoJx = pow(xf[x_], 2) + pow(xf[px_], 2);
-      twoJy = pow(xf[y_], 2) + pow(xf[py_], 2);
-      phix = atan2(xf[px_], xf[x_]);
-      phiy = atan2(xf[py_], xf[y_]);
-      xf[x_] = twoJx; xf[px_] = phix; xf[y_] = twoJy; xf[py_] = phiy;
-    }
-    if (f_rf == 0.0)
-      fprintf(outf,
-	      "%4ld %23.16le %23.16le %23.16le %23.16le %23.16le %23.16le\n",
-	      lastn, scl_1*xf[0], scl_2*xf[1], scl_1*xf[2], scl_2*xf[3],
-	      1e2*xf[4], 1e3*xf[5]);
-    else
-      fprintf(outf,
-	      "%4ld %23.16le %23.16le %23.16le %23.16le %23.16le %23.16le\n",
-	      lastn, scl_1*xf[0], scl_2*xf[1], scl_1*xf[2], scl_2*xf[3],
-	      1e2*xf[4], 2.0*f_rf*180.0*xf[5]/c0);
-  } while ((lastn != nmax) && (lastpos == globval.Cell_nLoc));
+        fprintf(outf, "         [%%]           [deg]\n");
+        fprintf(outf, "#\n");
+        fprintf(outf, "%4d %23.16e %23.16e %23.16e %23.16e %23.16e %23.16e\n",
+                0, scl_1 * ic1, scl_2 * ic2, scl_1 * ic3, scl_2 * ic4,
+                1e2 * dp, 2.0 * f_rf * 180.0 * globval.CODvect[ct_] / c0);
+    }
+    x2[x_] = x0[x_] + globval.CODvect[x_];
+    x2[px_] = x0[px_] + globval.CODvect[px_];
+    x2[y_] = x0[y_] + globval.CODvect[y_];
+    x2[py_] = x0[py_] + globval.CODvect[py_];
+    if (globval.Cavity_on) {
+        x2[delta_] = dp + globval.CODvect[delta_];
+        x2[ct_] = globval.CODvect[ct_];
+    } else {
+        x2[delta_] = dp;
+        x2[ct_] = 0.0;
+    }
+
+    lastn = 0;
+
+    if (prt) {
+        printf("\n");
+        printf("track:\n");
+        printf("%4ld %7.3f %7.3f %7.3f %7.3f %7.3f %7.3f\n", lastn, 1e3
+                * x2[x_], 1e3 * x2[px_], 1e3 * x2[y_], 1e3 * x2[py_], 1e2
+                * x2[delta_], 1e3 * x2[ct_]);
+    }
+
+    if (globval.MatMeth)
+        Cell_Concat(dp);
+
+    do {
+        (lastn)++;
+        for (i = 0; i < nv_; i++)
+            x1[i] = x2[i];
+
+        if (globval.MatMeth) {
+            Cell_fPass(x2, lastpos);
+        } else {
+            Cell_Pass(0, globval.Cell_nLoc, x2, lastpos);
+        }
+
+        for (i = x_; i <= py_; i++)
+            xf[i] = x2[i] - globval.CODvect[i];
+
+        for (i = delta_; i <= ct_; i++)
+            if (globval.Cavity_on && (i != ct_))
+                xf[i] = x2[i] - globval.CODvect[i];
+            else
+                xf[i] = x2[i];
+
+        if (floqs == 1)
+            getfloqs(xf);
+        else if (floqs == 2) {
+            getfloqs(xf);
+            twoJx = pow(xf[x_], 2) + pow(xf[px_], 2);
+            twoJy = pow(xf[y_], 2) + pow(xf[py_], 2);
+            phix = atan2(xf[px_], xf[x_]);
+            phiy = atan2(xf[py_], xf[y_]);
+            xf[x_] = twoJx;
+            xf[px_] = phix;
+            xf[y_] = twoJy;
+            xf[py_] = phiy;
+        }
+        if (f_rf == 0.0)
+            fprintf(
+                    outf,
+                    "%4ld %23.16le %23.16le %23.16le %23.16le %23.16le %23.16le\n",
+                    lastn, scl_1 * xf[0], scl_2 * xf[1], scl_1 * xf[2], scl_2
+                            * xf[3], 1e2 * xf[4], 1e3 * xf[5]);
+        else
+            fprintf(
+                    outf,
+                    "%4ld %23.16le %23.16le %23.16le %23.16le %23.16le %23.16le\n",
+                    lastn, scl_1 * xf[0], scl_2 * xf[1], scl_1 * xf[2], scl_2
+                            * xf[3], 1e2 * xf[4], 2.0 * f_rf * 180.0 * xf[5]
+                            / c0);
+    } while ((lastn != nmax) && (lastpos == globval.Cell_nLoc));
 
-  if (globval.MatMeth)
-    Cell_Pass(0, globval.Cell_nLoc, x1, lastpos);
+    if (globval.MatMeth)
+        Cell_Pass(0, globval.Cell_nLoc, x1, lastpos);
 
-  fclose(outf);
+    fclose(outf);
 }
 
 #undef ntrack
 
-
 #define step            0.1
 #define px              0.0
 #define py              0.0
-void track_(double r, struct LOC_getdynap *LINK)
-{
-  long i, lastn, lastpos;
-  Vector x;
-
-  x[0] = r * cos(LINK->phi);
-  x[1] = px;
-  x[2] = r * sin(LINK->phi);
-  x[3] = py;
-  x[4] = LINK->delta;
-  x[5] = 0.0;
-  /* transform to phase space */
-  if (LINK->floqs) {
-    LinTrans(5, globval.Ascr, x);
-  }
-  for (i = 0; i <= 3; i++)
-    x[i] += globval.CODvect[i];
-  lastn = 0;
-  do {
-    lastn++;
-    if (globval.MatMeth) {
-      Cell_fPass(x, lastpos);
-    } else {
-      Cell_Pass(0, globval.Cell_nLoc, x, lastpos);
+void track_(double r, struct LOC_getdynap *LINK) {
+    long i, lastn, lastpos;
+    Vector x;
+
+    x[0] = r * cos(LINK->phi);
+    x[1] = px;
+    x[2] = r * sin(LINK->phi);
+    x[3] = py;
+    x[4] = LINK->delta;
+    x[5] = 0.0;
+    /* transform to phase space */
+    if (LINK->floqs) {
+        LinTrans(5, globval.Ascr, x);
     }
-  } while (lastn != LINK->nturn && lastpos == globval.Cell_nLoc);
-  LINK->lost = (lastn != LINK->nturn);
+    for (i = 0; i <= 3; i++)
+        x[i] += globval.CODvect[i];
+    lastn = 0;
+    do {
+        lastn++;
+        if (globval.MatMeth) {
+            Cell_fPass(x, lastpos);
+        } else {
+            Cell_Pass(0, globval.Cell_nLoc, x, lastpos);
+        }
+    } while (lastn != LINK->nturn && lastpos == globval.Cell_nLoc);
+    LINK->lost = (lastn != LINK->nturn);
 }
 #undef step
 #undef px
 #undef py
 
-
 /****************************************************************************/
 /* void Trac(double x, double px, double y, double py, double dp, double ctau,
-          long nmax, long pos, long &lastn, long &lastpos, FILE *outf1)
-
-   Purpose:
-      Single particle tracking w/ respect to the chamber centrum
-        Based on the version of tracy 2 in soleillib.c
-   Input:
-      x, px, y, py 4 transverses coordinates
-      ctau         c*tau
-      dp           energy offset
-      nmax         number of turns
-      pos          starting position for tracking
-      aperture     global physical aperture
-
-   Output:
-      lastn       last n (should be nmax if  not lost)
-      lastpos     last position in the ring
-      outf1       output file with 6D phase at different pos
-
-   Return:
-         lastn:  last tracking turn that particle is not lost 
-       lastpos:   last element position that particle is not lost
-
-   Global variables:
-       globval
-
-   specific functions:
-       Cell_Pass
-
-   Comments:
-       Absolute TRACKING with respect to the center of the vacuum vessel
-       BUG: last printout is wrong because not at pos but at the end of
-            the ring
-       26/04/03 print output for phase space is for position pos now
-       01/12/03 tracking from 0 to pos -1L instead of 0 to pos
-       (wrong observation point)
-       
-       23/07/10 change the call variable in Cell_Pass( ): pos-1L --> pos (L704, L717).
-                 since the Cell_Pass( ) is tracking from element i0 to i1(tracy 3), and
-		       the Cell_Pass( ) is tracking from element i0+1L to i1(tracy 2).
-
-****************************************************************************/
+ long nmax, long pos, long &lastn, long &lastpos, FILE *outf1)
+
+ Purpose:
+ Single particle tracking w/ respect to the chamber centrum
+ Based on the version of tracy 2 in soleillib.c
+ Input:
+ x, px, y, py 4 transverses coordinates
+ ctau         c*tau
+ dp           energy offset
+ nmax         number of turns
+ pos          starting position for tracking
+ aperture     global physical aperture
+
+ Output:
+ lastn       last n (should be nmax if  not lost)
+ lastpos     last position in the ring
+ outf1       output file with 6D phase at different pos
+
+ Return:
+ lastn:  last tracking turn that particle is not lost
+ lastpos:   last element position that particle is not lost
+
+ Global variables:
+ globval
+
+ specific functions:
+ Cell_Pass
+
+ Comments:
+ Absolute TRACKING with respect to the center of the vacuum vessel
+ BUG: last printout is wrong because not at pos but at the end of
+ the ring
+ 26/04/03 print output for phase space is for position pos now
+ 01/12/03 tracking from 0 to pos -1L instead of 0 to pos
+ (wrong observation point)
+
+ 23/07/10 change the call variable in Cell_Pass( ): pos-1L --> pos (L704, L717).
+ since the Cell_Pass( ) is tracking from element i0 to i1(tracy 3), and
+ the Cell_Pass( ) is tracking from element i0+1L to i1(tracy 2).
+
+ ****************************************************************************/
 void Trac(double x, double px, double y, double py, double dp, double ctau,
-          long nmax, long pos, long &lastn, long &lastpos, FILE *outf1)
-{
-  bool lostF; /* Lost particle Flag */
-  Vector x1;     /* tracking coordinates */
-  Vector2  aperture;
-
-  /* Compute closed orbit : usefull if insertion devices */
-
-  aperture[0] = 1e0;
-  aperture[1] = 1e0;
-
-  x1[0] = x; x1[1] = px;
-  x1[2] = y; x1[3] = py;
-  x1[4] =dp; x1[5] = ctau;
-
-  lastn = 0L;  (lastpos) = pos;
-  lostF = true;
-  
-  if(trace) fprintf(outf1, "\n");
-  if(trace) fprintf(outf1, "%6ld %+10.5e %+10.5e %+10.5e %+10.5e %+10.5e %+10.5e \n", lastn,
-                 x1[0], x1[1], x1[2], x1[3], x1[4], x1[5]);
-  
-		 
-//  Cell_Pass(pos -1L, globval.Cell_nLoc, x1, lastpos);
-  Cell_Pass(pos, globval.Cell_nLoc, x1, lastpos);
-
-  if (lastpos == globval.Cell_nLoc)
-    do 
-    {
-         (lastn)++;  /* 3) continue tracking for nmax turns*/
-         Cell_Pass(0L,pos-1L, x1, lastpos); /* 1) check whether particle is stable at element from 0 to pos-1L*/
-    
-         if(trace) 
-         fprintf(outf1, "%6ld %+10.5e %+10.5e %+10.5e %+10.5e %+10.5e %+10.5e \n",
-	                 lastn, x1[0], x1[1], x1[2], x1[3], x1[4], x1[5]);
-    
-         if (lastpos == pos-1L) 
-	  Cell_Pass(pos,globval.Cell_nLoc, x1, lastpos); /* 2) check particle is stable at element from pos to end*/
-        //   Cell_Pass(pos-1L,globval.Cell_nLoc, x1, lastpos); 
-  
-    }while (((lastn) < nmax) && ((lastpos) == globval.Cell_nLoc));
-
-  if (lastpos == globval.Cell_nLoc) 
-    Cell_Pass(0L,pos, x1, lastpos);
-
-  if (lastpos != pos) {
-    printf("Trac: Particle lost \n");
-    fprintf(stdout, "turn:%6ld plane: %1d"
-	    " %+10.5g %+10.5g %+10.5g %+10.5g %+10.5g %+10.5g \n", 
-	    lastn, status.lossplane, x1[0], x1[1], x1[2], x1[3], x1[4], x1[5]);
-  }
+        long nmax, long pos, long &lastn, long &lastpos, FILE *outf1) {
+    bool lostF; /* Lost particle Flag */
+    Vector x1; /* tracking coordinates */
+    Vector2 aperture;
+
+    /* Compute closed orbit: useful if insertion devices */
+
+    aperture[0] = 1e0;
+    aperture[1] = 1e0;
+
+    x1[0] = x;
+    x1[1] = px;
+    x1[2] = y;
+    x1[3] = py;
+    x1[4] = dp;
+    x1[5] = ctau;
+
+    lastn = 0L;
+    (lastpos) = pos;
+    lostF = true;
+
+    if (trace)
+        fprintf(outf1, "\n");
+    if (trace)
+        fprintf(outf1,
+                "%6ld %+10.5e %+10.5e %+10.5e %+10.5e %+10.5e %+10.5e \n",
+                lastn, x1[0], x1[1], x1[2], x1[3], x1[4], x1[5]);
+
+    //  Cell_Pass(pos -1L, globval.Cell_nLoc, x1, lastpos);
+    Cell_Pass(pos, globval.Cell_nLoc, x1, lastpos);
+
+    if (lastpos == globval.Cell_nLoc)
+        do {
+            (lastn)++; /* 3) continue tracking for nmax turns*/
+            Cell_Pass(0L, pos - 1L, x1, lastpos); /* 1) check whether particle is stable at element from 0 to pos-1L*/
+
+            if (trace)
+                fprintf(
+                        outf1,
+                        "%6ld %+10.5e %+10.5e %+10.5e %+10.5e %+10.5e %+10.5e \n",
+                        lastn, x1[0], x1[1], x1[2], x1[3], x1[4], x1[5]);
+
+            if (lastpos == pos - 1L)
+                Cell_Pass(pos, globval.Cell_nLoc, x1, lastpos); /* 2) check particle is stable at element from pos to end*/
+            //   Cell_Pass(pos-1L,globval.Cell_nLoc, x1, lastpos);
+
+        } while (((lastn) < nmax) && ((lastpos) == globval.Cell_nLoc));
+
+    if (lastpos == globval.Cell_nLoc)
+        Cell_Pass(0L, pos, x1, lastpos);
+
+    if (lastpos != pos) {
+        printf("Trac: Particle lost \n");
+        fprintf(stdout, "turn:%6ld plane: %1d"
+            " %+10.5g %+10.5g %+10.5g %+10.5g %+10.5g %+10.5g \n", lastn,
+                status.lossplane, x1[0], x1[1], x1[2], x1[3], x1[4], x1[5]);
+    }
 }
 
 /****************************************************************************/
 /*bool chk_if_lost(double x0, double y0, double delta,
-		 long int nturn, bool floqs)
-		 
-   Purpose:
-       Binary search for dynamical aperture in Floquet space.
-
-   Input:
-       none
+ long int nturn, bool floqs)
 
-   Output:
-       none
+ Purpose:
+ Binary search for dynamical aperture in Floquet space.
 
-   Return:
-       none
+ Input:
+ none
 
-   Global variables:
-       px_0, py_0
+ Output:
+ none
 
-   Specific functions:
-       chk_if_lost
+ Return:
+ none
 
-   Comments:
-       none
+ Global variables:
+ px_0, py_0
 
-****************************************************************************/
+ Specific functions:
+ chk_if_lost
 
-#define nfloq     4
-bool chk_if_lost(double x0, double y0, double delta,
-		 long int nturn, bool floqs)
-{
-  long int  i, lastn, lastpos;
-  Vector    x;
+ Comments:
+ none
 
-  bool  prt = false;
+ ****************************************************************************/
 
-  x[x_] = x0; x[px_] = px_0; x[y_] = y0; x[py_] = py_0;
-  x[delta_] = delta; x[ct_] = 0.0;
-  if (floqs)
-    // transform to phase space
-    LinTrans(nfloq, globval.Ascr, x);  
-  for (i = 0; i <= 3; i++)  
-    x[i] += globval.CODvect[i];
-
-  lastn = 0;
-  if (prt) {
-    printf("\n");
-    printf("chk_if_lost:\n");
-    printf("%4ld %7.3f %7.3f %7.3f %7.3f %7.3f %7.3f\n",
-	   lastn, 1e3*x[x_], 1e3*x[px_], 1e3*x[y_], 1e3*x[py_],
-	   1e2*x[delta_], 1e3*x[ct_]);
-  }
-  do {
-    lastn++;
-    if (globval.MatMeth)
-      Cell_fPass(x, lastpos);
-    else
-      Cell_Pass(0, globval.Cell_nLoc, x, lastpos);
-    if (prt)
-      printf("%4ld %7.3f %7.3f %7.3f %7.3f %7.3f %7.3f\n",
-	     lastn, 1e3*x[x_], 1e3*x[px_], 1e3*x[y_], 1e3*x[py_],
-	     1e2*x[delta_], 1e3*x[ct_]);
-  } while ((lastn != nturn) && (lastpos == globval.Cell_nLoc));
-  return(lastn != nturn);
+#define nfloq     4
+bool chk_if_lost(double x0, double y0, double delta, long int nturn, bool floqs) {
+    long int i, lastn, lastpos;
+    Vector x;
+
+    bool prt = false;
+
+    x[x_] = x0;
+    x[px_] = px_0;
+    x[y_] = y0;
+    x[py_] = py_0;
+    x[delta_] = delta;
+    x[ct_] = 0.0;
+    if (floqs)
+        // transform to phase space
+        LinTrans(nfloq, globval.Ascr, x);
+    for (i = 0; i <= 3; i++)
+        x[i] += globval.CODvect[i];
+
+    lastn = 0;
+    if (prt) {
+        printf("\n");
+        printf("chk_if_lost:\n");
+        printf("%4ld %7.3f %7.3f %7.3f %7.3f %7.3f %7.3f\n", lastn,
+                1e3 * x[x_], 1e3 * x[px_], 1e3 * x[y_], 1e3 * x[py_], 1e2
+                        * x[delta_], 1e3 * x[ct_]);
+    }
+    do {
+        lastn++;
+        if (globval.MatMeth)
+            Cell_fPass(x, lastpos);
+        else
+            Cell_Pass(0, globval.Cell_nLoc, x, lastpos);
+        if (prt)
+            printf("%4ld %7.3f %7.3f %7.3f %7.3f %7.3f %7.3f\n", lastn, 1e3
+                    * x[x_], 1e3 * x[px_], 1e3 * x[y_], 1e3 * x[py_], 1e2
+                    * x[delta_], 1e3 * x[ct_]);
+    } while ((lastn != nturn) && (lastpos == globval.Cell_nLoc));
+    return (lastn != nturn);
 }
 #undef nfloq
 
 /****************************************************************************/
 /* void getdynap(double *r, double phi, double delta, double eps,
-	      int nturn, bool floqs)
+ int nturn, bool floqs)
 
-   Purpose:
-       Binary search for dynamical aperture in Floquet space.
+ Purpose:
+ Binary search for dynamical aperture in Floquet space.
 
 
-   Input:
-       none
+ Input:
+ none
 
-   Output:
-       none
+ Output:
+ none
 
-   Return:
-       none
+ Return:
+ none
 
-   Global variables:
-       none
+ Global variables:
+ none
 
-   Specific functions:
-       chk_if_lost
+ Specific functions:
+ chk_if_lost
 
-   Comments:
-       none
+ Comments:
+ none
 
-****************************************************************************/
-void getdynap(double &r, double phi, double delta, double eps,
-	      int nturn, bool floqs)
-{
-  /* Determine dynamical aperture by binary search. */
-  double  rmin = 0.0, rmax = r;
-
-  const bool    prt   = false;
-  const double  r_reset = 1e-3, r0 = 10e-3;
-
-  if (prt) printf("\n");
-
-  if (globval.MatMeth) Cell_Concat(delta);
-  while (!chk_if_lost(rmax*cos(phi), rmax*sin(phi), delta, nturn, floqs)) {
-    if (rmax < r_reset) rmax = r0;
-    rmax *= 2.0;
-  }
-  while (rmax-rmin >= eps) {
-    r = rmin + (rmax-rmin)/2.0;
-    if (prt) printf("getdynap: %6.3f %6.3f %6.3f\n",
-		    1e3*rmin, 1e3*rmax, 1e3*r);
-    if (! chk_if_lost(r*cos(phi), r*sin(phi), delta, nturn, floqs) )
-      rmin = r;
-    else
-      rmax = r;
-    if (rmin > rmax) {
-      printf("getdynap: rmin > rmax\n");
-      exit_(0);
-    }
+ ****************************************************************************/
+void getdynap(double &r, double phi, double delta, double eps, int nturn,
+        bool floqs) {
+    /* Determine dynamical aperture by binary search. */
+    double rmin = 0.0, rmax = r;
 
-  }
-  r = rmin;
-}
+    const bool prt = false;
+    const double r_reset = 1e-3, r0 = 10e-3;
 
+    if (prt)
+        printf("\n");
 
+    if (globval.MatMeth)
+        Cell_Concat(delta);
+    while (!chk_if_lost(rmax * cos(phi), rmax * sin(phi), delta, nturn, floqs)) {
+        if (rmax < r_reset)
+            rmax = r0;
+        rmax *= 2.0;
+    }
+    while (rmax - rmin >= eps) {
+        r = rmin + (rmax - rmin) / 2.0;
+        if (prt)
+            printf("getdynap: %6.3f %6.3f %6.3f\n", 1e3 * rmin, 1e3 * rmax, 1e3
+                    * r);
+        if (!chk_if_lost(r * cos(phi), r * sin(phi), delta, nturn, floqs))
+            rmin = r;
+        else
+            rmax = r;
+        if (rmin > rmax) {
+            printf("getdynap: rmin > rmax\n");
+            exit_(0);
+        }
+
+    }
+    r = rmin;
+}
 
 /****************************************************************************/
 /* void getcsAscr(void)
 
-   Purpose:
-        Get Courant-Snyder Ascr
+ Purpose:
+ Get Courant-Snyder Ascr
 
 
-   Input:
-       none
+ Input:
+ none
 
-   Output:
-       none
+ Output:
+ none
 
-   Return:
-       none
+ Return:
+ none
 
-   Global variables:
-       none
+ Global variables:
+ none
 
-   Specific functions:
-       none
+ Specific functions:
+ none
 
-   Comments:
-       none
+ Comments:
+ none
 
-****************************************************************************/
-void getcsAscr(void)
-{
-  long i, j;
-  double phi;
-  Matrix R;
-
-  UnitMat(6, R);
-  for (i = 1; i <= 2; i++) {
-    phi = -atan2(globval.Ascr[i * 2 - 2][i * 2 - 1], globval.Ascr[i * 2 - 2]
-		[i * 2 - 2]);
-    R[i * 2 - 2][i * 2 - 2] = cos(phi);
-    R[i * 2 - 1][i * 2 - 1] = R[i * 2 - 2][i * 2 - 2];
-    R[i * 2 - 2][i * 2 - 1] = sin(phi);
-    R[i * 2 - 1][i * 2 - 2] = -R[i * 2 - 2][i * 2 - 1];
-  }
-  MulRMat(6, globval.Ascr, R);
-  for (i = 1; i <= 2; i++) {
-    if (globval.Ascr[i * 2 - 2][i * 2 - 2] < 0.0) {
-      for (j = 0; j <= 5; j++) {
-	globval.Ascr[j][i * 2 - 2] = -globval.Ascr[j][i * 2 - 2];
-	globval.Ascr[j][i * 2 - 1] = -globval.Ascr[j][i * 2 - 1];
-      }
-    }
-  }
-  if (!InvMat(6, globval.Ascrinv))
-    printf("  *** Ascr is singular\n");
-}
+ ****************************************************************************/
+void getcsAscr(void) {
+    long i, j;
+    double phi;
+    Matrix R;
 
+    UnitMat(6, R);
+    for (i = 1; i <= 2; i++) {
+        phi = -atan2(globval.Ascr[i * 2 - 2][i * 2 - 1],
+                globval.Ascr[i * 2 - 2][i * 2 - 2]);
+        R[i * 2 - 2][i * 2 - 2] = cos(phi);
+        R[i * 2 - 1][i * 2 - 1] = R[i * 2 - 2][i * 2 - 2];
+        R[i * 2 - 2][i * 2 - 1] = sin(phi);
+        R[i * 2 - 1][i * 2 - 2] = -R[i * 2 - 2][i * 2 - 1];
+    }
+    MulRMat(6, globval.Ascr, R);
+    for (i = 1; i <= 2; i++) {
+        if (globval.Ascr[i * 2 - 2][i * 2 - 2] < 0.0) {
+            for (j = 0; j <= 5; j++) {
+                globval.Ascr[j][i * 2 - 2] = -globval.Ascr[j][i * 2 - 2];
+                globval.Ascr[j][i * 2 - 1] = -globval.Ascr[j][i * 2 - 1];
+            }
+        }
+    }
+    if (!InvMat(6, globval.Ascrinv))
+        printf("  *** Ascr is singular\n");
+}
 
 /****************************************************************************/
 /* void dynap(double r, double delta, double eps, int npoint, int nturn,
-	   double x[], double y[], bool floqs, bool print)
+ double x[], double y[], bool floqs, bool print)
 
-   Purpose:
-       Determine the dynamical aperture by tracking using polar coordinates,
-       and sampling in phase.
-       Assumes mid-plane symmetry
+ Purpose:
+ Determine the dynamical aperture by tracking using polar coordinates,
+ and sampling in phase.
+ Assumes mid-plane symmetry
 
-   Input:
-       r initial guess
-       delta off momentum energy
-       eps precision for binary search
-       npoint sample number for phase coordinate
-       nturn number of turn for computing da
-       floqs true means Floquet space
-       print true means Print out to the screen
+ Input:
+ r initial guess
+ delta off momentum energy
+ eps precision for binary search
+ npoint sample number for phase coordinate
+ nturn number of turn for computing da
+ floqs true means Floquet space
+ print true means Print out to the screen
 
-   Output:
-       x[] horizontal dynamics aperture
-       y[] vertical dynamics aperture
+ Output:
+ x[] horizontal dynamics aperture
+ y[] vertical dynamics aperture
 
-   Return:
-       none
+ Return:
+ none
 
-   Global variables:
-       none
+ Global variables:
+ none
 
-   Specific functions:
-       getdynap
+ Specific functions:
+ getdynap
 
-   Comments:
-       none
+ Comments:
+ none
 
-****************************************************************************/
-void dynap(FILE *fp, double r, const double delta,
-	   const double eps, const int npoint, const int nturn,
-	   double x[], double y[], const bool floqs, const bool print)
+ ****************************************************************************/
+void dynap(FILE *fp, double r, const double delta, const double eps,
+        const int npoint, const int nturn, double x[], double y[],
+        const bool floqs, const bool print)
 
 {
-  /* Determine the dynamical aperture by tracking.
+    /* Determine the dynamical aperture by tracking.
      Assumes mid-plane symmetry.                    */
 
-  long int  i, lastpos;
-  double    phi, x_min, x_max, y_min, y_max;
-
-  getcod(delta, lastpos);
-  if (floqs) {
-    Ring_GetTwiss(false, delta);
-    if (print) {
-      printf("\n");
-      printf("Dynamical Aperture (Floquet space):\n");
-      printf("     x^         y^\n");
-      printf("\n");
-    }
-    fprintf(fp, "# Dynamical Aperture (Floquet space):\n");
-    fprintf(fp, "#      x^         y^\n");
-    fprintf(fp, "#\n");
-  } else {
-    if (print) {
-      printf("\n");
-      printf("Dynamical Aperture:\n");
-      printf("     x      y\n");
-      printf("    [mm]   [mm]\n");
-      printf("\n");
-    }
-    fprintf(fp, "# Dynamical Aperture:\n");
-    fprintf(fp, "#    x      y\n");
-    fprintf(fp, "#   [mm]   [mm]\n");
-    fprintf(fp, "#\n");
-  }
-
-  x_min = 0.0; x_max = 0.0; y_min = 0.0; y_max = 0.0;
-  for (i = 0; i < npoint; i++) {
-    phi = i*M_PI/(npoint-1);
-    if (i == 0) 
-      phi = 1e-3;
-    else if (i == npoint-1)
-      phi -= 1e-3;
-    getdynap(r, phi, delta, eps, nturn, floqs);
-    x[i] = r*cos(phi); y[i] = r*sin(phi);
-    x_min = min(x[i], x_min); x_max = max(x[i], x_max);
-    y_min = min(y[i], y_min); y_max = max(y[i], y_max);
-    if (!floqs) {
-      if (print)
-        printf("  %6.2f %6.2f\n", 1e3*x[i], 1e3*y[i]);
-      fprintf(fp, "  %6.2f %6.2f\n", 1e3*x[i], 1e3*y[i]);
+    long int i, lastpos;
+    double phi, x_min, x_max, y_min, y_max;
+
+    getcod(delta, lastpos);
+    if (floqs) {
+        Ring_GetTwiss(false, delta);
+        if (print) {
+            printf("\n");
+            printf("Dynamical Aperture (Floquet space):\n");
+            printf("     x^         y^\n");
+            printf("\n");
+        }
+        fprintf(fp, "# Dynamical Aperture (Floquet space):\n");
+        fprintf(fp, "#      x^         y^\n");
+        fprintf(fp, "#\n");
     } else {
-      if (print)
-        printf("  %10.3e %10.3e\n", x[i], y[i]);
-      fprintf(fp, "  %10.3e %10.3e\n", x[i], y[i]);
+        if (print) {
+            printf("\n");
+            printf("Dynamical Aperture:\n");
+            printf("     x      y\n");
+            printf("    [mm]   [mm]\n");
+            printf("\n");
+        }
+        fprintf(fp, "# Dynamical Aperture:\n");
+        fprintf(fp, "#    x      y\n");
+        fprintf(fp, "#   [mm]   [mm]\n");
+        fprintf(fp, "#\n");
     }
-    fflush(fp);
-  }
 
-  if (print) {
-    printf("\n");
-    printf("  x^: %6.2f - %5.2f y^: %6.2f - %5.2f mm\n",
-	   1e3*x_min, 1e3*x_max, 1e3*y_min, 1e3*y_max);
-  }
+    x_min = 0.0;
+    x_max = 0.0;
+    y_min = 0.0;
+    y_max = 0.0;
+    for (i = 0; i < npoint; i++) {
+        phi = i * M_PI / (npoint - 1);
+        if (i == 0)
+            phi = 1e-3;
+        else if (i == npoint - 1)
+            phi -= 1e-3;
+        getdynap(r, phi, delta, eps, nturn, floqs);
+        x[i] = r * cos(phi);
+        y[i] = r * sin(phi);
+        x_min = min(x[i], x_min);
+        x_max = max(x[i], x_max);
+        y_min = min(y[i], y_min);
+        y_max = max(y[i], y_max);
+        if (!floqs) {
+            if (print)
+                printf("  %6.2f %6.2f\n", 1e3 * x[i], 1e3 * y[i]);
+            fprintf(fp, "  %6.2f %6.2f\n", 1e3 * x[i], 1e3 * y[i]);
+        } else {
+            if (print)
+                printf("  %10.3e %10.3e\n", x[i], y[i]);
+            fprintf(fp, "  %10.3e %10.3e\n", x[i], y[i]);
+        }
+        fflush(fp);
+    }
+
+    if (print) {
+        printf("\n");
+        printf("  x^: %6.2f - %5.2f y^: %6.2f - %5.2f mm\n", 1e3 * x_min, 1e3
+                * x_max, 1e3 * y_min, 1e3 * y_max);
+    }
 }
 
 /****************************************************************************/
 /* double get_aper(int n, double x[], double y[])
 
-   Purpose:
-   
+ Purpose:
 
-   Input:
-       none
 
-   Output:
-       none
+ Input:
+ none
 
-   Return:
-       none
+ Output:
+ none
 
-   Global variables:
-       none
+ Return:
+ none
 
-   Specific functions:
-       none
+ Global variables:
+ none
 
-   Comments:
-       none
+ Specific functions:
+ none
 
-****************************************************************************/
-double get_aper(int n, double x[], double y[])
-{
-  int     i;
-  double  A;
+ Comments:
+ none
+
+ ****************************************************************************/
+double get_aper(int n, double x[], double y[]) {
+    int i;
+    double A;
 
-  A = 0.0;
-  for (i = 2; i <= n; i++)
-    A += x[i-2]*y[i-1] - x[i-1]*y[i-2];
-  A += x[n-1]*y[0] - x[0]*y[n-1];
-// x2 from mid-plane symmetry
-  A = fabs(A);
-//  printf("\n");
-//  printf("  Dyn. Aper.: %5.1f mm^2\n", 1e6*A);
-  return(A);
+    A = 0.0;
+    for (i = 2; i <= n; i++)
+        A += x[i - 2] * y[i - 1] - x[i - 1] * y[i - 2];
+    A += x[n - 1] * y[0] - x[0] * y[n - 1];
+    // x2 from mid-plane symmetry
+    A = fabs(A);
+    //  printf("\n");
+    //  printf("  Dyn. Aper.: %5.1f mm^2\n", 1e6*A);
+    return (A);
 }
 
+void GetTrack(const char *file_name, long *n, double x[], double px[],
+        double y[], double py[]) {
+    int k;
+    char line[200];
+    FILE *inf;
 
-void GetTrack(const char *file_name,
-	      long *n, double x[], double px[], double y[], double py[])
-{
-  int   k;
-  char  line[200];
-  FILE  *inf;
+    inf = file_read(file_name);
 
-  inf = file_read(file_name);
+    do {
+        fgets(line, 200, inf);
+    } while (strstr(line, "#") != NULL);
 
-  do {
+    // skip initial conditions
     fgets(line, 200, inf);
-  } while (strstr(line, "#") != NULL);
 
-  // skip initial conditions
-  fgets(line, 200, inf);
+    do {
+        sscanf(line, "%d", &k);
+        sscanf(line, "%*d %lf %lf %lf %lf", &x[k - 1], &px[k - 1], &y[k - 1],
+                &py[k - 1]);
+    } while (fgets(line, 200, inf) != NULL);
 
-  do {
-     sscanf(line, "%d", &k);
-     sscanf(line, "%*d %lf %lf %lf %lf", &x[k-1], &px[k-1], &y[k-1], &py[k-1]);
-  } while (fgets(line, 200, inf) != NULL);
+    *n = k;
 
-  *n = k;
-
-   fclose(inf);
+    fclose(inf);
 }
 
-
 /****************************************************************************/
 /* void Getj(long n, double *x, double *px, double *y, double *py)
 
-   Purpose:
-        Calculates the linear invariant
+ Purpose:
+ Calculates the linear invariant
 
-   Input:
-       none
+ Input:
+ none
 
-   Output:
-       none
+ Output:
+ none
 
-   Return:
-       none
+ Return:
+ none
 
-   Global variables:
-       none
+ Global variables:
+ none
 
-   Specific functions:
-       none
+ Specific functions:
+ none
 
-   Comments:
-       none
+ Comments:
+ none
 
-****************************************************************************/
-void Getj(long n, double *x, double *px, double *y, double *py)
-{
-  long int i;
+ ****************************************************************************/
+void Getj(long n, double *x, double *px, double *y, double *py) {
+    long int i;
 
-  for (i = 0; i < n; i++) {
-    x[i] = (pow(x[i], 2)+pow(px[i], 2))/2.0;
-    y[i] = (pow(y[i], 2)+pow(py[i], 2))/2.0;
-  }
+    for (i = 0; i < n; i++) {
+        x[i] = (pow(x[i], 2) + pow(px[i], 2)) / 2.0;
+        y[i] = (pow(y[i], 2) + pow(py[i], 2)) / 2.0;
+    }
 }
 
 /****************************************************************************/
 /* double GetArg(double x, double px, double nu)
 
-   Purpose:
-       get argument of x
+ Purpose:
+ get argument of x
 
-   Input:
-       none
+ Input:
+ none
 
-   Output:
-       none
+ Output:
+ none
 
-   Return:
-       none
+ Return:
+ none
 
-   Global variables:
-       none
+ Global variables:
+ none
 
-   Specific functions:
-       none
+ Specific functions:
+ none
 
-   Comments:
-       17/07/03 use M_PI instead of pi
+ Comments:
+ 17/07/03 use M_PI instead of pi
 
-****************************************************************************/
-double GetArg(double x, double px, double nu)
-{
-  double phi, val;
+ ****************************************************************************/
+double GetArg(double x, double px, double nu) {
+    double phi, val;
 
-  phi = GetAngle(x, px);
-  if (phi < 0.0)
-    phi += 2.0 * M_PI;
-  val = phi + Fract(nu) * 2.0 * M_PI;
-  if (val < 0.0)
-    val += 2.0 * M_PI;
-  return val;
+    phi = GetAngle(x, px);
+    if (phi < 0.0)
+        phi += 2.0 * M_PI;
+    val = phi + Fract(nu) * 2.0 * M_PI;
+    if (val < 0.0)
+        val += 2.0 * M_PI;
+    return val;
 }
 
 /****************************************************************************/
 /* void GetPhi(long n, double *x, double *px, double *y, double *py)
 
-   Purpose:
-       get linear phases
+ Purpose:
+ get linear phases
 
-   Input:
-       none
+ Input:
+ none
 
-   Output:
-       none
+ Output:
+ none
 
-   Return:
-       none
+ Return:
+ none
 
-   Global variables:
-       none
+ Global variables:
+ none
 
-   Specific functions:
-       none
+ Specific functions:
+ none
 
-   Comments:
-       none
+ Comments:
+ none
 
-****************************************************************************/
-void GetPhi(long n, double *x, double *px, double *y, double *py)
-{
-  /* Calculates the linear phase */
-  long i;
+ ****************************************************************************/
+void GetPhi(long n, double *x, double *px, double *y, double *py) {
+    /* Calculates the linear phase */
+    long i;
 
-  for (i = 1; i <= n; i++) {
-    x[i - 1] = GetArg(x[i - 1], px[i - 1], i * globval.TotalTune[0]);
-    y[i - 1] = GetArg(y[i - 1], py[i - 1], i * globval.TotalTune[1]);
-  }
+    for (i = 1; i <= n; i++) {
+        x[i - 1] = GetArg(x[i - 1], px[i - 1], i * globval.TotalTune[0]);
+        y[i - 1] = GetArg(y[i - 1], py[i - 1], i * globval.TotalTune[1]);
+    }
 }
 
-
 /*********************************/
 /* Routines for Fourier analysis */
 /*********************************/
 
-void Sinfft(int n, double xr[])
-{
-  /* DFT with sine window */
-  int     i;
-  double  xi[n];
+void Sinfft(int n, double xr[]) {
+    /* DFT with sine window */
+    int i;
+    double xi[n];
 
-  for (i = 0; i < n; i++) {
-    xr[i] = sin((double)i/(double)n*M_PI)*xr[i]; xi[i] = 0.0;
-  }
-  FFT(n, xr, xi);
-  for (i = 0; i < n; i++)
-    xr[i] = sqrt(xr[i]*xr[i]+xi[i]*xi[i]);
+    for (i = 0; i < n; i++) {
+        xr[i] = sin((double) i / (double) n * M_PI) * xr[i];
+        xi[i] = 0.0;
+    }
+    FFT(n, xr, xi);
+    for (i = 0; i < n; i++)
+        xr[i] = sqrt(xr[i] * xr[i] + xi[i] * xi[i]);
 }
 
-void sin_FFT(int n, double xr[])
-{
-  /* DFT with sine window */
-  int     i;
-  double  *xi;
+void sin_FFT(int n, double xr[]) {
+    /* DFT with sine window */
+    int i;
+    double *xi;
 
-  xi = dvector(1, 2*n);
+    xi = dvector(1, 2 * n);
 
-  for (i = 1; i <= n; i++) {
-    xi[2*i-1] = sin((double)i/n*M_PI)*xr[i-1]; xi[2*i] = 0.0;
-  }
-  dfour1(xi, (unsigned long)n, 1);
-  for (i = 1; i <= n; i++)
-    xr[i-1] = sqrt(pow(xi[2*i-1], 2)+pow(xi[2*i], 2))*2.0/n;
+    for (i = 1; i <= n; i++) {
+        xi[2 * i - 1] = sin((double) i / n * M_PI) * xr[i - 1];
+        xi[2 * i] = 0.0;
+    }
+    dfour1(xi, (unsigned long) n, 1);
+    for (i = 1; i <= n; i++)
+        xr[i - 1] = sqrt(pow(xi[2 * i - 1], 2) + pow(xi[2 * i], 2)) * 2.0 / n;
 
-  free_dvector(xi, 1, 2*n);
+    free_dvector(xi, 1, 2 * n);
 }
 
+void sin_FFT(int n, double xr[], double xi[]) {
+    /* DFT with sine window */
+    int i;
+    double *xri;
 
-void sin_FFT(int n, double xr[], double xi[])
-{
-  /* DFT with sine window */
-  int      i;
-  double  *xri;
-
-  xri = dvector(1, 2*n);
+    xri = dvector(1, 2 * n);
 
-  for (i = 1; i <= n; i++) {
-    xri[2*i-1] = sin((double)i/n*M_PI)*xr[i-1];
-    xri[2*i] = sin((double)i/n*M_PI)*xi[i-1];
-  }
-  dfour1(xri, (unsigned long)n, 1);
-  for (i = 1; i <= n; i++) {
-    xr[i-1] = sqrt(pow(xri[2*i-1], 2)+pow(xri[2*i], 2))*2.0/n;
-    xi[i-1] = atan2(xri[2*i], xri[2*i-1]);
-  }
+    for (i = 1; i <= n; i++) {
+        xri[2 * i - 1] = sin((double) i / n * M_PI) * xr[i - 1];
+        xri[2 * i] = sin((double) i / n * M_PI) * xi[i - 1];
+    }
+    dfour1(xri, (unsigned long) n, 1);
+    for (i = 1; i <= n; i++) {
+        xr[i - 1] = sqrt(pow(xri[2 * i - 1], 2) + pow(xri[2 * i], 2)) * 2.0 / n;
+        xi[i - 1] = atan2(xri[2 * i], xri[2 * i - 1]);
+    }
 
-  free_dvector(xri, 1, 2*n);
+    free_dvector(xri, 1, 2 * n);
 }
 
-
-void GetInd(int n, int k, int *ind1, int *ind3)
-{
-  if (k == 1) {
-    *ind1 = 2; *ind3 = 2;
-  } else if (k == n/2+1) {
-    *ind1 = n/2; *ind3 = n/2;
-  } else {
-    *ind1 = k - 1; *ind3 = k + 1;
-  }
+void GetInd(int n, int k, int *ind1, int *ind3) {
+    if (k == 1) {
+        *ind1 = 2;
+        *ind3 = 2;
+    } else if (k == n / 2 + 1) {
+        *ind1 = n / 2;
+        *ind3 = n / 2;
+    } else {
+        *ind1 = k - 1;
+        *ind3 = k + 1;
+    }
 }
 
-
-void GetInd1(int n, int k, int *ind1, int *ind3)
-{
-  if (k == 1) {
-    *ind1 = 2; *ind3 = 2;
-  } else if (k == n) {
-    *ind1 = n - 1; *ind3 = n - 1;
-  } else {
-    *ind1 = k - 1; *ind3 = k + 1;
-  }
+void GetInd1(int n, int k, int *ind1, int *ind3) {
+    if (k == 1) {
+        *ind1 = 2;
+        *ind3 = 2;
+    } else if (k == n) {
+        *ind1 = n - 1;
+        *ind3 = n - 1;
+    } else {
+        *ind1 = k - 1;
+        *ind3 = k + 1;
+    }
 }
 
-
-void GetPeak(int n, double *x, int *k)
-{
-  /* Locate peak in DFT spectrum */
-  int ind1, ind2, ind3;
-  double peak;
-
-  peak = 0.0; *k = 1;
-  for (ind2 = 1; ind2 <= n/2+1; ind2++) {
-    GetInd(n, ind2, &ind1, &ind3);
-    if (x[ind2-1] > peak && x[ind1-1] < x[ind2-1] &&
-        x[ind3-1] < x[ind2-1])
-    {
-      peak = x[ind2-1]; *k = ind2;
+void GetPeak(int n, double *x, int *k) {
+    /* Locate peak in DFT spectrum */
+    int ind1, ind2, ind3;
+    double peak;
+
+    peak = 0.0;
+    *k = 1;
+    for (ind2 = 1; ind2 <= n / 2 + 1; ind2++) {
+        GetInd(n, ind2, &ind1, &ind3);
+        if (x[ind2 - 1] > peak && x[ind1 - 1] < x[ind2 - 1] && x[ind3 - 1]
+                < x[ind2 - 1]) {
+            peak = x[ind2 - 1];
+            *k = ind2;
+        }
     }
-  }
 }
 
-
-void GetPeak1(int n, double *x, int *k)
-{
-  /* Locate peak in DFT spectrum */
-  int ind1, ind2, ind3;
-  double peak;
-
-  peak = 0.0; *k = 1;
-  for (ind2 = 1; ind2 <= n; ind2++) {
-    GetInd1(n, ind2, &ind1, &ind3);
-    if (x[ind2-1] > peak && x[ind1-1] < x[ind2-1] &&
-        x[ind3-1] < x[ind2-1])
-    {
-      peak = x[ind2-1]; *k = ind2;
+void GetPeak1(int n, double *x, int *k) {
+    /* Locate peak in DFT spectrum */
+    int ind1, ind2, ind3;
+    double peak;
+
+    peak = 0.0;
+    *k = 1;
+    for (ind2 = 1; ind2 <= n; ind2++) {
+        GetInd1(n, ind2, &ind1, &ind3);
+        if (x[ind2 - 1] > peak && x[ind1 - 1] < x[ind2 - 1] && x[ind3 - 1]
+                < x[ind2 - 1]) {
+            peak = x[ind2 - 1];
+            *k = ind2;
+        }
     }
-  }
 }
 
-
-double Int2snu(int n, double *x, int k)
-{
-  /* Get frequency by nonlinear interpolation with two samples
+double Int2snu(int n, double *x, int k) {
+    /* Get frequency by nonlinear interpolation with two samples
      for sine window. The interpolation is:
 
-              1              2 A(k)       1
-         nu = - [ k - 1 + ------------- - - ] ,      k-1 <= N nu <= k
-              N           A(k-1) + A(k)   2
-   */
-  int ind, ind1, ind3;
-  double ampl1, ampl2;
-
-  GetInd(n, k, &ind1, &ind3);
-  if (x[ind3 - 1] > x[ind1 - 1]) {
-    ampl1 = x[k - 1];
-    ampl2 = x[ind3 - 1];
-    ind = k;
-  } else {
-    ampl1 = x[ind1 - 1];
-    ampl2 = x[k - 1];
-    /* Interpolate in right direction for 0 frequency */
-    if (k != 1)
-      ind = ind1;
+     1              2 A(k)       1
+     nu = - [ k - 1 + ------------- - - ] ,      k-1 <= N nu <= k
+     N           A(k-1) + A(k)   2
+     */
+    int ind, ind1, ind3;
+    double ampl1, ampl2;
+
+    GetInd(n, k, &ind1, &ind3);
+    if (x[ind3 - 1] > x[ind1 - 1]) {
+        ampl1 = x[k - 1];
+        ampl2 = x[ind3 - 1];
+        ind = k;
+    } else {
+        ampl1 = x[ind1 - 1];
+        ampl2 = x[k - 1];
+        /* Interpolate in right direction for 0 frequency */
+        if (k != 1)
+            ind = ind1;
+        else
+            ind = 0;
+    }
+    /* Avoid division by zero */
+    if (ampl1 + ampl2 != 0.0)
+        return ((ind - 1 + 2 * ampl2 / (ampl1 + ampl2) - 0.5) / n);
     else
-      ind = 0;
-  }
-  /* Avoid division by zero */
-  if (ampl1 + ampl2 != 0.0)
-    return ((ind - 1 + 2 * ampl2 / (ampl1 + ampl2) - 0.5) / n);
-  else
-    return 0.0;
+        return 0.0;
 }
 
-
 /****************************************************************************/
 /* double Sinc(double omega)
 
-   Purpose:
+ Purpose:
 
 
-   Input:
-       none
+ Input:
+ none
 
-   Output:
-       none
+ Output:
+ none
 
-   Return:
-       none
+ Return:
+ none
 
-   Global variables:
-       none
+ Global variables:
+ none
 
-   Specific functions:
-       none
+ Specific functions:
+ none
 
-   Comments:
-       zero test to be changed numericallywise
+ Comments:
+ zero test to be changed numericallywise
 
-****************************************************************************/
-double Sinc(double omega)
-{
-  /*  Function to calculate:
+ ****************************************************************************/
+double Sinc(double omega) {
+    /*  Function to calculate:
 
-                        sin( omega )
-                        ------------
-                           omega
-  */
-  if (omega != 0.0)
-    return (sin(omega) / omega);
-  else
-    return 1.0;
+     sin( omega )
+     ------------
+     omega
+     */
+    if (omega != 0.0)
+        return (sin(omega) / omega);
+    else
+        return 1.0;
 }
 
-
 /****************************************************************************/
 /* double intsampl(long n, double *x, double nu, long k)
 
-   Purpose:
+ Purpose:
 
 
-   Input:
-       none
+ Input:
+ none
 
-   Output:
-       none
+ Output:
+ none
 
-   Return:
-       none
+ Return:
+ none
 
-   Global variables:
-       none
+ Global variables:
+ none
 
-   Specific functions:
-       none
+ Specific functions:
+ none
 
-   Comments:
-       17/07/03 use M_PI instead of pi
+ Comments:
+ 17/07/03 use M_PI instead of pi
 
-****************************************************************************/
-double intsampl(int n, double *x, double nu, int k)
-{
-  /* Get amplitude by nonlinear interpolation for sine window. The
+ ****************************************************************************/
+double intsampl(int n, double *x, double nu, int k) {
+    /* Get amplitude by nonlinear interpolation for sine window. The
      distribution is given by:
 
-                   1    sin pi ( k + 1/2 )     sin pi ( k - 1/2 )
-           F(k) =  - ( -------------------- + -------------------- )
-                   2      pi ( k + 1/2 )          pi ( k - 1/2 )
-   */
-  double corr;
+     1    sin pi ( k + 1/2 )     sin pi ( k - 1/2 )
+     F(k) =  - ( -------------------- + -------------------- )
+     2      pi ( k + 1/2 )          pi ( k - 1/2 )
+     */
+    double corr;
 
-  corr = (Sinc(M_PI * (k - 1 + 0.5 - nu * n)) +
-          Sinc(M_PI * (k - 1 - 0.5 - nu * n))) / 2;
-  return (x[k - 1] / corr);
+    corr = (Sinc(M_PI * (k - 1 + 0.5 - nu * n)) + Sinc(M_PI * (k - 1 - 0.5 - nu
+            * n))) / 2;
+    return (x[k - 1] / corr);
 }
 
-
 /****************************************************************************/
 /* double linint(long n, long k, double nu, double *x)
 
-   Purpose:
+ Purpose:
 
 
-   Input:
-       none
+ Input:
+ none
 
-   Output:
-       none
+ Output:
+ none
 
-   Return:
-       none
+ Return:
+ none
 
-   Global variables:
-       none
+ Global variables:
+ none
 
-   Specific functions:
-       none
+ Specific functions:
+ none
 
-   Comments:
-       17/07/03 use M_PI instead of pi
+ Comments:
+ 17/07/03 use M_PI instead of pi
 
-****************************************************************************/
-double linint(int n, int k, double nu, double *x)
-{
-  /* Get phase by linear interpolation for rectangular window
+ ****************************************************************************/
+double linint(int n, int k, double nu, double *x) {
+    /* Get phase by linear interpolation for rectangular window
      with -pi <= phi <= pi */
-  int     i;
-  double  phi;
-  double  xr[n], xi[n];
-
-  for (i = 0; i < n; i++) {
-    xr[i] = x[i]; xi[i] = 0.0;
-  }
-  FFT(n, xr, xi);
-  phi = GetAngle(xr[k-1], xi[k-1]) - (n*nu-k+1)*M_PI;
-  if (phi > M_PI)
-    phi -= 2.0*M_PI;
-  else if (phi < -M_PI)
-    phi += 2.0*M_PI;
-  return phi;
+    int i;
+    double phi;
+    double xr[n], xi[n];
+
+    for (i = 0; i < n; i++) {
+        xr[i] = x[i];
+        xi[i] = 0.0;
+    }
+    FFT(n, xr, xi);
+    phi = GetAngle(xr[k - 1], xi[k - 1]) - (n * nu - k + 1) * M_PI;
+    if (phi > M_PI)
+        phi -= 2.0 * M_PI;
+    else if (phi < -M_PI)
+        phi += 2.0 * M_PI;
+    return phi;
 }
 
 /****************************************************************************/
 /* void FndRes(struct LOC_findres *LINK)
 
-   Purpose:
-
-
-   Input:
-       none
-
-   Output:
-       none
-
-   Return:
-       none
-
-   Global variables:
-       none
-
-   Specific functions:
-       none
-
-   Comments:
-       none
-
-****************************************************************************/
-void FndRes(struct LOC_findres *LINK)
-{
-  int i, j, FORLIM, FORLIM1;
-  double delta;
-
-  FORLIM = LINK->n;
-  for (i = 0; i <= FORLIM; i++) {
-    FORLIM1 = LINK->n;
-    for (j = -LINK->n; j <= FORLIM1; j++) {
-      delta = fabs(i * LINK->nux + j * LINK->nuy);
-      delta -= (int)delta;
-      if (delta > 0.5)
-	delta = 1 - delta;
-      delta = fabs(delta - LINK->f);
-      delta -= (int)delta;
-      if (delta > 0.5)
-	delta = 1 - delta;
-      if (delta < LINK->eps) {
-	if (abs(i) + abs(j) < LINK->n && (i != 0 || j >= 0)) {
-	  LINK->found = true;
-	  *LINK->nx = i;
-	  *LINK->ny = j;
-	}
-      }
-    }
-  }
+ Purpose:
+
+
+ Input:
+ none
+
+ Output:
+ none
+
+ Return:
+ none
+
+ Global variables:
+ none
+
+ Specific functions:
+ none
+
+ Comments:
+ none
+
+ ****************************************************************************/
+void FndRes(struct LOC_findres *LINK) {
+    int i, j, FORLIM, FORLIM1;
+    double delta;
+
+    FORLIM = LINK->n;
+    for (i = 0; i <= FORLIM; i++) {
+        FORLIM1 = LINK->n;
+        for (j = -LINK->n; j <= FORLIM1; j++) {
+            delta = fabs(i * LINK->nux + j * LINK->nuy);
+            delta -= (int) delta;
+            if (delta > 0.5)
+                delta = 1 - delta;
+            delta = fabs(delta - LINK->f);
+            delta -= (int) delta;
+            if (delta > 0.5)
+                delta = 1 - delta;
+            if (delta < LINK->eps) {
+                if (abs(i) + abs(j) < LINK->n && (i != 0 || j >= 0)) {
+                    LINK->found = true;
+                    *LINK->nx = i;
+                    *LINK->ny = j;
+                }
+            }
+        }
+    }
 }
 
-
 /****************************************************************************/
 /* void FindRes(long n_, double nux_, double nuy_, double f_,
-             long *nx_, long *ny_)
+ long *nx_, long *ny_)
 
-   Purpose:
+ Purpose:
 
 
-   Input:
-       none
+ Input:
+ none
 
-   Output:
-       none
+ Output:
+ none
 
-   Return:
-       none
+ Return:
+ none
 
-   Global variables:
-       none
+ Global variables:
+ none
 
-   Specific functions:
-       none
+ Specific functions:
+ none
 
-   Comments:
-       none
+ Comments:
+ none
 
-****************************************************************************/
-void FindRes(int n_, double nux_, double nuy_, double f_, int *nx_, int *ny_)
-{
-  /* Match f by a linear combination of nux and nuy */
-  struct LOC_findres V;
+ ****************************************************************************/
+void FindRes(int n_, double nux_, double nuy_, double f_, int *nx_, int *ny_) {
+    /* Match f by a linear combination of nux and nuy */
+    struct LOC_findres V;
 
-  V.n = n_;
-  V.nux = nux_;
-  V.nuy = nuy_;
-  V.f = f_;
-  V.nx = nx_;
-  V.ny = ny_;
-  V.found = false;
-  V.eps = 0.5e-6;
-  do {
-    V.eps = 10 * V.eps;
-    FndRes(&V);
-  } while (!V.found);
+    V.n = n_;
+    V.nux = nux_;
+    V.nuy = nuy_;
+    V.f = f_;
+    V.nx = nx_;
+    V.ny = ny_;
+    V.found = false;
+    V.eps = 0.5e-6;
+    do {
+        V.eps = 10 * V.eps;
+        FndRes(&V);
+    } while (!V.found);
 }
 
+void GetPeaks(int n, double *x, int nf, double *nu, double *A) {
+    int i, k, ind1, ind3;
 
-void GetPeaks(int n, double *x, int nf, double *nu, double *A)
-{
-  int i, k, ind1, ind3;
-
-  for (i = 0; i < nf; i++) {
-    GetPeak(n, x, &k);
-    nu[i] = Int2snu(n, x, k); A[i] = intsampl(n, x, nu[i], k);
-    /* Make peak flat to allow for new call */
-    GetInd(n, k, &ind1, &ind3);
-    if (x[ind1-1] > x[ind3-1])
-      x[k-1] = x[ind1-1];
-    else
-      x[k-1] = x[ind3-1];
-  }
+    for (i = 0; i < nf; i++) {
+        GetPeak(n, x, &k);
+        nu[i] = Int2snu(n, x, k);
+        A[i] = intsampl(n, x, nu[i], k);
+        /* Make peak flat to allow for new call */
+        GetInd(n, k, &ind1, &ind3);
+        if (x[ind1 - 1] > x[ind3 - 1])
+            x[k - 1] = x[ind1 - 1];
+        else
+            x[k - 1] = x[ind3 - 1];
+    }
 }
 
+void GetPeaks1(int n, double *x, int nf, double *nu, double *A) {
+    int i, k, ind1, ind3;
 
-void GetPeaks1(int n, double *x, int nf, double *nu, double *A)
-{
-  int i, k, ind1, ind3;
-
-  for (i = 0; i < nf; i++) {
-    GetPeak1(n, x, &k);
-    nu[i] = Int2snu(n, x, k); A[i] = intsampl(n, x, nu[i], k);
-    /* Make peak flat to allow for new call */
-    GetInd1(n, k, &ind1, &ind3);
-    if (x[ind1-1] > x[ind3-1])
-      x[k-1] = x[ind1-1];
-    else
-      x[k-1] = x[ind3-1];
-  }
+    for (i = 0; i < nf; i++) {
+        GetPeak1(n, x, &k);
+        nu[i] = Int2snu(n, x, k);
+        A[i] = intsampl(n, x, nu[i], k);
+        /* Make peak flat to allow for new call */
+        GetInd1(n, k, &ind1, &ind3);
+        if (x[ind1 - 1] > x[ind3 - 1])
+            x[k - 1] = x[ind1 - 1];
+        else
+            x[k - 1] = x[ind3 - 1];
+    }
 }
 
 /*******************************/
 /* Routines for magnetic error */
 /*******************************/
 
-void SetTol(int Fnum, double dxrms, double dyrms, double drrms)
-{
-  int   i;
-  long  k;
-
-  for (i = 1; i <= GetnKid(Fnum); i++) {
-    k = Elem_GetPos(Fnum, i);
-    Cell[k].Elem.M->PdSrms[X_] = dxrms;
-    Cell[k].Elem.M->PdSrnd[X_] = normranf();
-    Cell[k].Elem.M->PdSrms[Y_] = dyrms;
-    Cell[k].Elem.M->PdSrnd[Y_] = normranf();
-    Cell[k].Elem.M->PdTrms = drrms;
-    Cell[k].Elem.M->PdTrnd = normranf();
-    Mpole_SetdS(Fnum, i); Mpole_SetdT(Fnum, i);
-  }
+void SetTol(int Fnum, double dxrms, double dyrms, double drrms) {
+    int i;
+    long k;
+
+    for (i = 1; i <= GetnKid(Fnum); i++) {
+        k = Elem_GetPos(Fnum, i);
+        Cell[k].Elem.M->PdSrms[X_] = dxrms;
+        Cell[k].Elem.M->PdSrnd[X_] = normranf();
+        Cell[k].Elem.M->PdSrms[Y_] = dyrms;
+        Cell[k].Elem.M->PdSrnd[Y_] = normranf();
+        Cell[k].Elem.M->PdTrms = drrms;
+        Cell[k].Elem.M->PdTrnd = normranf();
+        Mpole_SetdS(Fnum, i);
+        Mpole_SetdT(Fnum, i);
+    }
 }
 
+void Scale_Tol(int Fnum, double dxrms, double dyrms, double drrms) {
+    int Knum;
+    long int loc;
 
-void Scale_Tol(int Fnum, double dxrms, double dyrms, double drrms)
-{
-  int       Knum;
-  long int  loc;
-
-  for (Knum = 1; Knum <= GetnKid(Fnum); Knum++) {
-    loc = Elem_GetPos(Fnum, Knum);
-    Cell[loc].Elem.M->PdSrms[X_] = dxrms; Cell[loc].Elem.M->PdSrms[Y_] = dyrms;
-    Cell[loc].Elem.M->PdTrms    = drrms;
-    Mpole_SetdS(Fnum, Knum); Mpole_SetdT(Fnum, Knum);
-  }
+    for (Knum = 1; Knum <= GetnKid(Fnum); Knum++) {
+        loc = Elem_GetPos(Fnum, Knum);
+        Cell[loc].Elem.M->PdSrms[X_] = dxrms;
+        Cell[loc].Elem.M->PdSrms[Y_] = dyrms;
+        Cell[loc].Elem.M->PdTrms = drrms;
+        Mpole_SetdS(Fnum, Knum);
+        Mpole_SetdT(Fnum, Knum);
+    }
 }
 
-
 /****************************************************************************/
 /* void SetaTol(int Fnum, int Knum, double dx, double dy, double dr)
 
-   Purpose:
-       Set a known random multipole displacement error
+ Purpose:
+ Set a known random multipole displacement error
 
-   Input:
-       none
+ Input:
+ none
 
-   Output:
-       none
+ Output:
+ none
 
-   Return:
-       none
+ Return:
+ none
 
-   Global variables:
-       none
+ Global variables:
+ none
 
-   Specific functions:
-       none
+ Specific functions:
+ none
 
-   Comments:
-       none
+ Comments:
+ none
 
-****************************************************************************/
-void SetaTol(int Fnum, int Knum, double dx, double dy, double dr)
-{
-  long int  loc;
+ ****************************************************************************/
+void SetaTol(int Fnum, int Knum, double dx, double dy, double dr) {
+    long int loc;
 
-  loc = Elem_GetPos(Fnum, Knum);
-  Cell[loc].Elem.M->PdSrms[0] = dx; Cell[loc].Elem.M->PdSrnd[0] = 1e0;
-  Cell[loc].Elem.M->PdSrms[1] = dy; Cell[loc].Elem.M->PdSrnd[1] = 1e0;
-  Cell[loc].Elem.M->PdTrms    = dr; Cell[loc].Elem.M->PdTrnd    = 1e0;
-  Mpole_SetdS(Fnum, Knum); Mpole_SetdT(Fnum, Knum);
+    loc = Elem_GetPos(Fnum, Knum);
+    Cell[loc].Elem.M->PdSrms[0] = dx;
+    Cell[loc].Elem.M->PdSrnd[0] = 1e0;
+    Cell[loc].Elem.M->PdSrms[1] = dy;
+    Cell[loc].Elem.M->PdSrnd[1] = 1e0;
+    Cell[loc].Elem.M->PdTrms = dr;
+    Cell[loc].Elem.M->PdTrnd = 1e0;
+    Mpole_SetdS(Fnum, Knum);
+    Mpole_SetdT(Fnum, Knum);
+}
+
+void ini_aper(const double Dxmin, const double Dxmax, const double Dymin,
+        const double Dymax) {
+    int k;
+
+    for (k = 0; k <= globval.Cell_nLoc; k++) {
+        Cell[k].maxampl[X_][0] = Dxmin;
+        Cell[k].maxampl[X_][1] = Dxmax;
+        Cell[k].maxampl[Y_][0] = Dymin;
+        Cell[k].maxampl[Y_][1] = Dymax;
+    }
 }
 
-
-void ini_aper(const double Dxmin, const double Dxmax, 
-              const double Dymin, const double Dymax) 
-{ 
-  int  k; 
- 
-  for (k = 0; k <= globval.Cell_nLoc; k++) { 
-    Cell[k].maxampl[X_][0] = Dxmin; Cell[k].maxampl[X_][1] = Dxmax; 
-    Cell[k].maxampl[Y_][0] = Dymin; Cell[k].maxampl[Y_][1] = Dymax; 
-  } 
-} 
- 
 void set_aper(const int Fnum, const double Dxmin, const double Dxmax,
-	      const double Dymin, const double Dymax)
-{
-  int       i;
-  long int  loc;
-
-  for (i = 1; i <= GetnKid(Fnum); i++) {
-    loc = Elem_GetPos(Fnum, i);
-    Cell[loc].maxampl[X_][0] = Dxmin; Cell[loc].maxampl[X_][1] = Dxmax;
-    Cell[loc].maxampl[Y_][0] = Dymin; Cell[loc].maxampl[Y_][1] = Dymax;
-  }
+        const double Dymin, const double Dymax) {
+    int i;
+    long int loc;
+
+    for (i = 1; i <= GetnKid(Fnum); i++) {
+        loc = Elem_GetPos(Fnum, i);
+        Cell[loc].maxampl[X_][0] = Dxmin;
+        Cell[loc].maxampl[X_][1] = Dxmax;
+        Cell[loc].maxampl[Y_][0] = Dymin;
+        Cell[loc].maxampl[Y_][1] = Dymax;
+    }
 }
 
+void LoadApertures(const char *ChamberFileName) {
+    char line[128], FamName[32];
+    long Fnum;
+    double Xmin, Xmax, Ymin, Ymax;
+    FILE *ChamberFile;
 
-void LoadApertures(const char *ChamberFileName)
-{
-  char    line[128], FamName[32];
-  long    Fnum;
-  double  Xmin, Xmax, Ymin, Ymax;
-  FILE    *ChamberFile;
-
-  ChamberFile = file_read(ChamberFileName);
+    ChamberFile = file_read(ChamberFileName);
 
-  do
-    fgets(line, 128, ChamberFile);
-  while (strstr(line, "#") != NULL);
+    do
+        fgets(line, 128, ChamberFile);
+    while (strstr(line, "#") != NULL);
 
-  do {
-    sscanf(line,"%s %lf %lf %lf %lf", FamName,&Xmin, &Xmax, &Ymin,&Ymax);
-      Fnum = ElemIndex(FamName);
-      if (Fnum > 0) set_aper(Fnum, Xmin, Xmax, Ymin, Ymax);
-  } while (fgets(line, 128, ChamberFile ) != NULL);
+    do {
+        sscanf(line, "%s %lf %lf %lf %lf", FamName, &Xmin, &Xmax, &Ymin, &Ymax);
+        Fnum = ElemIndex(FamName);
+        if (Fnum > 0)
+            set_aper(Fnum, Xmin, Xmax, Ymin, Ymax);
+    } while (fgets(line, 128, ChamberFile) != NULL);
 
-  fclose(ChamberFile);
+    fclose(ChamberFile);
 }
 
+// Load tolerances from the file
+void LoadTolerances(const char *TolFileName) {
+    char line[128], FamName[32];
+    int Fnum;
+    double dx, dy, dr;
+    FILE *tolfile;
+
+    tolfile = file_read(TolFileName);
+
+    do
+        fgets(line, 128, tolfile);
+    while (strstr(line, "#") != NULL);
+
+    do {
+        if (strstr(line, "#") == NULL) {
+            sscanf(line, "%s %lf %lf %lf", FamName, &dx, &dy, &dr);
+            Fnum = ElemIndex(FamName);
+            if (Fnum > 0) {
+                SetTol(Fnum, dx, dy, dr);
+            } else {
+                printf("LoadTolerances: undefined element %s\n", FamName);
+                exit_(1);
+            }
+        }
+    } while (fgets(line, 128, tolfile) != NULL);
+
+    fclose(tolfile);
+}
 
 // Load tolerances from the file
-void LoadTolerances(const char *TolFileName) 
-{
-  char    line[128], FamName[32];
-  int     Fnum;
-  double  dx, dy, dr;
-  FILE    *tolfile;
+void ScaleTolerances(const char *TolFileName, const double scl) {
+    char line[128], FamName[32];
+    int Fnum;
+    double dx, dy, dr;
+    FILE *tolfile;
+
+    tolfile = file_read(TolFileName);
+
+    do
+        fgets(line, 128, tolfile);
+    while (strstr(line, "#") != NULL);
+
+    do {
+        if (strstr(line, "#") == NULL) {
+            sscanf(line, "%s %lf %lf %lf", FamName, &dx, &dy, &dr);
+            Fnum = ElemIndex(FamName);
+            if (Fnum > 0) {
+                Scale_Tol(Fnum, scl * dx, scl * dy, scl * dr);
+            } else {
+                printf("ScaleTolerances: undefined element %s\n", FamName);
+                exit_(1);
+            }
+        }
+    } while (fgets(line, 128, tolfile) != NULL);
+    fclose(tolfile);
+}
+
+void SetKpar(int Fnum, int Knum, int Order, double k) {
+
+    Cell[Elem_GetPos(Fnum, Knum)].Elem.M->PBpar[Order + HOMmax] = k;
+    Mpole_SetPB(Fnum, Knum, Order);
+}
 
-  tolfile = file_read(TolFileName);
+void SetL(int Fnum, int Knum, double L) {
 
-  do
-    fgets(line, 128, tolfile);
-  while (strstr(line, "#") != NULL);
+    Cell[Elem_GetPos(Fnum, Knum)].Elem.PL = L;
+}
 
-  do {
-    if (strstr(line, "#") == NULL) {
-      sscanf(line,"%s %lf %lf %lf", FamName, &dx, &dy, &dr);
-      Fnum = ElemIndex(FamName);
-      if (Fnum > 0) {
-	SetTol(Fnum, dx, dy, dr);
-      } else {
-	printf("LoadTolerances: undefined element %s\n", FamName);
-	exit_(1);
-      }
-    }
-  } while (fgets(line, 128, tolfile) != NULL);
+void SetL(int Fnum, double L) {
+    int i;
 
-  fclose(tolfile);
+    for (i = 1; i <= GetnKid(Fnum); i++)
+        Cell[Elem_GetPos(Fnum, i)].Elem.PL = L;
 }
 
+void SetdKpar(int Fnum, int Knum, int Order, double dk) {
 
-// Load tolerances from the file
-void ScaleTolerances(const char *TolFileName, const double scl) 
-{
-  char    line[128], FamName[32];
-  int     Fnum;
-  double  dx, dy, dr;
-  FILE    *tolfile;
-
-  tolfile = file_read(TolFileName);
-
-  do
-    fgets(line, 128, tolfile);
-  while (strstr(line, "#") != NULL);
-  
-  do {
-    if (strstr(line, "#") == NULL) {
-      sscanf(line,"%s %lf %lf %lf", FamName, &dx, &dy, &dr);
-      Fnum = ElemIndex(FamName);
-      if (Fnum > 0) {
-	Scale_Tol(Fnum, scl*dx, scl*dy, scl*dr);
-      } else {
-	printf("ScaleTolerances: undefined element %s\n", FamName);
-	exit_(1);
-      }
-    }
-  } while (fgets(line, 128, tolfile) != NULL);
-  fclose(tolfile);
-}
-
-
-void SetKpar(int Fnum, int Knum, int Order, double k)
-{
-
-  Cell[Elem_GetPos(Fnum, Knum)].Elem.M->PBpar[Order+HOMmax] = k;
-  Mpole_SetPB(Fnum, Knum, Order);
+    Cell[Elem_GetPos(Fnum, Knum)].Elem.M->PBpar[Order + HOMmax] += dk;
+    Mpole_SetPB(Fnum, Knum, Order);
 }
 
+void SetKLpar(int Fnum, int Knum, int Order, double kL) {
+    long int loc;
 
-void SetL(int Fnum, int Knum, double L)
-{
+    if (abs(Order) > HOMmax) {
+        printf("SetKLPar: Error!....Multipole Order %d  > HOMmax %d\n", Order,
+                HOMmax);
+        exit_(1);
+    }
 
-  Cell[Elem_GetPos(Fnum, Knum)].Elem.PL = L;
+    loc = Elem_GetPos(Fnum, Knum);
+    if (Cell[loc].Elem.PL != 0e0)
+        Cell[loc].Elem.M->PBpar[Order + HOMmax] = kL / Cell[loc].Elem.PL;
+    else
+        Cell[loc].Elem.M->PBpar[Order + HOMmax] = kL;
+    Mpole_SetPB(Fnum, Knum, Order);
 }
 
+void SetdKLpar(int Fnum, int Knum, int Order, double dkL) {
+    long int loc;
 
-void SetL(int Fnum, double L)
-{
-  int  i;
-
-  for (i = 1; i <= GetnKid(Fnum); i++)
-    Cell[Elem_GetPos(Fnum, i)].Elem.PL = L;
+    loc = Elem_GetPos(Fnum, Knum);
+    if (Cell[loc].Elem.PL != 0e0)
+        Cell[loc].Elem.M->PBpar[Order + HOMmax] += dkL / Cell[loc].Elem.PL;
+    else
+        Cell[loc].Elem.M->PBpar[Order + HOMmax] += dkL;
+    Mpole_SetPB(Fnum, Knum, Order);
 }
 
+void SetdKrpar(int Fnum, int Knum, int Order, double dkrel) {
+    long int loc;
 
-void SetdKpar(int Fnum, int Knum, int Order, double dk)
-{
-
-  Cell[Elem_GetPos(Fnum, Knum)].Elem.M->PBpar[Order+HOMmax] += dk;
-  Mpole_SetPB(Fnum, Knum, Order);
+    loc = Elem_GetPos(Fnum, Knum);
+    if (Order == Dip && Cell[loc].Elem.M->Pthick == thick)
+        Cell[loc].Elem.M->PBpar[Dip + HOMmax] += dkrel
+                * Cell[loc].Elem.M->Pirho;
+    else
+        Cell[loc].Elem.M->PBpar[Order + HOMmax] += dkrel
+                * Cell[loc].Elem.M->PBpar[Order + HOMmax];
+    Mpole_SetPB(Fnum, Knum, Order);
 }
 
+void Setbn(int Fnum, int order, double bn) {
+    int i;
 
-void SetKLpar(int Fnum, int Knum, int Order, double kL)
-{
-  long int  loc;
-
-  if (abs(Order) > HOMmax){
-  printf("SetKLPar: Error!....Multipole Order %d  > HOMmax %d\n",Order,HOMmax);
-  exit_(1);
-  }
-  
-  loc = Elem_GetPos(Fnum, Knum);
-  if (Cell[loc].Elem.PL != 0e0)
-    Cell[loc].Elem.M->PBpar[Order+HOMmax] = kL/Cell[loc].Elem.PL;
-  else
-    Cell[loc].Elem.M->PBpar[Order+HOMmax] = kL;
-  Mpole_SetPB(Fnum, Knum, Order);
+    for (i = 1; i <= GetnKid(Fnum); i++)
+        SetKpar(Fnum, i, order, bn);
 }
 
+void SetbnL(int Fnum, int order, double bnL) {
+    int i;
 
-void SetdKLpar(int Fnum, int Knum, int Order, double dkL)
-{
-  long int  loc;
-
-  loc = Elem_GetPos(Fnum, Knum);
-  if (Cell[loc].Elem.PL != 0e0)
-    Cell[loc].Elem.M->PBpar[Order + HOMmax] += dkL/Cell[loc].Elem.PL;
-  else
-    Cell[loc].Elem.M->PBpar[Order + HOMmax] += dkL;
-  Mpole_SetPB(Fnum, Knum, Order);
+    for (i = 1; i <= GetnKid(Fnum); i++)
+        SetKLpar(Fnum, i, order, bnL);
 }
 
+void Setdbn(int Fnum, int order, double dbn) {
+    int i;
 
-void SetdKrpar(int Fnum, int Knum, int Order, double dkrel)
-{
-  long int  loc;
-
-  loc = Elem_GetPos(Fnum, Knum);
-  if (Order == Dip && Cell[loc].Elem.M->Pthick == thick)
-    Cell[loc].Elem.M->PBpar[Dip+HOMmax] += dkrel*Cell[loc].Elem.M->Pirho;
-  else
-    Cell[loc].Elem.M->PBpar[Order+HOMmax]
-      += dkrel*Cell[loc].Elem.M->PBpar[Order+HOMmax];
-  Mpole_SetPB(Fnum, Knum, Order);
+    for (i = 1; i <= GetnKid(Fnum); i++)
+        SetdKpar(Fnum, i, order, dbn);
 }
 
+void SetdbnL(int Fnum, int order, double dbnL) {
+    int i;
 
-void Setbn(int Fnum, int order, double bn)
-{
-  int i;
-
-  for (i = 1; i <=  GetnKid(Fnum); i++)
-    SetKpar(Fnum, i, order, bn);
+    for (i = 1; i <= GetnKid(Fnum); i++) {
+        SetdKLpar(Fnum, i, order, dbnL);
+    }
 }
 
+void Setbnr(int Fnum, long order, double bnr) {
+    int i;
 
-void SetbnL(int Fnum, int order, double bnL)
-{
-  int i;
-
-  for (i = 1; i <= GetnKid(Fnum); i++)
-    SetKLpar(Fnum, i, order, bnL);
+    for (i = 1; i <= GetnKid(Fnum); i++)
+        SetdKrpar(Fnum, i, order, bnr);
 }
 
+void SetbnL_sys(int Fnum, int Order, double bnL_sys) {
+    int Knum;
+    long int loc;
 
-void Setdbn(int Fnum, int order, double dbn)
-{
-  int i;
+    for (Knum = 1; Knum <= GetnKid(Fnum); Knum++) {
+        loc = Elem_GetPos(Fnum, Knum);
+        if (Cell[loc].Elem.PL != 0.0)
+            Cell[loc].Elem.M->PBsys[Order + HOMmax] = bnL_sys
+                    / Cell[loc].Elem.PL;
+        else
+            Cell[loc].Elem.M->PBsys[Order + HOMmax] = bnL_sys;
+        Mpole_SetPB(Fnum, Knum, Order);
+    }
+}
+
+void set_dbn_rel(const int type, const int n, const double dbn_rel) {
+    long int j;
+    double dbn;
 
-  for (i = 1; i <= GetnKid(Fnum); i++)
-    SetdKpar(Fnum, i, order, dbn);
+    printf("\n");
+    printf("Setting Db_%d/b_%d = %6.1e for:\n", n, type, dbn_rel);
+    printf("\n");
+    for (j = 0; j <= globval.Cell_nLoc; j++)
+        if ((Cell[j].Elem.Pkind == Mpole) && (Cell[j].Elem.M->n_design == type)) {
+            printf("%s\n", Cell[j].Elem.PName);
+            dbn = dbn_rel * Cell[j].Elem.M->PBpar[type + HOMmax];
+            Cell[j].Elem.M->PBrms[n + HOMmax] = dbn;
+            Cell[j].Elem.M->PBrnd[n + HOMmax] = normranf();
+            Mpole_SetPB(Cell[j].Fnum, Cell[j].Knum, n);
+        }
 }
 
+/********************************************************************
+ double GetKpar(int Fnum, int Knum, int Order)
 
-void SetdbnL(int Fnum, int order, double dbnL)
-{
-  int i;
+ Purpose:
+ Return the n-th order design field strength of the element
 
-  for (i = 1; i <= GetnKid(Fnum); i++) {
-    SetdKLpar(Fnum, i, order, dbnL);
-  }
-}
+ Input:
+ Fnum     family index
+ Knum     kid index
+ Order     design field strength
 
+ Ouput:
+ None
 
-void Setbnr(int Fnum, long order, double bnr)
-{
-  int  i;
+ Return:
+ n-th order design field strength
 
-  for (i = 1; i <= GetnKid(Fnum); i++)
-    SetdKrpar(Fnum, i, order, bnr);
+ *********************************************************************/
+double GetKpar(int Fnum, int Knum, int Order) {
+    return (Cell[Elem_GetPos(Fnum, Knum)].Elem.M->PBpar[Order + HOMmax]);
 }
 
+/********************************************************************
+ double GetL(int Fnum, int Knum)
 
-void SetbnL_sys(int Fnum, int Order, double bnL_sys)
-{
-  int       Knum;
-  long int  loc;
+ Purpose:
+ Return the length of the element with "Fnum" and "Knum"
 
-  for (Knum = 1; Knum <= GetnKid(Fnum); Knum++) {
-    loc = Elem_GetPos(Fnum, Knum);
-    if (Cell[loc].Elem.PL != 0.0)
-      Cell[loc].Elem.M->PBsys[Order+HOMmax] = bnL_sys/Cell[loc].Elem.PL;
-    else
-      Cell[loc].Elem.M->PBsys[Order+HOMmax] = bnL_sys;
-    Mpole_SetPB(Fnum, Knum, Order);
-  }
-}
+ Input:
+ Fnum     family index
+ Knum     kid index
 
 
-void set_dbn_rel(const int type, const int n, const double dbn_rel)
-{
-  long int  j;
-  double    dbn;
+ Ouput:
+ None
 
-  printf("\n");
-  printf("Setting Db_%d/b_%d = %6.1e for:\n", n, type, dbn_rel);
-  printf("\n");
-  for (j = 0; j <= globval.Cell_nLoc; j++)
-    if ((Cell[j].Elem.Pkind == Mpole) && (Cell[j].Elem.M->n_design == type)) {
-      printf("%s\n", Cell[j].Elem.PName);
-      dbn = dbn_rel*Cell[j].Elem.M->PBpar[type+HOMmax];
-      Cell[j].Elem.M->PBrms[n+HOMmax] = dbn;
-      Cell[j].Elem.M->PBrnd[n+HOMmax] = normranf();
-      Mpole_SetPB(Cell[j].Fnum, Cell[j].Knum, n);
-    }
-}
+ Return:
 
-/********************************************************************
-double GetKpar(int Fnum, int Knum, int Order)
-
-  Purpose:
-      Return the n-th order design field strength of the element
-       	
-   Input:
-       Fnum     family index
-       Knum     kid index
-      Order     design field strength
-     
-   Ouput:
-      None
-      
-  Return:
-      n-th order design field strength
-   
-*********************************************************************/
-double GetKpar(int Fnum, int Knum, int Order)
-{
-  return (Cell[Elem_GetPos(Fnum, Knum)].Elem.M->PBpar[Order+HOMmax]);
-}
 
-/********************************************************************
-double GetL(int Fnum, int Knum)
-
-  Purpose:
-      Return the length of the element with "Fnum" and "Knum"
-	
-   Input:
-       Fnum     family index
-       Knum     kid index
-   
-     
-   Ouput:
-      None
-      
-  Return:
-   
-   
-*********************************************************************/
-double GetL(int Fnum, int Knum)
-{
-  return (Cell[Elem_GetPos(Fnum, Knum)].Elem.PL);
+ *********************************************************************/
+double GetL(int Fnum, int Knum) {
+    return (Cell[Elem_GetPos(Fnum, Knum)].Elem.PL);
 }
 
 /********************************************************************
-double GetKLpar(int Fnum, int Knum, int Order)
-
-  Purpose:
-      Return the n-th order design integrated field strength of the element       
-	
-   Input:
-       Fnum     family index
-       Knum     kid index
-      Order     design field strength
-     
-   Ouput:
-      None
-      
-  Return:
-      n-th order design integrated field strength
-   
-*********************************************************************/
-
-double GetKLpar(int Fnum, int Knum, int Order)
-{
-  long int  loc = 0L;
+ double GetKLpar(int Fnum, int Knum, int Order)
 
-  loc = Elem_GetPos(Fnum, Knum);
-  if (Cell[loc].Elem.PL != 0e0)
-    return (Cell[loc].Elem.M->PBpar[Order+HOMmax]*Cell[loc].Elem.PL);
-  else
-    return (Cell[loc].Elem.M->PBpar[Order+HOMmax]);
-}
+ Purpose:
+ Return the n-th order design integrated field strength of the element
 
+ Input:
+ Fnum     family index
+ Knum     kid index
+ Order     design field strength
 
-void SetdKLrms(int Fnum, int Order, double dkLrms)
-{
-  long int  Knum, loc;
+ Ouput:
+ None
 
-  for (Knum = 1; Knum <= GetnKid(Fnum); Knum++) {
-    loc = Elem_GetPos(Fnum, Knum);
-    if (Cell[loc].Elem.PL != 0e0)
-      Cell[loc].Elem.M->PBrms[Order+HOMmax] = dkLrms/Cell[loc].Elem.PL;
-    else
-      Cell[loc].Elem.M->PBrms[Order+HOMmax] = dkLrms;
-    Cell[loc].Elem.M->PBrnd[Order+HOMmax] = normranf();
-    Mpole_SetPB(Fnum, Knum, Order);
-  }
-}
+ Return:
+ n-th order design integrated field strength
 
+ *********************************************************************/
 
-void Setdkrrms(int Fnum, int Order, double dkrrms)
-{
-  long int  Knum, loc;
+double GetKLpar(int Fnum, int Knum, int Order) {
+    long int loc = 0L;
 
-  for (Knum = 1; Knum <= GetnKid(Fnum); Knum++) {
     loc = Elem_GetPos(Fnum, Knum);
-    if (Order == Dip && Cell[loc].Elem.M->Pthick == thick)
-      Cell[loc].Elem.M->PBrms[Dip+HOMmax] = dkrrms*Cell[loc].Elem.M->Pirho;
+    if (Cell[loc].Elem.PL != 0e0)
+        return (Cell[loc].Elem.M->PBpar[Order + HOMmax] * Cell[loc].Elem.PL);
     else
-      Cell[loc].Elem.M->PBrms[Order+HOMmax]
-	= dkrrms*Cell[loc].Elem.M->PBpar[Order+HOMmax];
-    Cell[loc].Elem.M->PBrnd[Order+HOMmax] = normranf();
-    Mpole_SetPB(Fnum, Knum, Order);
-  }
+        return (Cell[loc].Elem.M->PBpar[Order + HOMmax]);
 }
 
+void SetdKLrms(int Fnum, int Order, double dkLrms) {
+    long int Knum, loc;
 
-void SetKL(int Fnum, int Order)
-{
-  long int  Knum;
-
-  for (Knum = 1; Knum <= GetnKid(Fnum); Knum++)
-    Mpole_SetPB(Fnum, Knum, Order);
+    for (Knum = 1; Knum <= GetnKid(Fnum); Knum++) {
+        loc = Elem_GetPos(Fnum, Knum);
+        if (Cell[loc].Elem.PL != 0e0)
+            Cell[loc].Elem.M->PBrms[Order + HOMmax] = dkLrms
+                    / Cell[loc].Elem.PL;
+        else
+            Cell[loc].Elem.M->PBrms[Order + HOMmax] = dkLrms;
+        Cell[loc].Elem.M->PBrnd[Order + HOMmax] = normranf();
+        Mpole_SetPB(Fnum, Knum, Order);
+    }
 }
 
+void Setdkrrms(int Fnum, int Order, double dkrrms) {
+    long int Knum, loc;
 
-void set_dx(const int type, const double sigma_x, const double sigma_y)
-{
-  long int  j;
-
-  printf("\n");
-  printf("Setting sigma_x,y = (%6.1e, %6.1e) for b_%d:\n",
-	 sigma_x, sigma_y, type);
-  printf("\n");
-  for (j = 0; j <= globval.Cell_nLoc; j++)
-    if ((Cell[j].Elem.Pkind == Mpole) && (Cell[j].Elem.M->n_design == type)) {
-      printf("%s\n", Cell[j].Elem.PName);
-      Cell[j].Elem.M->PdSrms[X_] = sigma_x;
-      Cell[j].Elem.M->PdSrms[Y_] = sigma_y;
-      Cell[j].Elem.M->PdSrnd[X_] = normranf();
-      Cell[j].Elem.M->PdSrnd[Y_] = normranf();
-      Mpole_SetdS(Cell[j].Fnum, Cell[j].Knum);
+    for (Knum = 1; Knum <= GetnKid(Fnum); Knum++) {
+        loc = Elem_GetPos(Fnum, Knum);
+        if (Order == Dip && Cell[loc].Elem.M->Pthick == thick)
+            Cell[loc].Elem.M->PBrms[Dip + HOMmax] = dkrrms
+                    * Cell[loc].Elem.M->Pirho;
+        else
+            Cell[loc].Elem.M->PBrms[Order + HOMmax] = dkrrms
+                    * Cell[loc].Elem.M->PBpar[Order + HOMmax];
+        Cell[loc].Elem.M->PBrnd[Order + HOMmax] = normranf();
+        Mpole_SetPB(Fnum, Knum, Order);
     }
 }
 
+void SetKL(int Fnum, int Order) {
+    long int Knum;
 
-void SetBpmdS(int Fnum, double dxrms, double dyrms)
-{
-  long int  Knum, loc;
-
-  for (Knum = 1; Knum <= GetnKid(Fnum); Knum++) {
-    loc = Elem_GetPos(Fnum, Knum);
-    Cell[loc].dS[X_] = normranf()*dxrms; Cell[loc].dS[Y_] = normranf()*dyrms;
-  }
+    for (Knum = 1; Knum <= GetnKid(Fnum); Knum++)
+        Mpole_SetPB(Fnum, Knum, Order);
 }
 
+void set_dx(const int type, const double sigma_x, const double sigma_y) {
+    long int j;
+
+    printf("\n");
+    printf("Setting sigma_x,y = (%6.1e, %6.1e) for b_%d:\n", sigma_x, sigma_y,
+            type);
+    printf("\n");
+    for (j = 0; j <= globval.Cell_nLoc; j++)
+        if ((Cell[j].Elem.Pkind == Mpole) && (Cell[j].Elem.M->n_design == type)) {
+            printf("%s\n", Cell[j].Elem.PName);
+            Cell[j].Elem.M->PdSrms[X_] = sigma_x;
+            Cell[j].Elem.M->PdSrms[Y_] = sigma_y;
+            Cell[j].Elem.M->PdSrnd[X_] = normranf();
+            Cell[j].Elem.M->PdSrnd[Y_] = normranf();
+            Mpole_SetdS(Cell[j].Fnum, Cell[j].Knum);
+        }
+}
+
+void SetBpmdS(int Fnum, double dxrms, double dyrms) {
+    long int Knum, loc;
+
+    for (Knum = 1; Knum <= GetnKid(Fnum); Knum++) {
+        loc = Elem_GetPos(Fnum, Knum);
+        Cell[loc].dS[X_] = normranf() * dxrms;
+        Cell[loc].dS[Y_] = normranf() * dyrms;
+    }
+}
 
 /****************************************/
 /* Routines for closed orbit correction */
 /****************************************/
 
-
 /****************************************************************************/
-void codstat(double *mean, double *sigma, double *xmax, long lastpos, bool all)
-{
-  long i, j, n;
-  Vector2 sum, sum2;
-  double TEMP;
-
-  n = 0;
-  for (j = 0; j <= 1; j++) {
-    sum[j] = 0.0; sum2[j] = 0.0; xmax[j] = 0.0;
-  }
-  for (i = 0; i <= lastpos; i++) {
-    if (all || Cell[i].Fnum == globval.bpm) {
-      n++;
-      for (j = 1; j <= 2; j++) {
-	sum[j - 1] += Cell[i].BeamPos[j * 2 - 2];
-	TEMP = Cell[i].BeamPos[j * 2 - 2];
-	sum2[j - 1] += TEMP * TEMP;
-	xmax[j - 1] = max(xmax[j - 1], fabs(Cell[i].BeamPos[j * 2 - 2]));
-      }
-    }
-  }
-  for (j = 0; j <= 1; j++) {
-    if (n != 0)
-      mean[j] = sum[j] / n;
-    else
-      mean[j] = 0.0;
-    if (n != 0 && n != 1) {
-      TEMP = sum[j];
-      sigma[j] = (n * sum2[j] - TEMP * TEMP) / (n * (n - 1.0));
-    } else
-      sigma[j] = 0.0;
-    if (sigma[j] >= 0.0)
-      sigma[j] = sqrt(sigma[j]);
-    else
-      sigma[j] = 0.0;
-  }
+void codstat(double *mean, double *sigma, double *xmax, long lastpos, bool all) {
+    long i, j, n;
+    Vector2 sum, sum2;
+    double TEMP;
+
+    n = 0;
+    for (j = 0; j <= 1; j++) {
+        sum[j] = 0.0;
+        sum2[j] = 0.0;
+        xmax[j] = 0.0;
+    }
+    for (i = 0; i <= lastpos; i++) {
+        if (all || Cell[i].Fnum == globval.bpm) {
+            n++;
+            for (j = 1; j <= 2; j++) {
+                sum[j - 1] += Cell[i].BeamPos[j * 2 - 2];
+                TEMP = Cell[i].BeamPos[j * 2 - 2];
+                sum2[j - 1] += TEMP * TEMP;
+                xmax[j - 1]
+                        = max(xmax[j - 1], fabs(Cell[i].BeamPos[j * 2 - 2]));
+            }
+        }
+    }
+    for (j = 0; j <= 1; j++) {
+        if (n != 0)
+            mean[j] = sum[j] / n;
+        else
+            mean[j] = 0.0;
+        if (n != 0 && n != 1) {
+            TEMP = sum[j];
+            sigma[j] = (n * sum2[j] - TEMP * TEMP) / (n * (n - 1.0));
+        } else
+            sigma[j] = 0.0;
+        if (sigma[j] >= 0.0)
+            sigma[j] = sqrt(sigma[j]);
+        else
+            sigma[j] = 0.0;
+    }
 }
 
 /****************************************************************************/
 /* void CodStatBpm(double *mean, double *sigma, double *xmax, long lastpos,
-                long bpmdis[mnp])
+ long bpmdis[mnp])
 
-   Purpose:
-       Get statistics for  closed orbit
+ Purpose:
+ Get statistics for  closed orbit
 
-   Input:
-       none
+ Input:
+ none
 
-   Output:
-       none
+ Output:
+ none
 
-   Return:
-       none
+ Return:
+ none
 
-   Global variables:
-       none
+ Global variables:
+ none
 
-   Specific functions:
-       none
+ Specific functions:
+ none
 
-   Comments:
-       none
+ Comments:
+ none
 
-****************************************************************************/
+ ****************************************************************************/
 void CodStatBpm(double *mean, double *sigma, double *xmax, long lastpos,
-                long bpmdis[mnp])
-{
-  long     i, j, m, n;
-  Vector2  sum, sum2;
-  double   TEMP;
-
-  m= n= 0;
-  for (j = 0; j <= 1; j++) {
-    sum[j] = 0.0; sum2[j] = 0.0; xmax[j] = 0.0;
-  }
-
-  for (i = 0; i <= lastpos; i++) {
-    if (Cell[i].Fnum == globval.bpm) {
-      if (! bpmdis[m]) {
-	for (j = 1; j <= 2; j++) {
-	  sum[j - 1] += Cell[i].BeamPos[j * 2 - 2];
-	  TEMP = Cell[i].BeamPos[j * 2 - 2];
-	  sum2[j - 1] += TEMP * TEMP;
-	  xmax[j - 1] = max(xmax[j - 1], fabs(Cell[i].BeamPos[j * 2 - 2]));
-	}
-        n++;
-      }
-      m++;
-    }
-  }
-  for (j = 0; j <= 1; j++) {
-    if (n != 0)
-      mean[j] = sum[j] / n;
-    else
-      mean[j] = 0.0;
-    if (n != 0 && n != 1) {
-      TEMP = sum[j];
-      sigma[j] = (n * sum2[j] - TEMP * TEMP) / (n * (n - 1.0));
-    } else
-      sigma[j] = 0.0;
-    if (sigma[j] >= 0.0)
-      sigma[j] = sqrt(sigma[j]);
-    else
-      sigma[j] = 0.0;
-  }
-}
-
+        long bpmdis[mnp]) {
+    long i, j, m, n;
+    Vector2 sum, sum2;
+    double TEMP;
+
+    m = n = 0;
+    for (j = 0; j <= 1; j++) {
+        sum[j] = 0.0;
+        sum2[j] = 0.0;
+        xmax[j] = 0.0;
+    }
 
+    for (i = 0; i <= lastpos; i++) {
+        if (Cell[i].Fnum == globval.bpm) {
+            if (!bpmdis[m]) {
+                for (j = 1; j <= 2; j++) {
+                    sum[j - 1] += Cell[i].BeamPos[j * 2 - 2];
+                    TEMP = Cell[i].BeamPos[j * 2 - 2];
+                    sum2[j - 1] += TEMP * TEMP;
+                    xmax[j - 1] = max(xmax[j - 1], fabs(Cell[i].BeamPos[j * 2
+                            - 2]));
+                }
+                n++;
+            }
+            m++;
+        }
+    }
+    for (j = 0; j <= 1; j++) {
+        if (n != 0)
+            mean[j] = sum[j] / n;
+        else
+            mean[j] = 0.0;
+        if (n != 0 && n != 1) {
+            TEMP = sum[j];
+            sigma[j] = (n * sum2[j] - TEMP * TEMP) / (n * (n - 1.0));
+        } else
+            sigma[j] = 0.0;
+        if (sigma[j] >= 0.0)
+            sigma[j] = sqrt(sigma[j]);
+        else
+            sigma[j] = 0.0;
+    }
+}
 
 /****************************************************************************/
 /* double digitize(double x, double maxkick, double maxsamp)
 
-   Purpose:
-       Map x onto the integer interval (-maxsamp ... maxsamp) where maxsamp
-       corresponds maxkick.
+ Purpose:
+ Map x onto the integer interval (-maxsamp ... maxsamp) where maxsamp
+ corresponds maxkick.
 
 
-   Input:
-       none
+ Input:
+ none
 
-   Output:
-       none
+ Output:
+ none
 
-   Return:
-       none
+ Return:
+ none
 
-   Global variables:
-       none
+ Global variables:
+ none
 
-   Specific functions:
-       none
+ Specific functions:
+ none
 
-   Comments:
-       none
+ Comments:
+ none
 
-****************************************************************************/
-double digitize(double x, double maxkick, double maxsamp)
-{
-  if (maxkick>0.)
-    if (maxsamp>1.)
-      return Sgn(x)*maxkick/maxsamp *min(floor(fabs(x)/maxkick*maxsamp),maxsamp-1.);
-    else {
-      return Sgn(x)*min(fabs(x),maxkick);
-    }
-  else
-    return x;
+ ****************************************************************************/
+double digitize(double x, double maxkick, double maxsamp) {
+    if (maxkick > 0.)
+        if (maxsamp > 1.)
+            return Sgn(x) * maxkick / maxsamp * min(floor(fabs(x) / maxkick
+                    * maxsamp), maxsamp - 1.);
+        else {
+            return Sgn(x) * min(fabs(x), maxkick);
+        }
+    else
+        return x;
 }
 
-
 /****************************************************************************/
 /* double digitize2(long plane, long inum, double x, double maxkick, double maxsamp)
 
-   Purpose:
+ Purpose:
 
 
-   Input:
-       none
+ Input:
+ none
 
-   Output:
-       none
+ Output:
+ none
 
-   Return:
-       none
+ Return:
+ none
 
-   Global variables:
-       none
+ Global variables:
+ none
 
-   Specific functions:
-       none
+ Specific functions:
+ none
 
-   Comments:
-       none
+ Comments:
+ none
 
-****************************************************************************/
+ ****************************************************************************/
 svdarray xmemo[2];
 
-double digitize2(long plane, long inum, double x, double maxkick, double maxsamp)
-{
-  double xint;
-
-  if (maxkick>0.)
-    if (maxsamp>1.)
-    {
-      xint=min(floor(fabs(x)/maxkick*maxsamp),maxsamp-1.);
-
-      if(fabs(xint-xmemo[inum][plane]) >=1.)
-      {
-        xmemo[inum][plane]=xint;
-      }
-      else
-      {
-        xmemo[inum][plane]+=0.1;
-        xint=min(xmemo[inum][plane],maxsamp-1.);
-      }
-      return Sgn(x)*maxkick/maxsamp*xint;
-    }
+double digitize2(long plane, long inum, double x, double maxkick,
+        double maxsamp) {
+    double xint;
+
+    if (maxkick > 0.)
+        if (maxsamp > 1.) {
+            xint = min(floor(fabs(x) / maxkick * maxsamp), maxsamp - 1.);
+
+            if (fabs(xint - xmemo[inum][plane]) >= 1.) {
+                xmemo[inum][plane] = xint;
+            } else {
+                xmemo[inum][plane] += 0.1;
+                xint = min(xmemo[inum][plane], maxsamp - 1.);
+            }
+            return Sgn(x) * maxkick / maxsamp * xint;
+        } else {
+            return Sgn(x) * min(fabs(x), maxkick);
+        }
     else
-    {
-      return Sgn(x)*min(fabs(x),maxkick);
-    }
-  else
-    return x;
+        return x;
 }
 
-
 // MATH ROUTINE a mettre dans mathlib.c
 
 /****************************************************************************/
 /*  void GetMean(n, x)
 
-   Purpose:
-       Get out the mean value of vector x
+ Purpose:
+ Get out the mean value of vector x
 
-   Input:
-       n vector size
-       x vector to get out the mean value
+ Input:
+ n vector size
+ x vector to get out the mean value
 
-   Output:
-       none
+ Output:
+ none
 
-   Return:
-       none
+ Return:
+ none
 
-   Global variables:
-       none
+ Global variables:
+ none
 
-   Specific functions:
-       none
+ Specific functions:
+ none
 
-   Comments:
-       to be moved in mathlib
+ Comments:
+ to be moved in mathlib
 
-****************************************************************************/
-void GetMean(long n, double *x)
-{
-  long i;
-  double mean = 0e0;
+ ****************************************************************************/
+void GetMean(long n, double *x) {
+    long i;
+    double mean = 0e0;
 
-  if ( n < 1 )
-  {
-    fprintf(stdout,"GetMean: error wrong vector size n=%ld\n",n);
-    exit_(1);
-  }
-  for (i = 0; i < n; i++)
-    mean += x[i];
-  mean /= n;
-  for (i = 0; i < n; i++)
-    x[i] = x[i] - mean;
+    if (n < 1) {
+        fprintf(stdout, "GetMean: error wrong vector size n=%ld\n", n);
+        exit_(1);
+    }
+    for (i = 0; i < n; i++)
+        mean += x[i];
+    mean /= n;
+    for (i = 0; i < n; i++)
+        x[i] = x[i] - mean;
 }
 
 /****************************************************************************/
 /* double Fract(double x)
 
-   Purpose:
-      Gets fractional part of x 
+ Purpose:
+ Gets fractional part of x
 
-   Input:
-       none
+ Input:
+ none
 
-   Output:
-       none
+ Output:
+ none
 
-   Return:
-       none
+ Return:
+ none
 
-   Global variables:
-       none
+ Global variables:
+ none
 
-   Specific functions:
-       none
+ Specific functions:
+ none
 
-   Comments:
-       none
+ Comments:
+ none
 
-****************************************************************************/
-double Fract(double x)
-{
-  return (x - (long int)x);
+ ****************************************************************************/
+double Fract(double x) {
+    return (x - (long int) x);
 }
 
 /****************************************************************************/
 /* double Sgn (double x)
 
-   Purpose:
-       Gets sign of x
+ Purpose:
+ Gets sign of x
 
-   Input:
-       none
+ Input:
+ none
 
-   Output:
-       0  if zero
-       1  if positive
-       -1 if negative
+ Output:
+ 0  if zero
+ 1  if positive
+ -1 if negative
 
-   Return:
-       none
+ Return:
+ none
 
-   Global variables:
-       none
+ Global variables:
+ none
 
-   Specific functions:
-       none
+ Specific functions:
+ none
 
-   Comments:
-       none
+ Comments:
+ none
 
-****************************************************************************/
-double Sgn (double x)
-{
-  return (x == 0.0 ? 0.0 : (x > 0.0 ? 1.0 : -1.0));
+ ****************************************************************************/
+double Sgn(double x) {
+    return (x == 0.0 ? 0.0 : (x > 0.0 ? 1.0 : -1.0));
 }
 
 /*************************************************************************/
 /*void ChamberOff(void)
  
-   Purpose:
-       Set global vacuum chamber limitation
+ Purpose:
+ Set global vacuum chamber limitation
 
-   Input:
-       none
+ Input:
+ none
 
-   Output:
-       none
+ Output:
+ none
 
-   Return:
-       none
+ Return:
+ none
 
-   Global variables:
-       none
+ Global variables:
+ none
 
-   Specific functions:
-       none
+ Specific functions:
+ none
 
-   Comments:
-       none
-  
+ Comments:
+ none
 
-*************************************************************************/
-void ChamberOff(void)
-{
-  int i;
 
-  for (i = 0; i <= globval.Cell_nLoc; i++) {
-    Cell[i].maxampl[X_][0] = -max_ampl; 
-    Cell[i].maxampl[X_][1] = max_ampl;
-    Cell[i].maxampl[Y_][0] = -max_ampl; 
-    Cell[i].maxampl[Y_][1] = max_ampl;
-  }
-  status.chambre = false;
+ *************************************************************************/
+void ChamberOff(void) {
+    int i;
+
+    for (i = 0; i <= globval.Cell_nLoc; i++) {
+        Cell[i].maxampl[X_][0] = -max_ampl;
+        Cell[i].maxampl[X_][1] = max_ampl;
+        Cell[i].maxampl[Y_][0] = -max_ampl;
+        Cell[i].maxampl[Y_][1] = max_ampl;
+    }
+    status.chambre = false;
 }
 
 /*************************************************************************/
 /*void PrintCh(void)
  
-   Purpose:
-       Output vacuum chamber limitation at each element to file "chambre.out"
+ Purpose:
+ Output vacuum chamber limitation at each element to file "chambre.out"
 
-   Input:
-       none
+ Input:
+ none
 
-   Output:
-       none
+ Output:
+ none
 
-   Return:
-       none
+ Return:
+ none
 
-   Global variables:
-       none
+ Global variables:
+ none
 
-   Specific functions:
-       none
+ Specific functions:
+ none
 
-   Comments:
-       none
-  
+ Comments:
+ none
 
-*************************************************************************/
- void PrintCh(void)
-{
-  long       i = 0;
-  struct tm  *newtime;
-  FILE       *f;
-
-  const  char  *fic    = "chambre.out";
-
-  newtime = GetTime();
-
-  f = file_write(fic);
-  fprintf(f, "# TRACY III synchrotron soleil -- %s -- %s \n", fic, asctime2(newtime));
-  fprintf(f, "#  i  name               s    -xch(mm) +xch(mm)  -zch(mm) +zch(mm)\n#\n");
-  
-  for (i = 1; i <= globval.Cell_nLoc; i++)
-	    fprintf(f, "%4ld  %15s %6.2f  %7.3f  %7.3f  %7.3f %7.3f\n", i, Cell[i].Elem.PName, Cell[i].S,
-	    Cell[i].maxampl[X_][0] * 1E3, 
-	    Cell[i].maxampl[X_][1] * 1E3,
-      Cell[i].maxampl[Y_][0] * 1E3, 
-	    Cell[i].maxampl[Y_][1] * 1E3);
-	    
-
-  fclose(f);
-}
-
-
-
-// /** function from soleilcommon.c **/
-// Version of nsrl-ii 
-// Move Read_Lattice() to soleilcommon.cc
-//void Read_Lattice(char *fic)
-//{
-//  bool     status;
-//  char     fic_maille[S_SIZE+4] = "", fic_erreur[S_SIZE+4] = "";
-//  int      i;
-//  double   dP = 0.0;
-//  Vector2  beta, alpha, eta, etap;
-//  Vector   codvect;
-
-//  const double RFacceptance = 0.060001; // soleil energy acceptance
-
-//  strcpy(fic_maille, fic); strcpy(fic_erreur, fic);
-
-//  /* generation automatique du nom du fichier maille et erreur */
-//  strcat(fic_maille, ".lat"); strcat(fic_erreur, ".lax");
-
-//  /* Initialisation de Tracy */
-
-//  t2init();
-
-  /* open the lattice Input file  */
-
-//  if ((fi = fopen(fic_maille, "r")) == NULL) {
-//    fprintf(stdout, "ReadLattice: Error while opening file %s \n", fic_maille);
-//    fprintf(stdout, "The lattice file has to end by .lat \n");
-//    exit_(1);
-//  }
-
-//  /* opens the lattice Output file */
-// //  if ((fo = fopen(fic_erreur, "w")) == NULL) {
-// //    fprintf(stdout, "ReadLattice: Error while opening file %s \n", fic_erreur);
-//    exit_(1);
-//  }
-
-  /* Reads lattice and set principle parameters
-   * Energy CODeps and energy offset
-   * print statistics
-   */
-//  status = Lattice_Read(&fi, &fo);
-
-//  if (status == false) {
-//    cout << "Lattice_Read function has returned false" << endl;
-//    cout << "See file " << fic_erreur << endl;
-//    exit_(1);
-//  }
-//  cout << "Lattice file: " << fic_maille << endl;
-
-  /* initializes cell structure: construction of the RING */
-  /* Creator of all the matrices for each element         */
-//  Cell_Init();
-
-//  if (globval.RingType == 1) { // for a ring
-//    /* define x/y physical aperture  */
-//    ChamberOff();
-
-//    /* Defines global variables for Tracy code */
-//    globval.H_exact     = false; // Small Ring Hamiltonian
-//    globval.quad_fringe = false; // quadrupole fringe fields on/off
-//    globval.EPU         = false; // Elliptically Polarizing Undulator
-//    globval.Cavity_on   = false; /* Cavity on/off */
-//    globval.radiation   = false; /* radiation on/off */
-//    globval.IBS         = false; /* diffusion on/off */
-//    globval.emittance   = false; /* emittance  on/off */
-//    globval.pathlength  = false; /* Path lengthening computation */
-//    globval.CODimax     = 40;    /* maximum number of iterations for COD
-//				    algo */
-//    globval.delta_RF = RFacceptance;/* energy acceptance for SOLEIL */
-
-//    Cell_SetdP(dP);  /* added for correcting BUG if non convergence:
-//                        compute on momentum linear matrices */
-//  } else {   
-    // for transfer lines
-    /* Initial settings : */
-//    beta[X_] = 8.1; 
-//    alpha[X_] = 0.0; 
-//    beta[Y_] = 8.1; 
-//    alpha[Y_] = 0.0;
-//    eta[X_] = 0.0; 
-//    etap[X_] = 0.0; 
-//    eta[Y_] = 0.0; 
-//    etap[Y_] = 0.0;
-
-//    for (i = 0; i < ss_dim; i++) {
-//      codvect[i] = 0.0; 
-//      globval.CODvect[i] = codvect[i];
-//    }
-//    dP = codvect[delta_];
-
-//    /* Defines global variables for Tracy code */
-//    globval.Cavity_on    = false; /* Cavity on/off */
-//    globval.radiation    = false; /* radiation on/off */
-//    globval.emittance    = false; /* emittance  on/off */
-//    globval.pathlength   = false; /* Path lengthening computation */
- //   globval.CODimax      = 10;    /* maximum number of iterations for COD
-//				     algo */
-//    globval.delta_RF = RFacceptance; /* 6% + epsilon energy acceptance
-//                                            for SOLEIL */
-//    globval.dPparticle = dP;
-
-//    ChamberOff();
-
-//    TransTwiss(alpha, beta, eta, etap, codvect);
-//  }
-//}
 
+ *************************************************************************/
+void PrintCh(void) {
+    long i = 0;
+    struct tm *newtime;
+    FILE *f;
+
+    const char *fic = "chambre.out";
+
+    newtime = GetTime();
+
+    f = file_write(fic);
+    fprintf(f, "# TRACY III Synchrotron SOLEIL -- %s -- %s \n", fic, asctime2(
+            newtime));
+    fprintf(f,
+            "#  i  name               s    -xch(mm) +xch(mm)  -ych(mm) +ych(mm)\n#\n");
+
+    for (i = 1; i <= globval.Cell_nLoc; i++)
+        fprintf(f, "%4ld  %15s %6.2f  %7.3f  %7.3f  %7.3f %7.3f\n", i,
+                Cell[i].Elem.PName, Cell[i].S, Cell[i].maxampl[X_][0] * 1E3,
+                Cell[i].maxampl[X_][1] * 1E3, Cell[i].maxampl[Y_][0] * 1E3,
+                Cell[i].maxampl[Y_][1] * 1E3);
+
+    fclose(f);
+}
 
 
 /****************************************************************************/
 /* void GetChromTrac(long Nb, long Nbtour, double emax,
-                     double *xix, double *xiz)
+ double *xix, double *xiz)
 
-   Purpose:
-       Computes chromaticities by tracking
+ Purpose:
+ Computes chromaticities by tracking
 
-   Input:
-       Nb      point number
-       Nbtour  turn number
-       emax    energy step
+ Input:
+ Nb      point number
+ Nbtour  turn number
+ emax    energy step
 
-   Output:
-       xix horizontal chromaticity
-       xiz vertical chromaticity
+ Output:
+ xix horizontal chromaticity
+ xiz vertical chromaticity
 
-   Return:
-       none
+ Return:
+ none
 
-   Global variables:
-       trace
+ Global variables:
+ trace
 
-   Specific functions:
-       Trac_Simple, Get_NAFF
+ Specific functions:
+ Trac_Simple, Get_NAFF
 
-   Comments:
-       27/04/03 chromaticities are now output arguments
+ Comments:
+ 27/04/03 chromaticities are now output arguments
+ 07/10/10 add test if unstable
 
-****************************************************************************/
+ ****************************************************************************/
 #define nterm  2
-void GetChromTrac(long Nb, long Nbtour, double emax, double *xix, double *xiz)
-{
-  bool    status = true;
-  int     nb_freq[2] = { 0, 0 };  /* frequency number to look for */
-  int     i = 0;
-  double  Tab[6][NTURN], fx[nterm], fz[nterm], nux1, nux2, nuz1, nuz2;
-
-  double  x = 1e-6, xp = 0.0, z = 1e-6, zp = 0.0;
-  double  x0 = 1e-6, xp0 = 0.0, z0 = 1e-6, zp0 = 0.0;
-  //double xixExtra = 0.0, xizExtra= 0.0, xixhalf= 0.0, xizhalf= 0.0;
-  //double nux3 = 0.0, nux4 = 0.0, nuz3 = 0.0, nuz4 = 0.0;
-
-  /* initializations */
-  for (i = 0; i < nterm; i++) {
-    fx[i] = 0.0; fz[i] = 0.0;
-  }
-  /* end init */
-
-  /* Tracking for delta = emax and computing tunes */
-  x = x0; xp = xp0; z = z0; zp = zp0;
-
-  Trac_Simple(x, xp, z, zp, emax, 0.0, Nbtour, Tab, &status);
-  Get_NAFF(nterm, Nbtour, Tab, fx, fz, nb_freq);
-
-  nux1 = (fabs (fx[0]) > 1e-8 ? fx[0] : fx[1]); nuz1 = fz[0];
-
-  if (trace)
-    fprintf(stdout,
-       "\nGetChromTrac: Entering routine for chroma using tracking\n");
-  if (trace)
-    fprintf(stdout, "emax= % 10.6e nux1=% 10.6e nuz1= % 10.6e\n",
-       emax, nux1, nuz1);
-
-  /* Tracking for delta = -emax and computing tunes */
-  x = x0; xp = xp0; z = z0; zp = zp0;
-
-  Trac_Simple(x, xp, z, zp, -emax, 0.0, Nbtour, Tab, &status);
-  Get_NAFF(nterm, Nbtour, Tab, fx, fz, nb_freq);
-
-  if (trace)
-    fprintf(stdout, "nturn=%6ld x=% 10.5g xp=% 10.5g z=% 10.5g zp=% 10.5g"
-	    " delta=% 10.5g ctau=% 10.5g \n",
-	    Nbtour,
-	    Tab[0][Nbtour-1], Tab[1][Nbtour-1],
-	    Tab[2][Nbtour-1], Tab[3][Nbtour-1],
-	    Tab[4][Nbtour-1], Tab[5][Nbtour-1]);
-
-  nux2 = (fabs(fx[0]) > 1e-8 ? fx[0] : fx[1]); nuz2 = fz[0];
-
-  if (trace)
-    fprintf(stdout, "emax= % 10.6e nux2= % 10.6e nuz2= % 10.6e\n",
-	    -emax, nux2, nuz2);
-
-  /* Computing chromaticities */
-  *xix = (nux2-nux1)*0.5/emax; *xiz = (nuz2-nuz1)*0.5/emax;
-
-  if (trace)
-    fprintf (stdout, "GetChromTrac: Exiting routine for chroma using tracking\n\n");
-
-  /*
-  // Compute for half a step to diagnose precision
-   Trac_Simple(x, xp, z, zp, emax*0.5, 0.0, Nbtour, Tab, &status);
-   Get_NAFF(nterm, Nbtour, Tab, fx, fz, nb_freq);
-   nux3 = (fabs (fx[0]) > 1e-8 ? fx[0] : fx[1]); nuz3 = fz[0];
-
-   Trac_Simple(x, xp, z, zp, -emax*0.5, 0.0, Nbtour, Tab, &status);
-   Get_NAFF(nterm, Nbtour, Tab, fx, fz, nb_freq);
-   nux4 = (fabs(fx[0]) > 1e-8 ? fx[0] : fx[1]); nuz4 = fz[0];
-
-   xixhalf = (nux4-nux3)/emax; xizhalf = (nuz4-nuz3)/emax;
-
-   // Richardson extrapolation
-   xixExtra = (4.0*xixhalf-*xix)/3.0;
-   xizExtra = (4.0*xizhalf-*xiz)/3.0;
-
-   fprintf(stdout, "chroma evaluated at +/- %6.2g, xix = % f xiz = % f\n",
-		   emax, *xix, *xiz);
-   fprintf(stdout, "chroma evaluated at +/- %6.2g, xix = % f xiz = % f\n",
-		   emax/2, xixhalf, xizhalf);
-   fprintf(stdout, "chroma evaluated from Richardson Extrapolation, xix = % f xiz = % f\n",
- 		   xixExtra, xizExtra);
-   */
+#define ZERO 1E-8
+
+void GetChromTrac(long Nb, long Nbtour, double emax, double *xix, double *xiy) {
+    bool status = true;
+    int nb_freq[2] = { 0, 0 }; /* frequency number to look for */
+    int i = 0;
+    double Tab[6][NTURN], fx[nterm], fy[nterm], nux1, nux2, nuy1, nuy2;
+
+    double x = 1e-6, xp = 0.0, y = 1e-6, yp = 0.0;
+    double x0 = 1e-6, xp0 = 0.0, y0 = 1e-6, yp0 = 0.0;
+    //double xixExtra = 0.0, xizExtra= 0.0, xixhalf= 0.0, xizhalf= 0.0;
+    //double nux3 = 0.0, nux4 = 0.0, nuz3 = 0.0, nuz4 = 0.0;
+
+    /* initializations */
+    for (i = 0; i < nterm; i++) {
+        fx[i] = 0.0;
+        fy[i] = 0.0;
+    }
+    /* end init */
+
+    /* Tracking for delta = emax and computing tunes */
+    x  = x0;
+    xp = xp0;
+    y  = y0;
+    yp = yp0;
+
+    Trac_Simple(x, xp, y, yp, emax, 0.0, Nbtour, Tab, &status);
+    if (status){
+    Get_NAFF(nterm, Nbtour, Tab, fx, fy, nb_freq);
+    nux1 = (fabs(fx[0]) > ZERO ? fx[0] : fx[1]);
+    nuy1 = fy[0];}
+    else{
+        nux1=999; nuy1=999;
+    }
+
+    if (trace)
+        fprintf(stdout,
+                "\nGetChromTrac: Entering routine for chroma using tracking\n");
+    if (trace)
+        fprintf(stdout, "emax= % 10.6e nux1=% 10.6e nuy1= % 10.6e\n", emax,
+                nux1, nuy1);
+
+    /* Tracking for delta = -emax and computing tunes */
+    x = x0;
+    xp = xp0;
+    y = y0;
+    yp = yp0;
+
+    Trac_Simple(x, xp, y, yp, -emax, 0.0, Nbtour, Tab, &status);
+    if (status){
+        Get_NAFF(nterm, Nbtour, Tab, fx, fy, nb_freq);
+    if (trace)
+        fprintf(stdout, "nturn=%6ld x=% 10.5g xp=% 10.5g z=% 10.5g zp=% 10.5g"
+            " delta=% 10.5g ctau=% 10.5g \n", Nbtour, Tab[0][Nbtour - 1],
+                Tab[1][Nbtour - 1], Tab[2][Nbtour - 1], Tab[3][Nbtour - 1],
+                Tab[4][Nbtour - 1], Tab[5][Nbtour - 1]);
+
+    nux2 = (fabs(fx[0]) > 1e-8 ? fx[0] : fx[1]);
+    nuy2 = fy[0];
+
+    if (trace)
+        fprintf(stdout, "emax= % 10.6e nux2= % 10.6e nuy2= % 10.6e\n", -emax,
+                nux2, nuy2);
+
+    /* Computing chromaticities */
+    *xix = (nux2 - nux1) * 0.5 / emax;
+    *xiy = (nuy2 - nuy1) * 0.5 / emax;
+
+    if (trace)
+        fprintf(stdout,
+                "GetChromTrac: Exiting routine for chroma using tracking\n\n");
+    }
+    else{ // unstable
+        *xix = -99999;
+        *xiy = -99999;
+    }
+
+    /*
+     // Compute for half a step to diagnose precision
+     Trac_Simple(x, xp, z, zp, emax*0.5, 0.0, Nbtour, Tab, &status);
+     Get_NAFF(nterm, Nbtour, Tab, fx, fz, nb_freq);
+     nux3 = (fabs (fx[0]) > 1e-8 ? fx[0] : fx[1]); nuz3 = fz[0];
+
+     Trac_Simple(x, xp, z, zp, -emax*0.5, 0.0, Nbtour, Tab, &status);
+     Get_NAFF(nterm, Nbtour, Tab, fx, fz, nb_freq);
+     nux4 = (fabs(fx[0]) > 1e-8 ? fx[0] : fx[1]); nuz4 = fz[0];
+
+     xixhalf = (nux4-nux3)/emax; xizhalf = (nuz4-nuz3)/emax;
+
+     // Richardson extrapolation
+     xixExtra = (4.0*xixhalf-*xix)/3.0;
+     xizExtra = (4.0*xizhalf-*xiz)/3.0;
+
+     fprintf(stdout, "chroma evaluated at +/- %6.2g, xix = % f xiz = % f\n",
+     emax, *xix, *xiz);
+     fprintf(stdout, "chroma evaluated at +/- %6.2g, xix = % f xiz = % f\n",
+     emax/2, xixhalf, xizhalf);
+     fprintf(stdout, "chroma evaluated from Richardson Extrapolation, xix = % f xiz = % f\n",
+     xixExtra, xizExtra);
+     */
 }
 #undef nterm
+#undef ZERO
 
 /****************************************************************************/
 /* void GetTuneTrac(long Nbtour, double emax, double *nux, double *nuz)
 
-   Purpose:
-       Computes chromaticities by tracking
+ Purpose:
+ Computes tunes by tracking
 
-   Input:
-       Nb      point number
-       Nbtour  turn number
-       emax    energy step
+ Input:
+ Nb      point number
+ Nbtour  turn number
+ emax    energy step
 
-   Output:
-       none
+ Output:
+ nux horizontal tune (0.0 if unstable)
+ nuz vertical tune (0.0 if unstable)
 
-   Return:
-       none
+ Return:
+ none
 
-   Global variables:
-       trace
+ Global variables:
+ trace
 
-   Specific functions:
-       Trac_Simple, Get_NAFF
+ Specific functions:
+ Trac_Simple, Get_NAFF
 
-   Comments:
-       none
+ Comments:
+   Add test on stability
 
-****************************************************************************/
+ ****************************************************************************/
 #define nterm  2
-void GetTuneTrac(long Nbtour, double emax, double *nux, double *nuz)
-{
-  double Tab[6][NTURN], fx[nterm], fz[nterm];
-  int nb_freq[2];
-  bool status;
-
-  double x = 1e-6, xp = 0.0, z = 1e-6, zp = 0.0;
-
-  Trac_Simple(x, xp, z, zp, emax, 0.0, Nbtour, Tab, &status);
-  Get_NAFF(nterm, Nbtour, Tab, fx, fz, nb_freq);
-
-  *nux = (fabs (fx[0]) > 1e-8 ? fx[0] : fx[1]);
-  *nuz = fz[0];
+#define ZERO 1E-8
+void GetTuneTrac(long Nbtour, double emax, double *nux, double *nuz) {
+    double Tab[6][NTURN], fx[nterm], fz[nterm];
+    int nb_freq[2];
+    bool status;
+
+    double x = 1e-6, xp = 0.0, z = 1e-6, zp = 0.0;
+
+    Trac_Simple(x, xp, z, zp, emax, 0.0, Nbtour, Tab, &status);
+    if (status){
+       Get_NAFF(nterm, Nbtour, Tab, fx, fz, nb_freq);
+        *nux = (fabs(fx[0]) > ZERO ? fx[0] : fx[1]);
+        *nuz = fz[0];}
+    else{ // particle unstable
+        *nux = 0.0;
+        *nuz = 0.0;}
 }
 #undef nterm
+#undef ZERO
 
 /****************************************************************************/
 /* void TransTwiss(double *alpha, double *beta, double *eta, double *etap, double *codvect)
 
-   Purpose: high level application
-          Calculate Twiss functions for a transport line
+ Purpose: high level application
+ Calculate Twiss functions for a transport line
 
-   Input:
-       alpha   alpha fonctions at the line entrance
-       beta    beta fonctions at the line entrance
-       eta     disperion fonctions at the line entrance
-       etap    dipersion derivatives fonctions at the line entrance
-       codvect closed orbit fonctions at the line entrance
+ Input:
+ alpha   alpha functions at the line entrance
+ beta    beta functions at the line entrance
+ eta     dispersion functions at the line entrance
+ etap    dispersion derivatives functions at the line entrance
+ codvect closed orbit functions at the line entrance
 
-   Output:
-       none
+ Output:
+ none
 
-   Return:
-       none
+ Return:
+ none
 
-   Global variables:
+ Global variables:
 
 
-   Specific functions:
-       TransTrace
+ Specific functions:
+ TransTrace
 
-   Comments:
-       redundant with ttwiss
+ Comments:
+ redundant with ttwiss
 
-****************************************************************************/
+ ****************************************************************************/
 void TransTwiss(Vector2 &alpha, Vector2 &beta, Vector2 &eta, Vector2 &etap,
-		Vector &codvect)
-{
-  TransTrace(0, globval.Cell_nLoc, alpha, beta, eta, etap, codvect);
+        Vector &codvect) {
+    TransTrace(0, globval.Cell_nLoc, alpha, beta, eta, etap, codvect);
 }
 
-
 /****************************************************************************/
 /* void ttwiss(double *alpha, double *beta, double *eta, double *etap, double dP)
 
-   Purpose:
-      Calculate Twiss functions for transport line
+ Purpose:
+ Calculate Twiss functions for transport line
 
-   Input:
-       none
+ Input:
+ none
 
-   Output:
-       none
+ Output:
+ none
 
-   Return:
-       none
+ Return:
+ none
 
-   Global variables:
-       none
+ Global variables:
+ none
 
-   Specific functions:
-       none
+ Specific functions:
+ none
 
-   Comments:
-       redundant with TransTwiss
+ Comments:
+ redundant with TransTwiss
 
-****************************************************************************/
-void ttwiss(const Vector2 &alpha, const Vector2 &beta,
-            const Vector2 &eta, const Vector2 &etap, const double dP)
-{
-  TraceABN(0, globval.Cell_nLoc, alpha, beta, eta, etap, dP);
+ ****************************************************************************/
+void ttwiss(const Vector2 &alpha, const Vector2 &beta, const Vector2 &eta,
+        const Vector2 &etap, const double dP) {
+    TraceABN(0, globval.Cell_nLoc, alpha, beta, eta, etap, dP);
 }
 
 /****************************************************************************/
 /* void findcodS(double dP)
 
-   Purpose: 
-       Search for the closed orbit using a numerical method
-       Algo: Newton_Raphson method
-             Quadratic convergence
-             May need a guess starting point
-             Simple precision algorithm
+ Purpose:
+ Search for the closed orbit using a numerical method
+ Algo: Newton_Raphson method
+ Quadratic convergence
+ May need a guess starting point
+ Simple precision algorithm
 
-   Input:
-       dP energy offset
+ Input:
+ dP energy offset
 
-   Output:
-       none
+ Output:
+ none
 
-   Return:
-       none
+ Return:
+ none
 
-   Global variables:
-       none
+ Global variables:
+ none
 
-   specific functions:
-       Newton_Raphson
+ specific functions:
+ Newton_Raphson
 
-   Comments:
-       Method introduced because of bad convergence of da for ID using RADIA maps
+ Comments:
+ Method introduced because of bad convergence of da for ID using RADIA maps
 
-****************************************************************************/
-void findcodS(double dP)
-{
-  double        *vcod;
-  Vector       x0;
-  const int    ntrial = 40;  // maximum number of trials for closed orbit
-  const double  tolx = 1e-8;  // numerical precision
-  int          k;
-  int          dim;    // 4D or 6D tracking
-  long         lastpos;
-
-  vcod = dvector(1, 6);
-      
-  // starting point
-  for (k = 1; k <= 6; k++)
-    vcod[k] = 0.0;  
-  
-  vcod[5] = dP;  // energy offset 
-    
-  if (globval.Cavity_on){
-      dim = 6;   /* 6D tracking*/
-    fprintf(stdout,"Error looking for cod in 6D\n");
-    exit_(1);
-  }
-    else{
-      dim = 4; /* 4D tracking */
-      vcod[1] = Cell[0].Eta[0]*dP; vcod[2] = Cell[0].Etap[0]*dP;
-      vcod[3] = Cell[0].Eta[1]*dP; vcod[4] = Cell[0].Etap[1]*dP;
-  }
-  
-  Newton_RaphsonS(ntrial, vcod, dim, tolx);
-
-  if (status.codflag == false)
-    fprintf(stdout, "Error No COD found\n");
-  if (trace) {
-    for (k = 1; k <= 6; k++)
-      x0[k-1] = vcod[k];
-    fprintf(stdout, "Before cod % .5e % .5e % .5e % .5e % .5e % .5e \n",
-	    x0[0], x0[1], x0[2], x0[3], x0[4], x0[5]);
-    Cell_Pass(0, globval.Cell_nLoc, x0, lastpos);
-    fprintf(stdout, "After  cod % .5e % .5e % .5e % .5e % .5e % .5e \n",
-	    x0[0], x0[1], x0[2], x0[3], x0[4], x0[5]);
-    Cell_Pass(0, globval.Cell_nLoc, x0, lastpos);
-  }
-  free_dvector(vcod,1,6);
-}
+ ****************************************************************************/
+void findcodS(double dP) {
+    double *vcod;
+    Vector x0;
+    const int ntrial = 40; // maximum number of trials for closed orbit
+    const double tolx = 1e-8; // numerical precision
+    int k;
+    int dim; // 4D or 6D tracking
+    long lastpos;
 
-/****************************************************************************/
-/* void findcod(double dP)
+    vcod = dvector(1, 6);
 
-   Purpose: 
-       Search for the closed orbit using a numerical method
-       Algo: Newton_Raphson method
-             Quadratic convergence
-             May need a guess starting point
-             Simple precision algorithm
-      4D
-      Starting point: linear closed orbit
+    // starting point
+    for (k = 1; k <= 6; k++)
+        vcod[k] = 0.0;
 
-      6D
-      Starting point: zero
-        if radiation on : x[5] is the synchroneous phase (equilibrium RF phase)
-                     off: x[5] is zero
+    vcod[5] = dP; // energy offset
 
-   Input:
-       dP energy offset
+    if (globval.Cavity_on) {
+        dim = 6; /* 6D tracking*/
+        fprintf(stdout, "Error looking for cod in 6D\n");
+        exit_(1);
+    } else {
+        dim = 4; /* 4D tracking */
+        vcod[1] = Cell[0].Eta[0] * dP;
+        vcod[2] = Cell[0].Etap[0] * dP;
+        vcod[3] = Cell[0].Eta[1] * dP;
+        vcod[4] = Cell[0].Etap[1] * dP;
+    }
 
-   Output:
-       none
+    Newton_RaphsonS(ntrial, vcod, dim, tolx);
+
+    if (status.codflag == false)
+        fprintf(stdout, "Error No COD found\n");
+    if (trace) {
+        for (k = 1; k <= 6; k++)
+            x0[k - 1] = vcod[k];
+        fprintf(stdout, "Before cod % .5e % .5e % .5e % .5e % .5e % .5e \n",
+                x0[0], x0[1], x0[2], x0[3], x0[4], x0[5]);
+        Cell_Pass(0, globval.Cell_nLoc, x0, lastpos);
+        fprintf(stdout, "After  cod % .5e % .5e % .5e % .5e % .5e % .5e \n",
+                x0[0], x0[1], x0[2], x0[3], x0[4], x0[5]);
+        Cell_Pass(0, globval.Cell_nLoc, x0, lastpos);
+    }
+    free_dvector(vcod, 1, 6);
+}
 
-   Return:
-       vcod:  6-D closed orbit 
+/****************************************************************************/
+/* void findcod(double dP)
+
+ Purpose:
+ Search for the closed orbit using a numerical method
+ Algo: Newton_Raphson method
+ Quadratic convergence
+ May need a guess starting point
+ Simple precision algorithm
+ 4D
+ Starting point: linear closed orbit
+
+ 6D
+ Starting point: zero
+ if radiation on : x[5] is the synchroneous phase (equilibrium RF phase)
+ off: x[5] is zero
+
+ Input:
+ dP energy offset
+
+ Output:
+ none
+
+ Return:
+ vcod:  6-D closed orbit
+
+ Global variables:
+ none
+
+ specific functions:
+ Newton_Raphson
+
+ Comments:
+ Method introduced because of bad convergence of da for ID
+ using RADIA maps
+
+ ****************************************************************************/
+void findcod(double dP) {
+    Vector vcod;
+    const int ntrial = 40; // maximum number of trials for closed orbit
+    const double tolx = 1e-10; // numerical precision
+    int k, dim = 0;
+    long lastpos;
+
+    // initializations
+    for (k = 0; k <= 5; k++)
+        vcod[k] = 0.0;
+
+    if (globval.Cavity_on) {
+        fprintf(stdout, "warning looking for cod in 6D\n");
+        dim = 6;
+    } else { // starting point linear closed orbit
+        dim = 4;
+        vcod[0] = Cell[0].Eta[0] * dP;
+        vcod[1] = Cell[0].Etap[0] * dP;
+        vcod[2] = Cell[0].Eta[1] * dP;
+        vcod[3] = Cell[0].Etap[1] * dP;
+        vcod[4] = dP; // energy offset
+    }
 
-   Global variables:
-       none
+    Newton_Raphson(dim, vcod, ntrial, tolx);
 
-   specific functions:
-       Newton_Raphson
+    if (status.codflag == false)
+        fprintf(stdout, "Error No COD found\n");
 
-   Comments:
-       Method introduced because of bad convergence of da for ID
-       using RADIA maps
+    CopyVec(6, vcod, globval.CODvect); // save closed orbit at the ring entrance
 
-****************************************************************************/
-void findcod(double dP)
-{
-  Vector        vcod;
-  const int     ntrial = 40;  // maximum number of trials for closed orbit
-  const double  tolx = 1e-10;  // numerical precision
-  int           k, dim = 0;
-  long          lastpos;
-
-  // initializations
-  for (k = 0; k <= 5; k++)
-    vcod[k] = 0.0;  
-    
-  if (globval.Cavity_on){
-    fprintf(stdout,"warning looking for cod in 6D\n");
-    dim = 6;
-  } else{ // starting point linear closed orbit
-    dim = 4;
-    vcod[0] = Cell[0].Eta[0]*dP; vcod[1] = Cell[0].Etap[0]*dP;
-    vcod[2] = Cell[0].Eta[1]*dP; vcod[3] = Cell[0].Etap[1]*dP;
-    vcod[4] = dP;  // energy offset 
-  }
-  
-  Newton_Raphson(dim, vcod, ntrial, tolx);
-
-  if (status.codflag == false)
-    fprintf(stdout, "Error No COD found\n");
-  
-  CopyVec(6, vcod, globval.CODvect); // save closed orbit at the ring entrance
-
-  if (trace)
-  {
-    fprintf(stdout,
-       "Before cod2 % .5e % .5e % .5e % .5e % .5e % .5e \n",
-       vcod[0], vcod[1], vcod[2], vcod[3], vcod[4], vcod[5]);
-    Cell_Pass(0, globval.Cell_nLoc, vcod, lastpos);
-    fprintf(stdout,
-       "After  cod2 % .5e % .5e % .5e % .5e % .5e % .5e \n",
-       vcod[0], vcod[1], vcod[2], vcod[3], vcod[4], vcod[5]);
-  }
+    if (trace) {
+        fprintf(stdout, "Before cod2 % .5e % .5e % .5e % .5e % .5e % .5e \n",
+                vcod[0], vcod[1], vcod[2], vcod[3], vcod[4], vcod[5]);
+        Cell_Pass(0, globval.Cell_nLoc, vcod, lastpos);
+        fprintf(stdout, "After  cod2 % .5e % .5e % .5e % .5e % .5e % .5e \n",
+                vcod[0], vcod[1], vcod[2], vcod[3], vcod[4], vcod[5]);
+    }
 }
 /****************************************************************************/
 /* void computeFandJS(double *x, int n, double **fjac, double *fvect)
 
-   Purpose:
-       Simple precision algo
-       Tracks x over one turn. And computes the Jacobian matrix of the 
-       transformation by numerical differentiation.
-       using forward difference formula : faster but less accurate
-       using symmetric difference formula
+ Purpose:
+ Simple precision algo
+ Tracks x over one turn. And computes the Jacobian matrix of the
+ transformation by numerical differentiation.
+ using forward difference formula : faster but less accurate
+ using symmetric difference formula
 
-   Input:
-       x vector for evaluation
-       n dimension 4 or 6
+ Input:
+ x vector for evaluation
+ n dimension 4 or 6
 
-   Output:
-      fvect transport of x over one turn
-      fjac  Associated jacobian matrix      
+ Output:
+ fvect transport of x over one turn
+ fjac  Associated jacobian matrix
 
-   Return:
-       none
+ Return:
+ none
 
-   Global variables:
-       none
+ Global variables:
+ none
 
-   specific functions:
-       none
+ specific functions:
+ none
 
-   Comments:
-       none
+ Comments:
+ none
 
-****************************************************************************/
+ ****************************************************************************/
 
-void computeFandJS(double *x, int n, double **fjac, double *fvect)
-{
-  int     i, k;
-  long    lastpos = 0L;
-  Vector  x0, fx, fx1, fx2;
-
-  const double deps = 1e-8;  //stepsize for numerical differentiation
-
-  for (i = 1; i <= 6; i++)
-    x0[i - 1] = x[i];
-  
-  Cell_Pass(0, globval.Cell_nLoc, x0, lastpos);
-
-  for (i = 1; i <= n; i++)
-  {
-    fvect[i] = x0[i - 1];
-    fx[i - 1] = x0[i - 1];
-  }
-
-  // compute Jacobian matrix by numerical differentiation
-  for (k = 0; k < n; k++)
-  {
-    for (i = 1; i <= 6; i++)
-      x0[i - 1] = x[i];
-    x0[k] += deps;  // differential step in coordinate k
+void computeFandJS(double *x, int n, double **fjac, double *fvect) {
+    int i, k;
+    long lastpos = 0L;
+    Vector x0, fx, fx1, fx2;
 
-    Cell_Pass(0, globval.Cell_nLoc, x0, lastpos);  // tracking along the ring
-    for (i = 1; i <= 6; i++)
-      fx1[i - 1] = x0[i - 1];
+    const double deps = 1e-8; //stepsize for numerical differentiation
 
     for (i = 1; i <= 6; i++)
-      x0[i - 1] = x[i];
-    x0[5] = 0.0;
-    x0[k] -= deps;  // differential step in coordinate k
+        x0[i - 1] = x[i];
 
-    Cell_Pass(0, globval.Cell_nLoc, x0, lastpos);  // tracking along the ring
-    for (i = 1; i <= 6; i++)
-      fx2[i - 1] = x0[i - 1];
+    Cell_Pass(0, globval.Cell_nLoc, x0, lastpos);
 
-    for (i = 1; i <= n; i++)  // symmetric difference formula
-      fjac[i][k + 1] = 0.5 * (fx1[i - 1] - fx2[i - 1]) / deps;
-    //~ for (i = 1; i <= n; i++) // forward difference formula
-    //~ fjac[i][k + 1] = (float) ((x0[i - 1] - fx[i - 1]) / deps);  
-  }
+    for (i = 1; i <= n; i++) {
+        fvect[i] = x0[i - 1];
+        fx[i - 1] = x0[i - 1];
+    }
+
+    // compute Jacobian matrix by numerical differentiation
+    for (k = 0; k < n; k++) {
+        for (i = 1; i <= 6; i++)
+            x0[i - 1] = x[i];
+        x0[k] += deps; // differential step in coordinate k
+
+        Cell_Pass(0, globval.Cell_nLoc, x0, lastpos); // tracking along the ring
+        for (i = 1; i <= 6; i++)
+            fx1[i - 1] = x0[i - 1];
+
+        for (i = 1; i <= 6; i++)
+            x0[i - 1] = x[i];
+        x0[5] = 0.0;
+        x0[k] -= deps; // differential step in coordinate k
+
+        Cell_Pass(0, globval.Cell_nLoc, x0, lastpos); // tracking along the ring
+        for (i = 1; i <= 6; i++)
+            fx2[i - 1] = x0[i - 1];
+
+        for (i = 1; i <= n; i++) // symmetric difference formula
+            fjac[i][k + 1] = 0.5 * (fx1[i - 1] - fx2[i - 1]) / deps;
+        //~ for (i = 1; i <= n; i++) // forward difference formula
+        //~ fjac[i][k + 1] = (float) ((x0[i - 1] - fx[i - 1]) / deps);
+    }
 }
 
 /****************************************************************************/
 /* void computeFand(int n, float *x, float **fjac, float *fvect)
 
-   Purpose:       
-       Tracks x over one turn. And computes the Jacobian matrix of the 
-       transformation by numerical differentiation.
-       using symmetric difference formula
-       double precision algorithm
+ Purpose:
+ Tracks x over one turn. And computes the Jacobian matrix of the
+ transformation by numerical differentiation.
+ using symmetric difference formula
+ double precision algorithm
 
-   Input:
-       x vector for evaluation
+ Input:
+ x vector for evaluation
 
-   Output:
-      fvect transport of x over one turn
-      fjac  Associated jacobian matrix      
+ Output:
+ fvect transport of x over one turn
+ fjac  Associated jacobian matrix
 
-   Return:
-       none
+ Return:
+ none
 
-   Global variables:
-       none
+ Global variables:
+ none
 
-   specific functions:
-       none
+ specific functions:
+ none
 
-   Comments:
-       none
+ Comments:
+ none
 
-****************************************************************************/
-void computeFandJ(int n, Vector &x, Matrix &fjac, Vector &fvect)
-{
-  int     i, k;
-  long    lastpos = 0;
-  Vector  x0, fx1, fx2;
+ ****************************************************************************/
+void computeFandJ(int n, Vector &x, Matrix &fjac, Vector &fvect) {
+    int i, k;
+    long lastpos = 0;
+    Vector x0, fx1, fx2;
+
+    const double deps = 1e-8; //stepsize for numerical differentiation
 
-  const double deps = 1e-8;  //stepsize for numerical differentiation
+    CopyVec(6, x, x0);
+
+    Cell_Pass(0, globval.Cell_nLoc, x0, lastpos);
+    CopyVec(n, x0, fvect);
 
-  CopyVec(6, x, x0);
-  
-  Cell_Pass(0, globval.Cell_nLoc, x0, lastpos);
-  CopyVec(n, x0, fvect);
-  
-  // compute Jacobian matrix by numerical differentiation
-  for (k = 0; k < n; k++) {
-    CopyVec(6L, x, x0);
-    x0[k] += deps;  // differential step in coordinate k
+    // compute Jacobian matrix by numerical differentiation
+    for (k = 0; k < n; k++) {
+        CopyVec(6L, x, x0);
+        x0[k] += deps; // differential step in coordinate k
 
-    Cell_Pass(0, globval.Cell_nLoc, x0, lastpos);  // tracking along the ring
-      CopyVec(6L, x0, fx1);
+        Cell_Pass(0, globval.Cell_nLoc, x0, lastpos); // tracking along the ring
+        CopyVec(6L, x0, fx1);
 
-      CopyVec(6L, x, x0);
-    x0[k] -= deps;  // differential step in coordinate k
+        CopyVec(6L, x, x0);
+        x0[k] -= deps; // differential step in coordinate k
 
-    Cell_Pass(0, globval.Cell_nLoc, x0, lastpos);  // tracking along the ring
-      CopyVec(6L, x0, fx2);
+        Cell_Pass(0, globval.Cell_nLoc, x0, lastpos); // tracking along the ring
+        CopyVec(6L, x0, fx2);
 
-    for (i = 0; i < n; i++)  // symmetric difference formula
-      fjac[i][k] = 0.5 * (fx1[i] - fx2[i]) / deps;
-  }
+        for (i = 0; i < n; i++) // symmetric difference formula
+            fjac[i][k] = 0.5 * (fx1[i] - fx2[i]) / deps;
+    }
 }
 
 /****************************************************************************/
 /* void Newton_RaphsonS(int ntrial,double x[],int n,double tolx, double tolf)
  
-   Purpose:
-       Newton_Rapson algorithm from Numerical Recipes
-       single precision algorithm
-       Robustess: quadratic convergence
-       Hint: for n-dimensional problem, the algo can be stuck on local minimum
-             In this case, it should be enough to provide a resonable starting 
-             point.
-
-       Method:
-         look for closed orbit solution of f(x) = x
-         This problems is equivalent to finding the zero of g(x)= f(x) - x
-         g(x+h) ~= f(x) - x + (Jacobian(f) -Id) h + O(h*h)
-         Then at first order we solve h:
-             h = - inverse(Jacobian(f) -Id) * (f(x)-x)
-            the new guess is then xnew = x + h
-         By iteration, this converges quadratically.
-     
-     The algo is stopped whenever  |x -xnew| < tolx     
-
-         f(x) is computes by tracking over one turn
-     Jacobian(f) is computed numerically by numerical differentiation
-     These two operations are provided by the function computeFandJ
-
-   Input:
-       ntrial number of iterations for closed zero search
-       n number of dimension 4 or 6
-     x intial guess for the closed orbit
-       tolx tolerance over the solution x
-       tolf tolerance over the evalution f(x)  
-
-   Output:
-       x closed orbit  
-
-   Return:
-       none
-
-   Global variables:
-       status
-
-   specific functions:
-       computeFandJS
-     ludcmp,lubksb 
-
-   Comments:
-       none
-
-****************************************************************************/
-
-void Newton_RaphsonS(int ntrial, double x[], int n, double tolx)
-{
-  int    k, i, *indx;
-  double  errx, d, *bet, *fvect, **alpha;
-
-  errx = 0.0;
-  // NR arrays start from 1 and not 0 !!!       
-  indx = ivector(1, n);
-  bet = dvector(1, n);
-  fvect = dvector(1, n);
-  alpha = dmatrix(1, n, 1, n);
-
-  for (k = 1; k <= ntrial; k++) {      // loop over number of iterations
-    // supply function values at x in fvect and Jacobian matrix in fjac
-    computeFandJS(x, n, alpha, fvect);
-
-    // Jacobian -Id
-    for (i = 1; i <= n; i++)
-      alpha[i][i] -= 1.0;
-    for (i = 1; i <= n; i++)
-      bet[i] = x[i] - fvect[i];  // right side of linear equation
-    // solve linear equations using LU decomposition using NR routines
-    dludcmp(alpha, n, indx, &d);
-    dlubksb(alpha, n, indx, bet);
-    errx = 0.0;  // check root convergence
-    for (i = 1; i <= n; i++) {    // update solution
-      errx += fabs(bet[i]);
-      x[i] += bet[i];
-    }
-
-    if (trace)
-      fprintf(stdout,
-         "%02d: cod % .5e % .5e % .5e % .5e % .5e % .5e  errx =% .5e\n",
-         k, x[1], x[2], x[3], x[4], x[5], x[6], errx);
-    if (errx <= tolx) {
-      status.codflag = true;
-      break;
+ Purpose:
+ Newton_Rapson algorithm from Numerical Recipes
+ single precision algorithm
+ Robustess: quadratic convergence
+ Hint: for n-dimensional problem, the algo can be stuck on local minimum
+ In this case, it should be enough to provide a resonable starting
+ point.
+
+ Method:
+ look for closed orbit solution of f(x) = x
+ This problems is equivalent to finding the zero of g(x)= f(x) - x
+ g(x+h) ~= f(x) - x + (Jacobian(f) -Id) h + O(h*h)
+ Then at first order we solve h:
+ h = - inverse(Jacobian(f) -Id) * (f(x)-x)
+ the new guess is then xnew = x + h
+ By iteration, this converges quadratically.
+
+ The algo is stopped whenever  |x -xnew| < tolx
+
+ f(x) is computes by tracking over one turn
+ Jacobian(f) is computed numerically by numerical differentiation
+ These two operations are provided by the function computeFandJ
+
+ Input:
+ ntrial number of iterations for closed zero search
+ n number of dimension 4 or 6
+ x intial guess for the closed orbit
+ tolx tolerance over the solution x
+ tolf tolerance over the evalution f(x)
+
+ Output:
+ x closed orbit
+
+ Return:
+ none
+
+ Global variables:
+ status
+
+ specific functions:
+ computeFandJS
+ ludcmp,lubksb
+
+ Comments:
+ none
+
+ ****************************************************************************/
+
+void Newton_RaphsonS(int ntrial, double x[], int n, double tolx) {
+    int k, i, *indx;
+    double errx, d, *bet, *fvect, **alpha;
+
+    errx = 0.0;
+    // NR arrays start from 1 and not 0 !!!
+    indx = ivector(1, n);
+    bet = dvector(1, n);
+    fvect = dvector(1, n);
+    alpha = dmatrix(1, n, 1, n);
+
+    for (k = 1; k <= ntrial; k++) { // loop over number of iterations
+        // supply function values at x in fvect and Jacobian matrix in fjac
+        computeFandJS(x, n, alpha, fvect);
+
+        // Jacobian -Id
+        for (i = 1; i <= n; i++)
+            alpha[i][i] -= 1.0;
+        for (i = 1; i <= n; i++)
+            bet[i] = x[i] - fvect[i]; // right side of linear equation
+        // solve linear equations using LU decomposition using NR routines
+        dludcmp(alpha, n, indx, &d);
+        dlubksb(alpha, n, indx, bet);
+        errx = 0.0; // check root convergence
+        for (i = 1; i <= n; i++) { // update solution
+            errx += fabs(bet[i]);
+            x[i] += bet[i];
+        }
+
+        if (trace)
+            fprintf(
+                    stdout,
+                    "%02d: cod % .5e % .5e % .5e % .5e % .5e % .5e  errx =% .5e\n",
+                    k, x[1], x[2], x[3], x[4], x[5], x[6], errx);
+        if (errx <= tolx) {
+            status.codflag = true;
+            break;
+        }
     }
-  }
-  // check whenver closed orbit found out
-  if ((k >= ntrial) && (errx >= tolx * 100)) status.codflag = false;
+    // check whenver closed orbit found out
+    if ((k >= ntrial) && (errx >= tolx * 100))
+        status.codflag = false;
 
-  free_dmatrix(alpha,1,n,1,n); free_dvector(bet,1,n); free_dvector(fvect,1,n);
-  free_ivector(indx,1,n);
+    free_dmatrix(alpha, 1, n, 1, n);
+    free_dvector(bet, 1, n);
+    free_dvector(fvect, 1, n);
+    free_ivector(indx, 1, n);
 }
 
-
 /****************************************************************************/
 /* int Newton_Raphson(int n, double x[], int ntrial, double tolx)
  
-   Purpose:
-       Newton_Rapson algorithm from Numerical Recipes
-       double precision algorithm
-       Robustess: quadratic convergence
-       Hint: for n-dimensional problem, the algo can be stuck on local minimum
-             In this case, it should be enough to provide a resonable starting 
-             point.
-
-       Method:
-         look for closed orbit solution of f(x) = x
-         This problems is equivalent to finding the zero of g(x)= f(x) - x
-         g(x+h) ~= f(x) - x + (Jacobian(f) -Id) h + O(h*h)
-         Then at first order we solve h:
-             h = - inverse(Jacobian(f) -Id) * (f(x)-x)
-            the new guess is then xnew = x + h
-         By iteration, this converges quadratically.
-     
-     The algo is stopped whenever  |x -xnew| < tolx     
-
-         f(x) is computes by tracking over one turn
-     Jacobian(f) is computed numerically by numerical differentiation
-     These two operations are provided by the function computeFandJ
-
-   Input:
-       ntrial number of iterations for closed zero search
-     x intial guess for the closed orbit
-       tolx tolerance over the solution x
-       tolf tolerance over the evalution f(x)  
-
-   Output:
-       x closed orbit  
-
-   Return:
-       none
-
-   Global variables:
-       status
-
-   specific functions:
-       computeFandJ
-     InvMat, LinTrans 
-
-   Comments:
-       none
-
-****************************************************************************/
-int Newton_Raphson (int n, Vector &x, int ntrial, double tolx)
-{
-  int k,  i;
-  double  errx;
-  Vector  bet, fvect;
-  Matrix  alpha;
-
-  errx = 0.0;
-
-  for (k = 1; k <= ntrial; k++) {  // loop over number of iterations
-    // supply function values at x in fvect and Jacobian matrix in fjac
-    computeFandJ(n, x, alpha, fvect);
-
-    // Jacobian - Id
-    for (i = 0; i < n; i++)
-      alpha[i][i] -= 1.0;
-    for (i = 0; i < n; i++)
-      bet[i] = x[i] - fvect[i];  // right side of linear equation
-    // inverse matrix using gauss jordan method from Tracy (from NR)
-    if (!InvMat((long) n,alpha))
-      fprintf(stdout,"Matrix non inversible ...\n");    
-    LinTrans((long) n, alpha, bet); // bet = alpha*bet
-        errx = 0.0;  // check root convergence
-    for (i = 0; i < n; i++)
-    {    // update solution
-      errx += fabs(bet[i]);
-      x[i] += bet[i]; 
+ Purpose:
+ Newton_Rapson algorithm from Numerical Recipes
+ double precision algorithm
+ Robustess: quadratic convergence
+ Hint: for n-dimensional problem, the algo can be stuck on local minimum
+ In this case, it should be enough to provide a resonable starting
+ point.
+
+ Method:
+ look for closed orbit solution of f(x) = x
+ This problems is equivalent to finding the zero of g(x)= f(x) - x
+ g(x+h) ~= f(x) - x + (Jacobian(f) -Id) h + O(h*h)
+ Then at first order we solve h:
+ h = - inverse(Jacobian(f) -Id) * (f(x)-x)
+ the new guess is then xnew = x + h
+ By iteration, this converges quadratically.
+
+ The algo is stopped whenever  |x -xnew| < tolx
+
+ f(x) is computes by tracking over one turn
+ Jacobian(f) is computed numerically by numerical differentiation
+ These two operations are provided by the function computeFandJ
+
+ Input:
+ ntrial number of iterations for closed zero search
+ x intial guess for the closed orbit
+ tolx tolerance over the solution x
+ tolf tolerance over the evalution f(x)
+
+ Output:
+ x closed orbit
+
+ Return:
+ none
+
+ Global variables:
+ status
+
+ specific functions:
+ computeFandJ
+ InvMat, LinTrans
+
+ Comments:
+ none
+
+ ****************************************************************************/
+int Newton_Raphson(int n, Vector &x, int ntrial, double tolx) {
+    int k, i;
+    double errx;
+    Vector bet, fvect;
+    Matrix alpha;
+
+    errx = 0.0;
+
+    for (k = 1; k <= ntrial; k++) { // loop over number of iterations
+        // supply function values at x in fvect and Jacobian matrix in fjac
+        computeFandJ(n, x, alpha, fvect);
+
+        // Jacobian - Id
+        for (i = 0; i < n; i++)
+            alpha[i][i] -= 1.0;
+        for (i = 0; i < n; i++)
+            bet[i] = x[i] - fvect[i]; // right side of linear equation
+        // inverse matrix using gauss jordan method from Tracy (from NR)
+        if (!InvMat((long) n, alpha))
+            fprintf(stdout, "Matrix non inversible ...\n");
+        LinTrans((long) n, alpha, bet); // bet = alpha*bet
+        errx = 0.0; // check root convergence
+        for (i = 0; i < n; i++) { // update solution
+            errx += fabs(bet[i]);
+            x[i] += bet[i];
+        }
+
+        if (trace)
+            fprintf(
+                    stdout,
+                    "%02d: cod2 % .5e % .5e % .5e % .5e % .5e % .5e  errx =% .5e\n",
+                    k, x[0], x[1], x[2], x[3], x[4], x[5], errx);
+        if (errx <= tolx) {
+            status.codflag = true;
+            return 1;
+        }
     }
-    
-    if (trace)
-      fprintf(stdout,
-         "%02d: cod2 % .5e % .5e % .5e % .5e % .5e % .5e  errx =% .5e\n",
-         k, x[0], x[1], x[2], x[3], x[4], x[5], errx);
-    if (errx <= tolx)
-    {
-      status.codflag = true;
+    // check whever closed orbit found out
+    if ((k >= ntrial) && (errx >= tolx)) {
+        status.codflag = false;
         return 1;
     }
-  }
-  // check whever closed orbit found out
-  if ((k >= ntrial) && (errx >= tolx))
-  {
-    status.codflag = false;
-      return 1;
-  }
-  return 0;
+    return 0;
 }
 
+void rm_mean(long int n, double x[]) {
+    long int i;
+    double mean;
 
-
-void rm_mean(long int n, double x[])
-{
-  long int  i;
-  double    mean;
-
-  mean = 0.0;
-  for (i = 0; i < n; i++)
-    mean += x[i];
-  mean /= n;
-  for (i = 0; i < n; i++)
-    x[i] -= mean;
+    mean = 0.0;
+    for (i = 0; i < n; i++)
+        mean += x[i];
+    mean /= n;
+    for (i = 0; i < n; i++)
+        x[i] -= mean;
 }
diff --git a/tracy/tracy/src/prtmfile.cc b/tracy/tracy/src/prtmfile.cc
index 181fbd5b8fa43d00d7beb1df89b1a82588f3874b..b8d99aacc83d0fc639a5ddb8fcf2e4a5b94da74a 100644
--- a/tracy/tracy/src/prtmfile.cc
+++ b/tracy/tracy/src/prtmfile.cc
@@ -1,67 +1,66 @@
 /* Tracy-2
 
-   J. Bengtsson, CBP, LBL      1990 - 1994   Pascal version
-                 SLS, PSI      1995 - 1997
-   M. Boege      SLS, PSI      1998          C translation
-   L. Nadolski   SOLEIL        2002          Link to NAFF, Radia field maps
-   J. Bengtsson  NSLS-II, BNL  2004 -        
+ J. Bengtsson, CBP, LBL      1990 - 1994   Pascal version
+ SLS, PSI      1995 - 1997
+ M. Boege      SLS, PSI      1998          C translation
+ L. Nadolski   SOLEIL        2002          Link to NAFF, Radia field maps
+ J. Bengtsson  NSLS-II, BNL  2004 -
 
 
-   To generate a lattice flat file.
+ To generate a lattice flat file.
 
-   Type codes:
+ Type codes:
 
-     marker     -1
-     drift	 0
-     multipole   1
-     cavity      2
-     thin kick   3
-     wiggler     4
-     kick_map    6
+ marker     -1
+ drift	 0
+ multipole   1
+ cavity      2
+ thin kick   3
+ wiggler     4
+ kick_map    6
 
-   Integration methods:
+ Integration methods:
 
-     fourth order symplectic integrator   4
+ fourth order symplectic integrator   4
 
-   Format:
+ Format:
 
-     name, family no, kid no, element no
-     type code, integration method, no of integration steps
-     vacuum apertures: xmin, xmax, ymin, ymax
+ name, family no, kid no, element no
+ type code, integration method, no of integration steps
+ vacuum apertures: xmin, xmax, ymin, ymax
 
-   The following lines follows depending on element type.
+ The following lines follows depending on element type.
 
-     type
+ type
 
  1)  drift:	 L
 
  2)  multipole:  
-                 a.)  hor., ver. displacement, roll angle (design), roll angle (error);
-                 b.)  L, 1/rho, entrance angle, exit angle, totoal magnet gap[m];
-		 c.)  number of orders with nonzero field components, design field order
-		 d.)  The last lines are the nonzero multipole components, 
-		     the format is:
-		        n, Bn , An
-                        where n is the field order, Bn is the upright 
-		        field component, Bn is the skew field component   
+ a.)  hor., ver. displacement, roll angle (design), roll angle (error);
+ b.)  L, 1/rho, entrance angle, exit angle, totoal magnet gap[m];
+ c.)  number of orders with nonzero field components, design field order
+ d.)  The last lines are the nonzero multipole components,
+ the format is:
+ n, Bn , An
+ where n is the field order, Bn is the upright
+ field component, Bn is the skew field component
 
  3)  wiggler:    L [m], lambda [m]
-                 no of harmonics
-                 harm no, kxV [1/m], BoBrhoV [1/m], kxH, BoBrhoH, phi
-                    ...
+ no of harmonics
+ harm no, kxV [1/m], BoBrhoV [1/m], kxH, BoBrhoH, phi
+ ...
 
  4)  cavity:	 cavity voltage/beam energy [eV], omega/c, beam energy [eV]
 
  5)  thin kick:	 hor., ver. displacement, roll angle (total)
-		 no of nonzero multipole coeff.
-		 n, b , a
-		     n   n
-		    ...
+ no of nonzero multipole coeff.
+ n, b , a
+ n   n
+ ...
 
-6)   kick_map:   order <file name>
-
-*/
+ 6)   kick_map:   order <file name>
 
+ */
 
 #define snamelen 10
 
@@ -75,88 +74,98 @@
 #define kick_map_  6
 
 /******************************************************************************
-void prtName(FILE *fp, const int i,
-	     const int type, const int method, const int N)
-
-    Purpose:
-        Print out the general imformation of an element to a file
-
-    Input:
-        i                index number in the whole lattice
-	type             predfined integer number for different type of element
-	                     Type codes:
-                                    marker         -1
-                                    drift	    0
-                                    multipole       1
-                                    cavity          2
-                                    thin kick       3
-                                    wiggler         4
-                                    kick_map        6
-        
-	method             integrated method
-	N                  number of integration steps of the element
-	
-    Output:
-        Output to the file as the first 3 lines in file "fp":
-	
-	L1:      element name, family index, kid index, element index in the whole lattice
-        L2:      type code, integration method,  number of integration steps
-        L3:      vacuum apertures: xmin, xmax, ymin, ymax
-
-    Comments:
-         Called by prtmfile()
-******************************************************************************/
-void prtName(FILE *fp, const int i,
-	     const int type, const int method, const int N)
-{
-  fprintf(fp, "%-15s %4ld %4ld %4d\n",
-	  Cell[i].Elem.PName, Cell[i].Fnum, Cell[i].Knum, i);
+ void prtName(FILE *fp, const int i,
+ const int type, const int method, const int N)
+
+ Purpose:
+ Print out the general imformation of an element to a file
+
+ Input:
+ i                index number in the whole lattice
+ type             predfined integer number for different type of element
+ Type codes:
+ marker         -1
+ drift	    0
+ multipole       1
+ cavity          2
+ thin kick       3
+ wiggler         4
+ kick_map        6
+
+ method             integrated method
+ N                  number of integration steps of the element
+
+ Output:
+ Output to the file as the first 3 lines in file "fp":
+
+ L1:      element name, family index, kid index, element index in the whole lattice
+ L2:      type code, integration method,  number of integration steps
+ L3:      vacuum apertures: xmin, xmax, ymin, ymax
+
+ Comments:
+ Called by prtmfile()
+ ******************************************************************************/
+void prtName(FILE *fp, const int i, const int type, const int method,
+    const int N) {
+  fprintf(fp, "%-15s %4ld %4ld %4d\n", Cell[i].Elem.PName, Cell[i].Fnum,
+      Cell[i].Knum, i);
   fprintf(fp, " %3d %3d %3d\n", type, method, N);
-  fprintf(fp, " %23.16e %23.16e %23.16e %23.16e\n",
-	  Cell[i].maxampl[X_][0], Cell[i].maxampl[X_][1],
-	  Cell[i].maxampl[Y_][0], Cell[i].maxampl[Y_][1]);
+  fprintf(fp, " %23.16e %23.16e %23.16e %23.16e\n", Cell[i].maxampl[X_][0],
+      Cell[i].maxampl[X_][1], Cell[i].maxampl[Y_][0], Cell[i].maxampl[Y_][1]);
 }
 
 /******************************************************************************
-void prtHOM(FILE *fp, const int n_design, const mpolArray PB, const int Order)
-
-    Purpose:
-        Print out all field component for multipole to a file
-
-    Input:
-        fp               file name
-	n_design         design order of multipole
-	PB               multipole field components arry, format is: n Bn An
-	Order            maximum order of multipole
-	
-    Output:
-        None
-
-    Comments:
-         Called by prtmfile()
-******************************************************************************/
-void prtHOM(FILE *fp, const int n_design, const mpolArray PB, const int Order)
-{
+ void prtHOM(FILE *fp, const int n_design, const mpolArray PB, const int Order)
+
+ Purpose:
+ Print out all field component for multipole to a file
+
+ Input:
+ fp               file name
+ n_design         design order of multipole
+ PB               multipole field components arry, format is: n Bn An
+ Order            maximum order of multipole
+
+ Output:
+ None
+
+ Comments:
+ Called by prtmfile()
+ ******************************************************************************/
+void prtHOM(FILE *fp, const int n_design, const mpolArray PB, const int Order) {
   int i = 0, nmpole = 0;
-  
-  for (i = 1; i <= Order; i++){
-    if ((PB[HOMmax-i] != 0.0) || (PB[HOMmax+i] != 0.0)) 
+
+  for (i = 1; i <= Order; i++) {
+    if ((PB[HOMmax - i] != 0.0) || (PB[HOMmax + i] != 0.0))
       nmpole++;
   }
-  
+
   fprintf(fp, "  %2d %2d\n", nmpole, n_design);
-  
+
   for (i = 1; i <= Order; i++) {
-    if ((PB[HOMmax-i] != 0.0) || (PB[HOMmax+i] != 0.0))
-      fprintf(fp, "%3d %23.16e %23.16e\n", i, PB[HOMmax+i], PB[HOMmax-i]);
+    if ((PB[HOMmax - i] != 0.0) || (PB[HOMmax + i] != 0.0))
+      fprintf(fp, "%3d %23.16e %23.16e\n", i, PB[HOMmax + i], PB[HOMmax - i]);
   }
 }
 
+/******************************************************************************
+ void prtmfile(const char mfile_dat[])
+
+ Purpose:
+ Print out flatfile
+
+ Input:
+ fp           filename
+
+ Output:
+ None
+
+ Comments:
 
-void prtmfile(const char mfile_dat[])
-{
-  int     i, j;
-  FILE    *mfile;
+ ******************************************************************************/
+void prtmfile(const char mfile_dat[]) {
+  int i, j;
+  FILE *mfile;
 
   mfile = file_write(mfile_dat);
   for (i = 0; i <= globval.Cell_nLoc; i++) {
@@ -167,61 +176,55 @@ void prtmfile(const char mfile_dat[])
       break;
     case Mpole:
       if (Cell[i].Elem.PL != 0.0) {
-	prtName(mfile, i, mpole_, Cell[i].Elem.M->Pmethod, Cell[i].Elem.M->PN);
-	fprintf(mfile, " %23.16e %23.16e %23.16e %23.16e\n",
-		Cell[i].dS[X_], Cell[i].dS[Y_],
-		Cell[i].Elem.M->PdTpar,
-		Cell[i].Elem.M->PdTsys
-		+Cell[i].Elem.M->PdTrms*Cell[i].Elem.M->PdTrnd);
-	fprintf(mfile, " %23.16e %23.16e %23.16e %23.16e %23.16e\n",
-		Cell[i].Elem.PL, Cell[i].Elem.M->Pirho,
-		Cell[i].Elem.M->PTx1, Cell[i].Elem.M->PTx2,
-		Cell[i].Elem.M->Pgap);
-	prtHOM(mfile, Cell[i].Elem.M->n_design, Cell[i].Elem.M->PB,
-	       Cell[i].Elem.M->Porder);
+        prtName(mfile, i, mpole_, Cell[i].Elem.M->Pmethod, Cell[i].Elem.M->PN);
+        fprintf(mfile, " %23.16e %23.16e %23.16e %23.16e\n", Cell[i].dS[X_],
+            Cell[i].dS[Y_], Cell[i].Elem.M->PdTpar, Cell[i].Elem.M->PdTsys
+                + Cell[i].Elem.M->PdTrms * Cell[i].Elem.M->PdTrnd);
+        fprintf(mfile, " %23.16e %23.16e %23.16e %23.16e %23.16e\n",
+            Cell[i].Elem.PL, Cell[i].Elem.M->Pirho, Cell[i].Elem.M->PTx1,
+            Cell[i].Elem.M->PTx2, Cell[i].Elem.M->Pgap);
+        prtHOM(mfile, Cell[i].Elem.M->n_design, Cell[i].Elem.M->PB,
+            Cell[i].Elem.M->Porder);
       } else {
-	prtName(mfile, i, thinkick_, Cell[i].Elem.M->Pmethod,
-		Cell[i].Elem.M->PN);
-	fprintf(mfile, " %23.16e %23.16e %23.16e\n",
-		Cell[i].dS[X_], Cell[i].dS[Y_],
-		Cell[i].Elem.M->PdTsys
-		+Cell[i].Elem.M->PdTrms*Cell[i].Elem.M->PdTrnd);
-	prtHOM(mfile, Cell[i].Elem.M->n_design, Cell[i].Elem.M->PB,
-	       Cell[i].Elem.M->Porder);
+        prtName(mfile, i, thinkick_, Cell[i].Elem.M->Pmethod,
+            Cell[i].Elem.M->PN);
+        fprintf(mfile, " %23.16e %23.16e %23.16e\n", Cell[i].dS[X_],
+            Cell[i].dS[Y_], Cell[i].Elem.M->PdTsys + Cell[i].Elem.M->PdTrms
+                * Cell[i].Elem.M->PdTrnd);
+        prtHOM(mfile, Cell[i].Elem.M->n_design, Cell[i].Elem.M->PB,
+            Cell[i].Elem.M->Porder);
       }
       break;
     case Wigl:
       prtName(mfile, i, wiggler_, Cell[i].Elem.W->Pmethod, Cell[i].Elem.W->PN);
-      fprintf(mfile, " %23.16e %23.16e\n",
-	      Cell[i].Elem.PL, Cell[i].Elem.W->lambda);
+      fprintf(mfile, " %23.16e %23.16e\n", Cell[i].Elem.PL,
+          Cell[i].Elem.W->lambda);
       fprintf(mfile, "%2d\n", Cell[i].Elem.W->n_harm);
       for (j = 0; j < Cell[i].Elem.W->n_harm; j++) {
-	fprintf(mfile, "%2d %23.16e %23.16e %23.16e %23.16e %23.16e\n",
-		Cell[i].Elem.W->harm[j],
-		Cell[i].Elem.W->kxV[j], Cell[i].Elem.W->BoBrhoV[j],
-		Cell[i].Elem.W->kxH[j], Cell[i].Elem.W->BoBrhoH[j],
-		Cell[i].Elem.W->phi[j]);
+        fprintf(mfile, "%2d %23.16e %23.16e %23.16e %23.16e %23.16e\n",
+            Cell[i].Elem.W->harm[j], Cell[i].Elem.W->kxV[j],
+            Cell[i].Elem.W->BoBrhoV[j], Cell[i].Elem.W->kxH[j],
+            Cell[i].Elem.W->BoBrhoH[j], Cell[i].Elem.W->phi[j]);
       }
       break;
     case Cavity:
       prtName(mfile, i, cavity_, 0, 0);
-      fprintf(mfile, " %23.16e %23.16e %d %23.16e\n",
-	      Cell[i].Elem.C->Pvolt/(1e9*globval.Energy),
-	      2.0*M_PI*Cell[i].Elem.C->Pfreq/c0, Cell[i].Elem.C->Ph,
-	      1e9*globval.Energy);
+      fprintf(mfile, " %23.16e %23.16e %d %23.16e\n", Cell[i].Elem.C->Pvolt
+          / (1e9 * globval.Energy), 2.0 * M_PI * Cell[i].Elem.C->Pfreq / c0,
+          Cell[i].Elem.C->Ph, 1e9 * globval.Energy);
       break;
     case marker:
       prtName(mfile, i, marker_, 0, 0);
       break;
     case Insertion:
       prtName(mfile, i, kick_map_, Cell[i].Elem.ID->Pmethod,
-	      Cell[i].Elem.ID->PN);
+          Cell[i].Elem.ID->PN);
       if (Cell[i].Elem.ID->firstorder)
-	fprintf(mfile, " %3.1lf %1d %s\n",
-		Cell[i].Elem.ID->scaling, 1, Cell[i].Elem.ID->fname1);
-      else
-	fprintf(mfile, " %3.1lf %1d %s\n",
-		Cell[i].Elem.ID->scaling, 2, Cell[i].Elem.ID->fname2);
+        fprintf(mfile, " %3.1lf %1d %s\n", Cell[i].Elem.ID->scaling1, 1,
+            Cell[i].Elem.ID->fname1);
+      if (Cell[i].Elem.ID->secondorder)
+        fprintf(mfile, " %3.1lf %1d %s\n", Cell[i].Elem.ID->scaling1, 2,
+            Cell[i].Elem.ID->fname2);
       break;
     default:
       fprintf(mfile, "prtmfile: unknown type\n");
diff --git a/tracy/tracy/src/radia2tracy.cc b/tracy/tracy/src/radia2tracy.cc
index 3f65ea812eaf0d22d34948da231b0e935ab5bcfb..efc1066f000bcf45e36e4f5c19475cf535dd6a56 100644
--- a/tracy/tracy/src/radia2tracy.cc
+++ b/tracy/tracy/src/radia2tracy.cc
@@ -1,540 +1,661 @@
 /* Tracy-2
 
-   J. Bengtsson, CBP, LBL      1990 - 1994   Pascal version
-                 SLS, PSI      1995 - 1997
-   M. Boege      SLS, PSI      1998          C translation
-   L. Nadolski   SOLEIL        2002          Link to NAFF, Radia field maps
-   J. Bengtsson  NSLS-II, BNL  2004 -        
+ J. Bengtsson, CBP, LBL      1990 - 1994   Pascal version
+ SLS, PSI      1995 - 1997
+ M. Boege      SLS, PSI      1998          C translation
+ L. Nadolski   SOLEIL        2002          Link to NAFF, Radia field maps
+ J. Bengtsson  NSLS-II, BNL  2004 -
 
-*/
+ */
 
 /* Spline routine adapted from NR with template */
 template<typename T>
-void spline(const double x[], const T y[], int const n,
-	    double const yp1, const double ypn, T y2[])
+void spline(const double x[], const T y[], int const n, double const yp1,
+        const double ypn, T y2[])
 /* Function to be called only once
-Given arrays x[1..n] and y[1..n] containing a tabulated function, i.e., yi = f(xi), with
-x1 <x2 < :: : < xN, and given values yp1 and ypn for the first derivative of the interpolating
-function at points 1 and n, respectively, this routine returns an array y2[1..n] that contains
-the second derivatives of the interpolating function at the tabulated points xi. If yp1 and/or
-ypn are equal to 10e30 or larger, the routine is signaled to set the corresponding boundary
-condition for a natural spline, with zero second derivative on that boundary.
-*/
+ Given arrays x[1..n] and y[1..n] containing a tabulated function, i.e., yi = f(xi), with
+ x1 <x2 < :: : < xN, and given values yp1 and ypn for the first derivative of the interpolating
+ function at points 1 and n, respectively, this routine returns an array y2[1..n] that contains
+ the second derivatives of the interpolating function at the tabulated points xi. If yp1 and/or
+ ypn are equal to 10e30 or larger, the routine is signaled to set the corresponding boundary
+ condition for a natural spline, with zero second derivative on that boundary.
+ */
 {
-  int     i, k;
-  double  sig;
-  T       p, u[n], qn, un;
-
-  if (yp1 > 0.99e30)
-    y2[1] = u[1] = 0.0;
-  else {
-    y2[1] = -0.5; u[1] = (3.0/(x[2]-x[1]))*((y[2]-y[1])/(x[2]-x[1])-yp1);
-  }
-  for (i = 2; i <= n-1; i++) {
-    sig = (x[i]-x[i-1])/(x[i+1]-x[i-1]); p = sig*y2[i-1]+2.0;
-    y2[i] = (sig-1.0)/p;
-    u[i] = (y[i+1]-y[i])/(x[i+1]-x[i]) - (y[i]-y[i-1])/(x[i]-x[i-1]);
-    u[i] = (6.0*u[i]/(x[i+1]-x[i-1])-sig*u[i-1])/p;
-  }
-  if (ypn > 0.99e30)
-    qn = un = 0.0;
-  else {
-    qn = 0.5; un = (3.0/(x[n]-x[n-1]))*(ypn-(y[n]-y[n-1])/(x[n]-x[n-1]));
-  }
-  y2[n] = (un-qn*u[n-1])/(qn*y2[n-1]+1.0);
-  for (k = n-1; k >= 1; k--)
-    y2[k] = y2[k]*y2[k+1]+u[k];
-}
+    int i, k;
+    double sig;
+    T p, u[n], qn, un;
 
+    if (yp1 > 0.99e30)
+        y2[1] = u[1] = 0.0;
+    else {
+        y2[1] = -0.5;
+        u[1] = (3.0 / (x[2] - x[1])) * ((y[2] - y[1]) / (x[2] - x[1]) - yp1);
+    }
+    for (i = 2; i <= n - 1; i++) {
+        sig = (x[i] - x[i - 1]) / (x[i + 1] - x[i - 1]);
+        p = sig * y2[i - 1] + 2.0;
+        y2[i] = (sig - 1.0) / p;
+        u[i] = (y[i + 1] - y[i]) / (x[i + 1] - x[i]) - (y[i] - y[i - 1])
+                / (x[i] - x[i - 1]);
+        u[i] = (6.0 * u[i] / (x[i + 1] - x[i - 1]) - sig * u[i - 1]) / p;
+    }
+    if (ypn > 0.99e30)
+        qn = un = 0.0;
+    else {
+        qn = 0.5;
+        un = (3.0 / (x[n] - x[n - 1])) * (ypn - (y[n] - y[n - 1]) / (x[n] - x[n
+                - 1]));
+    }
+    y2[n] = (un - qn * u[n - 1]) / (qn * y2[n - 1] + 1.0);
+    for (k = n - 1; k >= 1; k--)
+        y2[k] = y2[k] * y2[k + 1] + u[k];
+}
 
 template<typename T, typename U>
-void splint(const double xa[], const U ya[], const U y2a[],
-	    const int n, const T &x, T &y)
+void splint(const double xa[], const U ya[], const U y2a[], const int n,
+        const T &x, T &y)
 /* SPLine INTerpolation. Once spline are known, only evaluate polynome
  * Given the arrays xa[1..n] and ya[1..n], which tabulate a function (with the xai's in order),
-and given the array y2a[1..n], which is the output from spline above, and given a value of
-x, this routine returns a cubic-spline interpolated value y.
-*/
+ and given the array y2a[1..n], which is the output from spline above, and given a value of
+ x, this routine returns a cubic-spline interpolated value y.
+ */
 {
-  int     klo, khi, k;
-  double  h;
-  T       a, b;
-  
-  klo = 1; khi = n;
-  while (khi-klo > 1) {
-    k = (khi+klo) >> 1;
-    if (xa[k] > x)
-      khi = k;
-    else
-      klo = k;
-  }
-  h = xa[khi]-xa[klo];
-  if (h == 0.0) nrerror("Bad xa input to routine splint");
-  a = (xa[khi]-x)/h; b = (x-xa[klo])/h;
-  y = a*ya[klo]+b*ya[khi]+((a*a*a-a)*y2a[klo]+(b*b*b-b)*y2a[khi])*(h*h)/6.0;
-}
+    int klo, khi, k;
+    double h;
+    T a, b;
 
+    klo = 1;
+    khi = n;
+    while (khi - klo > 1) {
+        k = (khi + klo) >> 1;
+        if (xa[k] > x)
+            khi = k;
+        else
+            klo = k;
+    }
+    h = xa[khi] - xa[klo];
+    if (h == 0.0)
+        nrerror("Bad xa input to routine splint");
+    a = (xa[khi] - x) / h;
+    b = (x - xa[klo]) / h;
+    y = a * ya[klo] + b * ya[khi] + ((a * a * a - a) * y2a[klo] + (b * b * b
+            - b) * y2a[khi]) * (h * h) / 6.0;
+}
 
 template<typename T>
-void splin2(const double x1a[], const double x2a[],
-	    double **ya, double **y2a, const int m, const int n,
-	    const T &x1, const T &x2, T &y)
+void splin2(const double x1a[], const double x2a[], double **ya, double **y2a,
+        const int m, const int n, const T &x1, const T &x2, T &y)
 /* Main function computing the bicubic spline
-Given x1a, x2a, ya, m, n as described in splie2 and y2a as produced by that routine; and
-given a desired interpolating point x1,x2; this routine returns an interpolated function value y
-by bicubic spline interpolation.
+ Given x1a, x2a, ya, m, n as described in splie2 and y2a as produced by that routine; and
+ given a desired interpolating point x1,x2; this routine returns an interpolated function value y
+ by bicubic spline interpolation.
  */{
-  int  j;
-  T    ytmp[m+1], yytmp[m+1]; // Perform m evaluations of the row splines constructed by
-  
-  for (j = 1; j <= m; j++) //splie2, using the one-dimensional spline evaluator
-    splint(x2a, ya[j], y2a[j], n, x2, yytmp[j]); //splint.
-  spline(x1a, yytmp, m, 1.0e30, 1.0e30, ytmp); // Construct the one-dimensional column spline and evaluate it.
-  splint(x1a, yytmp, ytmp, m, x1, y);
-}
+    int j;
+    T ytmp[m + 1], yytmp[m + 1]; // Perform m evaluations of the row splines constructed by
 
+    for (j = 1; j <= m; j++) //splie2, using the one-dimensional spline evaluator
+        splint(x2a, ya[j], y2a[j], n, x2, yytmp[j]); //splint.
+    spline(x1a, yytmp, m, 1.0e30, 1.0e30, ytmp); // Construct the one-dimensional column spline and evaluate it.
+    splint(x1a, yytmp, ytmp, m, x1, y);
+}
 
-void splie2(double x1a[], double x2a[], double **ya,
-	    int m, int n, double **y2a)
+void splie2(double x1a[], double x2a[], double **ya, int m, int n, double **y2a)
 /* precompute the auxiliary second-derivative table
-Given an m by n tabulated function ya[1..m][1..n], and tabulated independent variables
-x2a[1..n], this routine constructs one-dimensional natural cubic splines of the rows of ya
-and returns the second-derivatives in the array y2a[1..m][1..n]. (The array x1a[1..m] is
-included in the argument list merely for consistency with routine splin2.)
-*/
+ Given an m by n tabulated function ya[1..m][1..n], and tabulated independent variables
+ x2a[1..n], this routine constructs one-dimensional natural cubic splines of the rows of ya
+ and returns the second-derivatives in the array y2a[1..m][1..n]. (The array x1a[1..m] is
+ included in the argument list merely for consistency with routine splin2.)
+ */
 {
-  int  j;
+    int j;
 
-  for (j = 1; j <= m; j++)
-	  // Values 10e30 signal a natural spline
-    spline(x2a, ya[j], n, 1.0e30, 1.0e30, y2a[j]);
+    for (j = 1; j <= m; j++)
+        // Values 10e30 signal a natural spline
+        spline(x2a, ya[j], n, 1.0e30, 1.0e30, y2a[j]);
 }
 
-
 /****************************************************************************/
 /* void  Read_IDfile(char *fic_radia, int *pnx, int *pnz,
-                 double tabx[IDXMAX],  double tabz[IDZMAX],
-                 double thetax[IDZMAX][IDXMAX], double thetaz[IDZMAX][IDXMAX])
-   Purpose:
-        Reads ID parameters from file specified by fic_radia
-        First or Second order terms        
-        
-   Input:
-        fic_radia radia file to read ID description from
-        The input format is the same for first and second order kicks
-        
-   Output:
-        pnx    horizontal point number for theta matrices
-        pnz    horizontal point number for theta matrices
-        tabx   tabular for horizontal descretization values
-        tabz   tabular for vertical descretization values
-        thetax 2D horizontal matrice for first or second order kicks
-        thetaz 2D vertical matrice for first or second order kicks
+ double tabx[IDXMAX],  double tabz[IDZMAX],
+ double thetax[IDZMAX][IDXMAX], double thetaz[IDZMAX][IDXMAX])
+ Purpose:
+ Reads ID parameters from file specified by fic_radia
+ First or Second order terms
+
+ Input:
+ fic_radia radia file to read ID description from
+ The input format is the same for first and second order kicks
+
+ Output:
+ pnx    horizontal point number for theta matrices
+ pnz    horizontal point number for theta matrices
+ tabx   tabular for horizontal discretization values
+ tabz   tabular for vertical discretization values
+ thetax 2D horizontal matrix for first or second order kicks
+ thetaz 2D vertical matrix for first or second order kicks
+
+ Return:
+ none
+
+ Global variables:
+ none
+
+ Specific functions:
+ none
  
-   Return:
-        none
-        
-   Global variables:
-        none
-        
-   Specific functions:
-        none
-        
-   Comments:
-       WARNING: the filename must be a lowercase name without special
-                characters !!!
-
-                and without its MANDATORY .dat extension
-       18/10/03 add test for numerical zero to correct H chromaticity
-                divergence
-****************************************************************************/
+ Comments:
+ WARNING: the filename must be a lowercase name without special
+ characters !!!
+
+ and without its MANDATORY .dat extension
+ 18/10/03 add test for numerical zero to correct H chromaticity
+ divergence
+ ****************************************************************************/
 
 #define ZERO_RADIA 1e-7
 void Read_IDfile(char *fic_radia, double *L, int *pnx, int *pnz,
-                 double tabx[IDXMAX],  double tabz[IDZMAX],
-                 double thetax[IDZMAX][IDXMAX], double thetaz[IDZMAX][IDXMAX])
-{
-  FILE *fi;
-  char dummy[5000];
-  int nx, nz;
-  int i,j;
-  traceID = false;
-
-  /* open radia text file */
-  if ((fi = fopen(fic_radia,"r")) == NULL) {
-    fprintf(stdout, "Read_IDfile: Error while opening file %s \n",
-	    fic_radia);
-    exit_(1);
-  }
-  
-  fprintf(stdout, "\n");
-  fprintf(stdout, "Reading ID filename %s \n", fic_radia);
-  
-  /* first line */
-  fscanf(fi,"%[^\n]\n", dummy); /* Read a full line */
-  fprintf(stdout,"%s\n", dummy);
-  /* second line */
-  fscanf(fi,"%[^\n]\n", dummy);
-  fprintf(stdout,"%s\n", dummy);
-  /* third line */
-  fscanf(fi,"%[^\n]\n", dummy);
-  fprintf(stdout,"%s\n", dummy);
-  /* fourth line : Undulator length */
-  fscanf(fi,"%lf\n",L);
-  fprintf(stdout,"Insertion de longueur L = %lf m\n",*L);
-  /* fifth line */
-  fscanf(fi,"%[^\n]\n", dummy);
-  fprintf(stdout,"%s\n", dummy);
-  /* sisxth line : Number of Horizontal points */
-  fscanf(fi,"%d\n",&nx);
-  fprintf(stdout,"nx = %d\n", nx);
-  /* seventh line */
-  fscanf(fi,"%[^\n]\n", dummy);
-  fprintf(stdout,"%s\n", dummy);
-  /* Number of Vertical points */
-  fscanf(fi,"%d\n",&nz);
-  fprintf(stdout,"nz = %d\n", nz);
-  
-  /* Check dimensions */
-  if (nx > IDXMAX || nz > IDZMAX) {
-    fprintf(stdout,
-	    "Read_IDfile:  Increase the size of insertion tables \n");
-    fprintf(stdout, "nx = % d (IDXmax = %d) and nz = %d (IDZMAX = % d) \n",
-	    nx, IDXMAX, nz, IDZMAX);
-    exit_(1);
-  }
-  
-  /* ninth line */
-  fscanf(fi, "%[^\n]\n", dummy);
-  //  fprintf(stdout, "%s\n", dummy);
-  /* tenth line */
-  fscanf(fi, "%[^\n]\n", dummy);
-  //  fprintf(stdout,"%s\n", dummy);
-  
-  /* eleventh line : x scaling */
-  //  fscanf(fi, "%[^\n]\n", &dummy);
-  //  fprintf(stdout, "%s\n", dummy);
-  
-  for (j = 0; j < nx; j++)
-    fscanf(fi, "%lf", &tabx[j]);
-  fscanf(fi, "%[^\n]\n", dummy);
-  
-  /* Array creation for thetax */
-  for (i = 0; i < nz; i++) {
-    //    fscanf(fi,"%*lf"); /*read without storage */
-    fscanf(fi, "%lf", &tabz[i]); /*read without storage */
-    
-    for (j = 0; j < nx; j++) {
-      fscanf(fi, "%lf", &thetax[i][j]);
-      if (fabs(thetax[i][j]) < ZERO_RADIA)
-	thetax[i][j] = 0.0;
-      if (traceID) fprintf(stdout,"%+12.8lf ", thetax[i][j]);
+        double tabx[IDXMAX], double tabz[IDZMAX],
+        double thetax[IDZMAX][IDXMAX], double thetaz[IDZMAX][IDXMAX]) {
+    FILE *fi;
+    char dummy[5000];
+    int nx, nz;
+    int i, j;
+    traceID = false;
+
+    /* open radia text file */
+    if ((fi = fopen(fic_radia, "r")) == NULL) {
+        fprintf(stdout, "Read_IDfile: Error while opening file %s \n",
+                fic_radia);
+        exit_(1);
     }
-    fscanf(fi,"\n");
-    if (traceID) fprintf(stdout,"\n");
-  }
-  
-  /* comment line */
-  fscanf(fi,"%[^\n]\n", dummy);
-  //  fprintf(stdout,"%s\n", dummy);
-  /* comment line */
-  fscanf(fi,"%[^\n]\n", dummy);
-  //  fprintf(stdout,"%s\n", dummy);
-  /* xscale */
-  //  fscanf(fi,"%[^\n]\n", dummy);
-  //  fprintf(stdout,"%s\n", dummy);
-  for (j = 0; j < nx; j++) {
-    fscanf(fi, "%lf", &tabx[j]);
-  }
-  
-  /* Array creation for thetaz */
-  for (i = 0; i < nz; i++) {
-    fscanf(fi, "%*f");
-    for (j = 0; j < nx; j++) {
-      fscanf(fi, "%lf", &thetaz[i][j]);
-      if (fabs(thetaz[i][j]) < ZERO_RADIA)
-	thetaz[i][j] = 0.0;
-      if (traceID)
-	fprintf(stdout, "%+12.8lf ", thetaz[i][j]);
+
+    fprintf(stdout, "\n");
+    fprintf(stdout, "Reading ID filename %s \n", fic_radia);
+
+    /* first line */
+    fscanf(fi, "%[^\n]\n", dummy); /* Read a full line */
+    fprintf(stdout, "%s\n", dummy);
+    /* second line */
+    fscanf(fi, "%[^\n]\n", dummy);
+    fprintf(stdout, "%s\n", dummy);
+    /* third line */
+    fscanf(fi, "%[^\n]\n", dummy);
+    fprintf(stdout, "%s\n", dummy);
+    /* fourth line : Undulator length */
+    fscanf(fi, "%lf\n", L);
+    fprintf(stdout, "Insertion of Length L = %lf m\n", *L);
+    /* fifth line */
+    fscanf(fi, "%[^\n]\n", dummy);
+    fprintf(stdout, "%s\n", dummy);
+    /* sisxth line : Number of Horizontal points */
+    fscanf(fi, "%d\n", &nx);
+    fprintf(stdout, "nx = %d\n", nx);
+    /* seventh line */
+    fscanf(fi, "%[^\n]\n", dummy);
+    fprintf(stdout, "%s\n", dummy);
+    /* Number of Vertical points */
+    fscanf(fi, "%d\n", &nz);
+    fprintf(stdout, "nz = %d\n", nz);
+
+    /* Check dimensions */
+    if (nx > IDXMAX || nz > IDZMAX) {
+        fprintf(stdout,
+                "Read_IDfile:  Increase the size of insertion tables \n");
+        fprintf(stdout, "nx = % d (IDXmax = %d) and nz = %d (IDZMAX = % d) \n",
+                nx, IDXMAX, nz, IDZMAX);
+        exit_(1);
     }
-    fscanf(fi, "\n");
-    if (traceID) fprintf(stdout, "\n");
-  }
-  
-  /* For debugging */
-  if (traceID)
+
+    /* ninth line */
+    fscanf(fi, "%[^\n]\n", dummy);
+    //  fprintf(stdout, "%s\n", dummy);
+    /* tenth line */
+    fscanf(fi, "%[^\n]\n", dummy);
+    //  fprintf(stdout,"%s\n", dummy);
+
+    /* eleventh line : x scaling */
+    //  fscanf(fi, "%[^\n]\n", &dummy);
+    //  fprintf(stdout, "%s\n", dummy);
+
+    for (j = 0; j < nx; j++)
+        fscanf(fi, "%lf", &tabx[j]);
+    fscanf(fi, "%[^\n]\n", dummy);
+
+    /* Array creation for thetax */
+    for (i = 0; i < nz; i++) {
+        //    fscanf(fi,"%*lf"); /*read without storage */
+        fscanf(fi, "%lf", &tabz[i]); /*read without storage */
+
+        for (j = 0; j < nx; j++) {
+            fscanf(fi, "%lf", &thetax[i][j]);
+            if (fabs(thetax[i][j]) < ZERO_RADIA)
+                thetax[i][j] = 0.0;
+            if (traceID)
+                fprintf(stdout, "%+12.8lf ", thetax[i][j]);
+        }
+        fscanf(fi, "\n");
+        if (traceID)
+            fprintf(stdout, "\n");
+    }
+
+    /* comment line */
+    fscanf(fi, "%[^\n]\n", dummy);
+    //  fprintf(stdout,"%s\n", dummy);
+    /* comment line */
+    fscanf(fi, "%[^\n]\n", dummy);
+    //  fprintf(stdout,"%s\n", dummy);
+    /* xscale */
+    //  fscanf(fi,"%[^\n]\n", dummy);
+    //  fprintf(stdout,"%s\n", dummy);
     for (j = 0; j < nx; j++) {
-      fprintf(stdout, "tabx[%d] =% lf\n", j, tabx[j]);
+        fscanf(fi, "%lf", &tabx[j]);
     }
-  if (traceID)
-    for (j = 0; j < nz; j++) {
-      fprintf(stdout, "tabz[%d] =% lf\n", j, tabz[j]);
+
+    /* Array creation for thetaz */
+    for (i = 0; i < nz; i++) {
+        fscanf(fi, "%*f");
+        for (j = 0; j < nx; j++) {
+            fscanf(fi, "%lf", &thetaz[i][j]);
+            if (fabs(thetaz[i][j]) < ZERO_RADIA)
+                thetaz[i][j] = 0.0;
+            if (traceID)
+                fprintf(stdout, "%+12.8lf ", thetaz[i][j]);
+        }
+        fscanf(fi, "\n");
+        if (traceID)
+            fprintf(stdout, "\n");
     }
-  
-  *pnx = nx; *pnz = nz;
-  
-  fclose(fi);
-}
 
+    /* For debugging */
+    if (traceID)
+        for (j = 0; j < nx; j++) {
+            fprintf(stdout, "tabx[%d] =% lf\n", j, tabx[j]);
+        }
+    if (traceID)
+        for (j = 0; j < nz; j++) {
+            fprintf(stdout, "tabz[%d] =% lf\n", j, tabz[j]);
+        }
 
+    *pnx = nx;
+    *pnz = nz;
+
+    fclose(fi);
+}
 
 /****************************************************************************/
 /* void LinearInterpolation2(double X, double Z, double &TX, double &TZ,
-                             CellType &Cell, bool &out, int order)
-                          
-   Purpose:
-        Computes thx and thz in X and Z values using a bilinear interpolation
-        interpolation of the array thetax(x,z) and thetaz(x,z)
-        
-   Input:
-       X, Z location of the interpolation
-       Cell element containing ID device
-       order 1 for first order kick map interpolation
-             2 for second order kick map interpolation  
-       
-   Output:
-       TX, TZ thetax and thetaz interpolated at X and Z
-       out true if interpolation out of table
-       
-   Return:
-       none
-       
-   Global variables:
-       none
-       
-   Specific functions:
+ CellType &Cell, bool &out, int order)
+
+ Purpose:
+ Computes thx and thz in X and Z values using a bilinear interpolation
+ interpolation of the array thetax(x,z) and thetaz(x,z)
+
+ Input:
+ X, Z location of the interpolation
+ Cell element containing ID device
+ order 1 for first order kick map interpolation
+ 2 for second order kick map interpolation
+
+ Output:
+ TX, TZ thetax and thetaz interpolated at X and Z
+ out true if interpolation out of table
+
+ Return:
+ none
+
+ Global variables:
+ none
+
+ Specific functions:
  
-   Comments:
-       Search for index could be speed up easily
+ Comments:
+ Search for index could be speed up easily
  
-****************************************************************************/
+ ****************************************************************************/
 template<typename T>
-void LinearInterpolation2(T &X, T &Z, T &TX, T &TZ, CellType &Cell,
-			  bool &out, int order)
-{
-  int            i, ix = 0, iz = 0;
-  T              T1, U, THX = 0.0, THZ = 0.0;
-  double         xstep = 0.0;
-  double         zstep = 0.0;
-  int            nx = 0, nz = 0;
-  InsertionType  *WITH;
-  
-  WITH = Cell.Elem.ID; nx = WITH->nx; nz = WITH->nz;
-  
-  xstep = WITH->tabx[1]-WITH->tabx[0]; /* increasing values */
-  zstep = WITH->tabz[0]-WITH->tabz[1]; /* decreasing values */
-  
-  if (traceID) printf("LinearInterpolation2: xstep = % f zstep = % f\n", xstep, zstep);
-  
-  /* test whether X and Z within the transverse map area */
-  if (X < WITH->tabx[0] || X > WITH->tabx[nx-1]) {
-    printf("LinearInterpolation2: X out of borders \n");
-    printf("X = % lf but tabx[0] = % lf and tabx[nx-1] = % lf\n",
-	   is_double<T>::cst(X), WITH->tabx[0], WITH->tabx[nx-1]);
-    out = true;
-    return;
-  }
-  
-  if (Z > WITH->tabz[0] || Z < WITH->tabz[nz-1]) {
-    printf("LinearInterpolation2: Z out of borders \n");
-    printf("Z = % lf but tabz[0] = % lf and tabz[nz-1] = % lf\n",
-	   is_double<T>::cst(Z),  WITH->tabz[0], WITH->tabz[nz-1]);
-    out = true;
-    return;
-  }
-  
-  out = false;
-  
-  /* looking for the index for X */
-  i = 0;
-  while (X >= WITH->tabx[i]  && i <= nx-1) {
-    i++;
-    if (traceID)
-      printf("%2d % lf % lf % lf \n",
-	     i, is_double<T>::cst(X), WITH->tabx[i], WITH->tabx[i+1]);
-  }
-  ix = i - 1;
-  
-  /* looking for the index for Z */
-  i = 0;
-  while (Z <= WITH->tabz[i] && i <= nz-1) {
-    i++;
-    if (traceID)
-      printf("%2d % lf % lf % lf \n",
-	     i, is_double<T>::cst(Z), WITH->tabz[i], WITH->tabz[i+1]);
-  }
-  iz = i - 1;
-  
-  if (traceID) printf("LinearInterpolation2: Indices are ix=%d and iz=%d\n", ix, iz);
-  
-  /** Bilinear Interpolation **/
-  U = (X - WITH->tabx[ix])/xstep; T1 = -(Z - WITH->tabz[iz])/zstep;
-  
-  if (order == 1) { // first order kick map interpolation
-    if (ix >= 0 && iz >= 0) {
-      THX = (1.0-U)*(1.0-T1)*WITH->thetax1[iz][ix]
-	    + U*(1.0-T1)*WITH->thetax1[iz][ix+1]
-	    + (1.0-U)*T1*WITH->thetax1[iz+1][ix]
-	    + U*T1*WITH->thetax1[iz+1][ix+1];
-      
-      THZ = (1.0-U)*(1.0-T1)*WITH->thetaz1[iz][ix]
-	    + U*(1.0-T1)*WITH->thetaz1[iz][ix+1]
-	    + (1.0-U)*T1*WITH->thetaz1[iz+1][ix]
-	    + U*T1*WITH->thetaz1[iz+1][ix+1];
-    }
-    
-    if (traceID) {
-      printf("X=% f interpolation : U= % lf T =% lf\n",
-	     is_double<T>::cst(X), is_double<T>::cst(U),
-	     is_double<T>::cst(T1));
-      printf("THX = % lf 11= % lf 12= %lf 21 = %lf 22 =%lf \n",
-	     is_double<T>::cst(THX),
-	     WITH->thetax1[iz][ix], WITH->thetax1[iz][ix+1],
-	     WITH->thetax1[iz+1][ix], WITH->thetax1[iz+1][ix+1]);
-      printf("Z=% f interpolation : U= % lf T =% lf\n",
-	     is_double<T>::cst(Z), is_double<T>::cst(U),
-	     is_double<T>::cst(T1));
-      printf("THZ = % lf 11= % lf 12= %lf 21 = %lf 22 =%lf \n",
-	     is_double<T>::cst(THZ),
-	     WITH->thetaz1[iz][ix], WITH->thetaz1[iz][ix+1],
-	     WITH->thetaz1[iz+1][ix],WITH->thetaz1[iz+1][ix+1]);
-    }
-  }
-  
-  if (order == 2) { // second order kick map interpolation
-    if (ix >= 0 && iz >= 0) {
-      THX = (1.0-U)*(1.0-T1)*WITH->thetax[iz][ix]
-	    + U*(1.0-T1)*WITH->thetax[iz][ix+1]
-	    + (1.0-U)*T1*WITH->thetax[iz+1][ix]
-	    + U*T1*WITH->thetax[iz+1][ix+1];
-      
-      THZ = (1.0-U)*(1.0-T1)*WITH->thetaz[iz][ix]
-	    + U*(1.0-T1)*WITH->thetaz[iz][ix+1]
-	    + (1.0-U)*T1*WITH->thetaz[iz+1][ix]
-	    + U*T1*WITH->thetaz[iz+1][ix+1];
+void LinearInterpolation2(T &X, T &Z, T &TX, T &TZ, CellType &Cell, bool &out,
+        int order) {
+    int i, ix = 0, iz = 0;
+    T T1, U, THX = 0.0, THZ = 0.0;
+    double xstep = 0.0;
+    double zstep = 0.0;
+    int nx = 0, nz = 0;
+    InsertionType *WITH;
+    traceID = false;
+
+    WITH = Cell.Elem.ID;
+
+    if (order == 1) {
+        nx = WITH->nx1;
+        nz = WITH->nz1;
+
+        xstep = WITH->tabx1[1] - WITH->tabx1[0]; /* increasing values */
+        zstep = WITH->tabz1[0] - WITH->tabz1[1]; /* decreasing values */
+
+        if (traceID)
+            printf("LinearInterpolation2: xstep = % f zstep = % f\n", xstep,
+                    zstep);
+
+        /* test whether X and Z within the transverse map area */
+        if (X < WITH->tabx1[0] || X > WITH->tabx1[nx - 1]) {
+            printf("LinearInterpolation2: X out of borders \n");
+            printf("X = % lf but tabx[0] = % lf and tabx[nx-1] = % lf\n",
+                    is_double<T>::cst(X), WITH->tabx1[0], WITH->tabx1[nx - 1]);
+            out = true;
+            return;
+        }
+
+        if (Z > WITH->tabz1[0] || Z < WITH->tabz1[nz - 1]) {
+            printf("LinearInterpolation2: Z out of borders \n");
+            printf("Z = % lf but tabz[0] = % lf and tabz[nz-1] = % lf\n",
+                    is_double<T>::cst(Z), WITH->tabz1[0], WITH->tabz1[nz - 1]);
+            out = true;
+            return;
+        }
+
+        out = false;
+
+        /* looking for the index for X */
+        i = 0;
+        while (X >= WITH->tabx1[i] && i <= nx - 1) {
+            i++;
+            if (traceID)
+                printf("%2d % lf % lf % lf \n", i, is_double<T>::cst(X),
+                        WITH->tabx1[i], WITH->tabx1[i + 1]);
+        }
+        ix = i - 1;
+
+        /* looking for the index for Z */
+        i = 0;
+        while (Z <= WITH->tabz1[i] && i <= nz - 1) {
+            i++;
+            if (traceID)
+                printf("%2d % lf % lf % lf \n", i, is_double<T>::cst(Z),
+                        WITH->tabz1[i], WITH->tabz1[i + 1]);
+        }
+        iz = i - 1;
+
+        if (traceID)
+            printf("LinearInterpolation2: Indices are ix=%d and iz=%d\n", ix,
+                    iz);
+
+        /** Bilinear Interpolation **/
+        U = (X - WITH->tabx1[ix]) / xstep;
+        T1 = -(Z - WITH->tabz1[iz]) / zstep;
+
+        // first order kick map interpolation
+        if (ix >= 0 && iz >= 0) {
+            THX = (1.0 - U) * (1.0 - T1) * WITH->thetax1[iz][ix] + U * (1.0
+                    - T1) * WITH->thetax1[iz][ix + 1] + (1.0 - U) * T1
+                    * WITH->thetax1[iz + 1][ix] + U * T1
+                    * WITH->thetax1[iz + 1][ix + 1];
+
+            THZ = (1.0 - U) * (1.0 - T1) * WITH->thetaz1[iz][ix] + U * (1.0
+                    - T1) * WITH->thetaz1[iz][ix + 1] + (1.0 - U) * T1
+                    * WITH->thetaz1[iz + 1][ix] + U * T1
+                    * WITH->thetaz1[iz + 1][ix + 1];
+        }
+
+        if (traceID) {
+            printf("X=% f interpolation : U= % lf T =% lf\n",
+                    is_double<T>::cst(X), is_double<T>::cst(U),
+                    is_double<T>::cst(T1));
+            printf("THX = % lf 11= % lf 12= %lf 21 = %lf 22 =%lf \n",
+                    is_double<T>::cst(THX), WITH->thetax1[iz][ix],
+                    WITH->thetax1[iz][ix + 1], WITH->thetax1[iz + 1][ix],
+                    WITH->thetax1[iz + 1][ix + 1]);
+            printf("Z=% f interpolation : U= % lf T =% lf\n",
+                    is_double<T>::cst(Z), is_double<T>::cst(U),
+                    is_double<T>::cst(T1));
+            printf("THZ = % lf 11= % lf 12= %lf 21 = %lf 22 =%lf \n",
+                    is_double<T>::cst(THZ), WITH->thetaz1[iz][ix],
+                    WITH->thetaz1[iz][ix + 1], WITH->thetaz1[iz + 1][ix],
+                    WITH->thetaz1[iz + 1][ix + 1]);
+        }
+
+        TX = THX;
+        TZ = THZ;
     }
-    
-    if (traceID) {
-      printf("LSN X=% f interpolation : U= % lf T =% lf\n",
-	     is_double<T>::cst(X), is_double<T>::cst(U),
-	     is_double<T>::cst(T1));
-      printf("THX = % lf 11= % lf 12= %lf 21 = %lf 22 =%lf \n",
-	     is_double<T>::cst(THX),
-	     WITH->thetax[iz][ix], WITH->thetax[iz][ix+1],
-	     WITH->thetax[iz+1][ix], WITH->thetax[iz+1][ix+1]);
-      printf("Z=% f interpolation : U= % lf T =% lf\n",
-	     is_double<T>::cst(Z), is_double<T>::cst(U),
-	     is_double<T>::cst(T1));
-      printf("THZ = % lf 11= % lf 12= %lf 21 = %lf 22 =%lf \n",
-	     is_double<T>::cst(THZ),
-	     WITH->thetaz[iz][ix], WITH->thetaz[iz][ix+1],
-	     WITH->thetaz[iz+1][ix], WITH->thetaz[iz+1][ix+1]);
+
+    if (order == 2) {
+        nx = WITH->nx2;
+        nz = WITH->nz2;
+        xstep = WITH->tabx2[1] - WITH->tabx2[0]; /* increasing values */
+        zstep = WITH->tabz2[0] - WITH->tabz2[1]; /* decreasing values */
+
+        if (traceID)
+            printf("LinearInterpolation2: xstep = % f zstep = % f\n", xstep,
+                    zstep);
+
+        /* test whether X and Z within the transverse map area */
+        if (X < WITH->tabx2[0] || X > WITH->tabx2[nx - 1]) {
+            printf("LinearInterpolation2: X out of borders \n");
+            printf("X = % lf but tabx[0] = % lf and tabx[nx-1] = % lf\n",
+                    is_double<T>::cst(X), WITH->tabx2[0], WITH->tabx2[nx - 1]);
+            out = true;
+            return;
+        }
+
+        if (Z > WITH->tabz2[0] || Z < WITH->tabz2[nz - 1]) {
+            printf("LinearInterpolation2: Z out of borders \n");
+            printf("Z = % lf but tabz[0] = % lf and tabz[nz-1] = % lf\n",
+                    is_double<T>::cst(Z), WITH->tabz2[0], WITH->tabz2[nz - 1]);
+            out = true;
+            return;
+        }
+        /* looking for the index for X */
+        i = 0;
+        while (X >= WITH->tabx2[i] && i <= nx - 1) {
+            i++;
+            if (traceID)
+                printf("%2d % lf % lf % lf \n", i, is_double<T>::cst(X),
+                        WITH->tabx2[i], WITH->tabx2[i + 1]);
+        }
+        ix = i - 1;
+
+        /* looking for the index for Z */
+        i = 0;
+        while (Z <= WITH->tabz2[i] && i <= nz - 1) {
+            i++;
+            if (traceID)
+                printf("%2d % lf % lf % lf \n", i, is_double<T>::cst(Z),
+                        WITH->tabz2[i], WITH->tabz2[i + 1]);
+        }
+        iz = i - 1;
+
+        if (traceID)
+            printf("LinearInterpolation2: Indices are ix=%d and iz=%d\n", ix,
+                    iz);
+
+        /** Bilinear Interpolation **/
+        U = (X - WITH->tabx2[ix]) / xstep;
+        T1 = -(Z - WITH->tabz2[iz]) / zstep;
+
+        // second order kick map interpolation
+        if (ix >= 0 && iz >= 0) {
+            THX = (1.0 - U) * (1.0 - T1) * WITH->thetax2[iz][ix] + U * (1.0
+                    - T1) * WITH->thetax2[iz][ix + 1] + (1.0 - U) * T1
+                    * WITH->thetax2[iz + 1][ix] + U * T1
+                    * WITH->thetax2[iz + 1][ix + 1];
+
+            THZ = (1.0 - U) * (1.0 - T1) * WITH->thetaz2[iz][ix] + U * (1.0
+                    - T1) * WITH->thetaz2[iz][ix + 1] + (1.0 - U) * T1
+                    * WITH->thetaz2[iz + 1][ix] + U * T1
+                    * WITH->thetaz2[iz + 1][ix + 1];
+        }
+
+        if (traceID) {
+            printf("LSN X=% f interpolation : U= % lf T =% lf\n",
+                    is_double<T>::cst(X), is_double<T>::cst(U),
+                    is_double<T>::cst(T1));
+            printf("THX = % lf 11= % lf 12= %lf 21 = %lf 22 =%lf \n",
+                    is_double<T>::cst(THX), WITH->thetax2[iz][ix],
+                    WITH->thetax2[iz][ix + 1], WITH->thetax2[iz + 1][ix],
+                    WITH->thetax2[iz + 1][ix + 1]);
+            printf("Z=% f interpolation : U= % lf T =% lf\n",
+                    is_double<T>::cst(Z), is_double<T>::cst(U),
+                    is_double<T>::cst(T1));
+            printf("THZ = % lf 11= % lf 12= %lf 21 = %lf 22 =%lf \n",
+                    is_double<T>::cst(THZ), WITH->thetaz2[iz][ix],
+                    WITH->thetaz2[iz][ix + 1], WITH->thetaz2[iz + 1][ix],
+                    WITH->thetaz2[iz + 1][ix + 1]);
+        }
+
+        TX = THX;
+        TZ = THZ;
     }
-  }
-  TX = THX; TZ = THZ;
 }
 
-
 /****************************************************************************/
 /* void SplineInterpolation2(double X, double Z, double &TX, double &TZ,
-                             CellType &Cell, bool &out)
+ CellType &Cell, bool &out, int order)
  
-   Purpose:
-        Computes thx and thz in X and Z values using a bilinear interpolation
-        interpolation of the array thetax(x, z) and thetaz(x, z)
+ Purpose:
+ Computes thx and thz in X and Z values using a bilinear interpolation
+ interpolation of the array thetax(x, z) and thetaz(x, z)
  
-   Input:
-       X, Z location of the interpolation
-       Cell element containing ID device
+ Input:
+ X, Z location of the interpolation
+ Cell element containing ID device
+ Order 1 or 2 for first or second order maps
  
-   Output:
-       TX, TZ thetax and thetaz interpolated at X and Z
-       out true if interpolation out of table
+ Output:
+ TX, TZ thetax and thetaz interpolated at X and Z
+ out true if interpolation out of table
  
-   Return:
-       none
+ Return:
+ none
  
-   Global variables:
-       none
+ Global variables:
+ none
  
-   Specific functions:
+ Specific functions:
  
-   Comments:
-       none
+ Comments:
+ 4 November 2010 - Add order and separate 1st and second order tables
  
-****************************************************************************/
+ ****************************************************************************/
 template<typename T>
-void SplineInterpolation2(T &X, T &Z, T &thetax, T &thetaz,
-			  CellType &Cell, bool &out)
-{
-    int            nx, nz;
-    InsertionType  *WITH;
-//    int kx, kz;
+void SplineInterpolation2(T &X, T &Z, T &thetax, T &thetaz, CellType &Cell,
+        bool &out, int order) {
+    int nx, nz;
+    InsertionType *WITH;
+    double *tabx; /* spacing in H-plane */
+    double *tabz; /* spacing in V-plane */
 
-    WITH = Cell.Elem.ID; nx = WITH->nx; nz = WITH->nz;
+    WITH = Cell.Elem.ID;
+    if (order == 1) {
+        nx = WITH->nx1;
+        nz = WITH->nz1;
+        tabx = WITH->tabx1;
+        tabz = WITH->tabz1;
+    } else {
+        nx = WITH->nx2;
+        nz = WITH->nz2;
+        tabx = WITH->tabx2;
+        tabz = WITH->tabz2;
+    }
 
     /* test whether X and Z within the transverse map area */
-    if (X < WITH->tabx[0] || X > WITH->tabx[nx-1] ||
-	Z > WITH->tabz[0] || Z < WITH->tabz[nz-1]) {
-        printf("SplineInterpolation2: out of borders in element s= %4.2f %*s\n",
-	       Cell.S, 5, Cell.Elem.PName);
+    if (X < tabx[0] || X > tabx[nx - 1] || Z > tabz[0] || Z < tabz[nz - 1]) {
+        printf(
+                "SplineInterpolation2: out of borders in element s= %4.2f %*s\n",
+                Cell.S, 5, Cell.Elem.PName);
         printf("X = % lf but tabx[0] = % lf and tabx[nx-1] = % lf\n",
-	       is_double<T>::cst(X), WITH->tabx[0], WITH->tabx[nx-1]);
+                is_double<T>::cst(X), tabx[0], tabx[nx - 1]);
         printf("Z = % lf but tabz[0] = % lf and tabz[nz-1] = % lf\n",
-	       is_double<T>::cst(Z), WITH->tabz[0], WITH->tabz[nz-1]);
+                is_double<T>::cst(Z), tabz[0], tabz[nz - 1]);
         out = true;
         return;
     }
 
     out = false;
-    // H-plane
-    splin2(WITH->tab2-1, WITH->tab1-1, WITH->tx, WITH->f2x, nz, nx,
-	   Z, X, thetax);
-/*    if (fabs(temp) > ZERO_RADIA)
-      *thetax = (double) temp;
-    else
-      *thetax = 0.0;*/
-    // V-plane
-    splin2(WITH->tab2-1, WITH->tab1-1, WITH->tz, WITH->f2z, nz, nx,
-	   Z, X, thetaz);
-/*    if (fabs(temp) > ZERO_RADIA)
-      *thetaz = (double) temp;
-    else
-      *thetaz = 0.0;*/
-
-/*    FILE * fic0;
-    char *fic="fit.out";
-    fic0 = fopen(fic, "w");
-    for (kz = 1; kz <= nz; kz++) {
-      for (kx = 1; kx <= nx; kx++)
-	fprintf(fic0, "% 12.3e", tz[kz][kx]);
-      fprintf(fic0, "\n");
+    if (order == 1) {
+        // H-plane
+        splin2(WITH->TabzOrd1 - 1, WITH->TabxOrd1 - 1, WITH->tx1, WITH->f2x1, nz, nx,
+                Z, X, thetax);
+        /*    if (fabs(temp) > ZERO_RADIA)
+         *thetax = (double) temp;
+         else
+         *thetax = 0.0;*/
+        // V-plane
+        splin2(WITH->TabzOrd1 - 1, WITH->TabxOrd1 - 1, WITH->tz1, WITH->f2z1, nz, nx,
+                Z, X, thetaz);
+        /*    if (fabs(temp) > ZERO_RADIA)
+         *thetaz = (double) temp;
+         else
+         *thetaz = 0.0;*/
+    }
+
+    if (order == 2) {
+        // H-plane
+        splin2(WITH->TabzOrd2 - 1, WITH->TabxOrd2 - 1, WITH->tx2, WITH->f2x2, nz, nx,
+                Z, X, thetax);
+        /*    if (fabs(temp) > ZERO_RADIA)
+         *thetax = (double) temp;
+         else
+         *thetax = 0.0;*/
+        // V-plane
+        splin2(WITH->TabzOrd2 - 1, WITH->TabxOrd2 - 1, WITH->tz2, WITH->f2z2, nz, nx,
+                Z, X, thetaz);
+        /*    if (fabs(temp) > ZERO_RADIA)
+         *thetaz = (double) temp;
+         else
+         *thetaz = 0.0;*/
     }
-    fclose(fic0);*/
 }
 
+void Matrices4Spline(InsertionType *WITH, int Order) {
+    int kx, kz;
 
-void Matrices4Spline(InsertionType *WITH)
-{
-  int kx, kz;
+    if (Order == 1) {
+        for (kx = 0; kx < WITH->nx1; kx++) {
+            WITH->TabxOrd1[kx] = (float) WITH->tabx1[kx];
+        }
+
+        /** reordering: it has to be in increasing order */
+        for (kz = 0; kz < WITH->nz1; kz++) {
+            WITH->TabzOrd1[kz] = (float) WITH->tabz1[WITH->nz1 - kz - 1];
+        }
+
+        for (kx = 0; kx < WITH->nx1; kx++) {
+            for (kz = 0; kz < WITH-> nz1; kz++) {
+                WITH->tx1[kz + 1][kx + 1] = (float) (WITH->thetax1[WITH->nz1
+                        - kz - 1][kx]);
+                WITH->tz1[kz + 1][kx + 1] = (float) (WITH->thetaz1[WITH->nz1
+                        - kz - 1][kx]);
+            }
+        }
+        // computes second derivative matrices
+        splie2(WITH->TabzOrd1 - 1, WITH->TabxOrd1 - 1, WITH->tx1, WITH->nz1,
+                WITH->nx1, WITH->f2x1);
+        splie2(WITH->TabzOrd1 - 1, WITH->TabxOrd1 - 1, WITH->tz1, WITH->nz1,
+                WITH->nx1, WITH->f2z1);
+    }
 
-  for (kx = 0; kx < WITH->nx; kx++) {
-    WITH->tab1[kx] = (float) WITH->tabx[kx];
-  }
+    if (Order == 2) {
+        for (kx = 0; kx < WITH->nx2; kx++) {
+            WITH->TabxOrd2[kx] = (float) WITH->tabx2[kx];
+        }
 
-  /** reordering: it has to be in increasing order */
-  for (kz = 0; kz < WITH->nz; kz++) {
-    WITH->tab2[kz] = (float) WITH->tabz[WITH->nz-kz-1];
-  }
+        /** reordering: it has to be in increasing order */
+        for (kz = 0; kz < WITH->nz2; kz++) {
+            WITH->TabzOrd2[kz] = (float) WITH->tabz2[WITH->nz2 - kz - 1];
+        }
 
-  for (kx = 0; kx < WITH->nx; kx++) {
-    for (kz = 0; kz <WITH-> nz; kz++) {
-      WITH->tx[kz+1][kx+1] = (float) (WITH->thetax[WITH->nz-kz-1][kx]);
-      WITH->tz[kz+1][kx+1] = (float) (WITH->thetaz[WITH->nz-kz-1][kx]);
+        for (kx = 0; kx < WITH->nx2; kx++) {
+            for (kz = 0; kz < WITH-> nz2; kz++) {
+                WITH->tx2[kz + 1][kx + 1] = (float) (WITH->thetax2[WITH->nz2
+                        - kz - 1][kx]);
+                WITH->tz2[kz + 1][kx + 1] = (float) (WITH->thetaz2[WITH->nz2
+                        - kz - 1][kx]);
+            }
+        }
+        // computes second derivative matrices
+        splie2(WITH->TabzOrd2 - 1, WITH->TabxOrd2 - 1, WITH->tx2, WITH->nz2,
+                WITH->nx2, WITH->f2x2);
+        splie2(WITH->TabzOrd2 - 1, WITH->TabxOrd2 - 1, WITH->tz2, WITH->nz2,
+                WITH->nx2, WITH->f2z2);
     }
-  }
 
-  // computes second derivative matrices
-  splie2(WITH->tab2-1,WITH->tab1-1,WITH->tx,WITH->nz,WITH->nx,WITH->f2x);
-  splie2(WITH->tab2-1,WITH->tab1-1,WITH->tz,WITH->nz,WITH->nx,WITH->f2z);
 }
diff --git a/tracy/tracy/src/rdmfile.cc b/tracy/tracy/src/rdmfile.cc
index d7b03621bc57b0d66923d110d5e508e817bb3606..b3391c0e966ebcfb889dfc75320bee36bbe569b8 100644
--- a/tracy/tracy/src/rdmfile.cc
+++ b/tracy/tracy/src/rdmfile.cc
@@ -1,347 +1,382 @@
-/* Tracy-2
-
-   J. Bengtsson, CBP, LBL      1990 - 1994   Pascal version
-                 SLS, PSI      1995 - 1997
-   M. Boege      SLS, PSI      1998          C translation
-   L. Nadolski   SOLEIL        2002          Link to NAFF, Radia field maps
-   J. Bengtsson  NSLS-II, BNL  2004 -        
-
-
-   To generate a lattice flat file.
-
-   Type codes:
-
-     marker     -1
-     drift	 0
-     multipole   1
-     cavity      2
-     thin kick   3
-     wiggler     4
-
-   Integration methods:
-
-     linear, matrix style (obsolete)              0
-     2nd order symplectic integrator (obsolete)   2
-     4th order symplectic integrator              4
-
-   Format:
-
-     name, family no, kid no, element no
-     type code, integration method, no of integration steps
-     apertures: xmin, xmax, ymin, ymax
-
-   The following lines follows depending on element type.
-
-     type
-
-     drift:	 L
-
-     multipole:  hor., ver. displ., roll angle (design), roll angle (error)
-                 L, 1/rho, entrance angle, exit angle
-		 no of nonzero multipole coeff., n design
-		 n, b , a
-		     n   n
-		     .
-		     .
-		     .
-
-     wiggler:    L [m], lambda [m]
-                 no of harmonics
-                 harm no, kxV [1/m], BoBrhoV [1/m], kxH, BoBrhoH, phi
-                    ...
-
-     cavity:	 cavity voltage/beam energy [eV], omega/c, beam energy [eV]
-
-     thin kick:	 hor., ver. displacement, roll angle (total)
-		 no of nonzero multipole coeff.
-		 n, b , a
-		     n   n
-		     .
-		     .
-		     .
-
-     kick_map:   scale order <file name>
-
-*/
-
-
-#define snamelen   10
-
-// numerical type codes
-#define marker_   -1
-#define drift_     0
-#define mpole_     1
-#define cavity_    2
-#define thinkick_  3
-#define wiggler_   4
-#define insertion_ 6
-
-
-ifstream  inf;
-
-
-void get_kind(const int kind, elemtype &Elem)
-{
-
-  switch (kind) {
-  case marker_:
-    Elem.Pkind = PartsKind(marker);
-    break;
-  case drift_:
-    Elem.Pkind = PartsKind(drift);
-    Drift_Alloc(&Elem);
-    break;
-  case mpole_:
-    Elem.Pkind = PartsKind(Mpole);
-    Mpole_Alloc(&Elem);
-    Elem.M->Pthick = pthicktype(thick);
-    break;
-  case cavity_:
-    Elem.Pkind = PartsKind(Cavity);
-    Cav_Alloc(&Elem);
-    break;
-  case thinkick_:
-    Elem.Pkind = PartsKind(Mpole);
-    Mpole_Alloc(&Elem);
-    Elem.M->Pthick = pthicktype(thin);
-    break;
-  case wiggler_:
-    Elem.Pkind = PartsKind(Wigl);
-    Wiggler_Alloc(&Elem);
-    break;
-  case insertion_:
-    Elem.Pkind = PartsKind(Insertion);
-    Insertion_Alloc(&Elem);
-    break;
-  default:
-    cout << "get_kind: unknown type " << kind << " " << Elem.PName << endl;
-    exit_(1);
-    break;
-  }
-}
-
-
-void rdmfile(const char *mfile_dat)
-{
-  char      line[max_str], file_name[max_str];
-  int       j, nmpole, kind, method, n;
-  long int  i;
-  double    dTerror;
-
-  bool  prt = false;
-
-  cout << endl;
-  cout << "reading machine file: " << mfile_dat << endl;
-
-  file_rd(inf, mfile_dat);
-
-  while (inf.getline(line, max_str) != NULL) {
-    if (prt) printf("%s\n", line);
-    sscanf(line, "%*s %*d %*d %ld", &i);
-
-    Cell[i].dS[X_] = 0.0; Cell[i].dS[Y_] = 0.0;
-    Cell[i].dT[X_] = 1.0; Cell[i].dT[Y_] = 0.0;
-
-    sscanf(line, "%s %ld %ld", Cell[i].Elem.PName, &Cell[i].Fnum, &Cell[i].Knum);
-
-    if (Cell[i].Knum == 1) {
-      strcpy(ElemFam[Cell[i].Fnum-1].ElemF.PName, Cell[i].Elem.PName);
-      globval.Elem_nFam = max(Cell[i].Fnum, globval.Elem_nFam);
-    }
-
-    if (i > 0) {
-      ElemFam[Cell[i].Fnum-1].KidList[Cell[i].Knum-1] = i;
-      ElemFam[Cell[i].Fnum-1].nKid =
-	max(Cell[i].Knum, ElemFam[Cell[i].Fnum-1].nKid);
-    }
-
-    inf.getline(line, max_str);
-    if (prt) printf("%s\n", line);
-    sscanf(line, "%d %d %d", &kind, &method, &n);
-    get_kind(kind, Cell[i].Elem);
-    if (i > 0)
-      ElemFam[Cell[i].Fnum-1].ElemF.Pkind = Cell[i].Elem.Pkind;
-
-    inf.getline(line, max_str);
-    if (prt) printf("%s\n", line);
-    sscanf(line, "%lf %lf %lf %lf",
-	   &Cell[i].maxampl[X_][0], &Cell[i].maxampl[X_][1],
-	   &Cell[i].maxampl[Y_][0], &Cell[i].maxampl[Y_][1]);
-
-    Cell[i].Elem.PL = 0.0;
-
-    switch (Cell[i].Elem.Pkind) {
-    case undef:
-      cout << "rdmfile: unknown type " << i << endl;
-      exit_(1);
-      break;
-    case marker:
-      break;
-    case drift:
-      inf.getline(line, max_str);
-      if (prt) printf("%s\n", line);
-      sscanf(line, "%lf", &Cell[i].Elem.PL);
-      break;
-    case Cavity:
-      inf.getline(line, max_str);
-      if (prt) printf("%s\n", line);
-      sscanf(line, "%lf %lf %d %lf",
-	     &Cell[i].Elem.C->Pvolt, &Cell[i].Elem.C->Pfreq,
-	     &Cell[i].Elem.C->Ph, &globval.Energy);
-      globval.Energy *= 1e-9;
-      Cell[i].Elem.C->Pvolt *= globval.Energy*1e9;
-      Cell[i].Elem.C->Pfreq *= c0/(2.0*M_PI);
-     break;
-    case Mpole:
-      Cell[i].Elem.M->Pmethod = method; Cell[i].Elem.M->PN = n;
-
-      if (Cell[i].Elem.M->Pthick == thick) {
-	inf.getline(line, max_str);
-	if (prt) printf("%s\n", line);
-	sscanf(line, "%lf %lf %lf %lf",
-	       &Cell[i].dS[X_], &Cell[i].dS[Y_],
-	       &Cell[i].Elem.M->PdTpar, &dTerror);
-	Cell[i].dT[X_] = cos(dtor(dTerror+Cell[i].Elem.M->PdTpar));
-	Cell[i].dT[Y_] = sin(dtor(dTerror+Cell[i].Elem.M->PdTpar));
-
-	inf.getline(line, max_str);
-	if (prt) printf("%s\n", line);
-	sscanf(line, "%lf %lf %lf %lf %lf",
-	       &Cell[i].Elem.PL, &Cell[i].Elem.M->Pirho,
-	       &Cell[i].Elem.M->PTx1, &Cell[i].Elem.M->PTx2,
-	       &Cell[i].Elem.M->Pgap);
-	if (Cell[i].Elem.M->Pirho != 0.0) Cell[i].Elem.M->Porder = 1;
-      } else {
-	inf.getline(line, max_str);
-	if (prt) printf("%s\n", line);
-	sscanf(line, "%lf %lf %lf",
-	       &Cell[i].dS[X_], &Cell[i].dS[Y_], &dTerror); 
-	Cell[i].dT[X_] = cos(dtor(dTerror));
-	Cell[i].dT[Y_] = sin(dtor(dTerror));
-      }
-
-      Cell[i].Elem.M->Pc0 = sin(Cell[i].Elem.PL*Cell[i].Elem.M->Pirho/2.0);
-      Cell[i].Elem.M->Pc1 = cos(dtor(Cell[i].Elem.M->PdTpar))
-	                    *Cell[i].Elem.M->Pc0;
-      Cell[i].Elem.M->Ps1 = sin(dtor(Cell[i].Elem.M->PdTpar))
-	                    *Cell[i].Elem.M->Pc0;
-
-      inf.getline(line, max_str);
-      if (prt) printf("%s\n", line);
-      sscanf(line, "%d %d", &nmpole, &Cell[i].Elem.M->n_design);
-      for (j = 1; j <= nmpole; j++) {
-	inf.getline(line, max_str);
-	if (prt) printf("%s\n", line);
-	sscanf(line, "%d", &n);
-	sscanf(line, "%*d %lf %lf",
-	       &Cell[i].Elem.M->PB[HOMmax+n], &Cell[i].Elem.M->PB[HOMmax-n]);
-	Cell[i].Elem.M->PBpar[HOMmax+n] = Cell[i].Elem.M->PB[HOMmax+n];
-	Cell[i].Elem.M->PBpar[HOMmax-n] = Cell[i].Elem.M->PB[HOMmax-n];
-	Cell[i].Elem.M->Porder = max(n, Cell[i].Elem.M->Porder);
-      }
-      break;
-    case Wigl:
-      Cell[i].Elem.W->Pmethod = method; Cell[i].Elem.W->PN = n;
-
-      inf.getline(line, max_str);
-      if (prt) printf("%s\n", line);
-      sscanf(line, "%lf %lf", &Cell[i].Elem.PL, &Cell[i].Elem.W->lambda);
-
-      inf.getline(line, max_str);
-      if (prt) printf("%s\n", line);
-      sscanf(line, "%d", &Cell[i].Elem.W->n_harm);
-
-      if (Cell[i].Knum == 1) Wiggler_Alloc(&ElemFam[Cell[i].Fnum-1].ElemF);
-      for (j = 0; j < Cell[i].Elem.W->n_harm; j++) {
-	inf.getline(line, max_str);
-	if (prt) printf("%s\n", line);
-	sscanf(line, "%d %lf %lf %lf %lf %lf", &Cell[i].Elem.W->harm[j],
-	       &Cell[i].Elem.W->kxV[j], &Cell[i].Elem.W->BoBrhoV[j],
-	       &Cell[i].Elem.W->kxH[j], &Cell[i].Elem.W->BoBrhoH[j],
-	       &Cell[i].Elem.W->phi[j]);
-	ElemFam[Cell[i].Fnum-1].ElemF.W->BoBrhoV[j]
-	  = Cell[i].Elem.W->BoBrhoV[j];
-	ElemFam[Cell[i].Fnum-1].ElemF.W->BoBrhoH[j]
-	  = Cell[i].Elem.W->BoBrhoH[j];
-      }
-      break;
-    case Insertion:
-      Cell[i].Elem.ID->Pmethod = method; Cell[i].Elem.ID->PN = n;
-
-      inf.getline(line, max_str);
-      if (prt) printf("%s\n", line);
-      sscanf(line, "%lf %d %s", &Cell[i].Elem.ID->scaling, &n, file_name);
-
-      if (n == 1) {
-	Cell[i].Elem.ID->firstorder = true;
-	Cell[i].Elem.ID->secondorder = false;
-
-	strcpy(Cell[i].Elem.ID->fname1, file_name);
-	Read_IDfile(Cell[i].Elem.ID->fname1, &Cell[i].Elem.PL,
-		    &Cell[i].Elem.ID->nx, &Cell[i].Elem.ID->nz,
-		    Cell[i].Elem.ID->tabx, Cell[i].Elem.ID->tabz,
-		    Cell[i].Elem.ID->thetax1, Cell[i].Elem.ID->thetaz1);
-      } else if (n == 2) {
-	Cell[i].Elem.ID->firstorder = false;
-	Cell[i].Elem.ID->secondorder = true;
-
-	strcpy(Cell[i].Elem.ID->fname2, file_name);
-	Read_IDfile(Cell[i].Elem.ID->fname2, &Cell[i].Elem.PL,
-		    &Cell[i].Elem.ID->nx, &Cell[i].Elem.ID->nz,
-		    Cell[i].Elem.ID->tabx, Cell[i].Elem.ID->tabz,
-		    Cell[i].Elem.ID->thetax, Cell[i].Elem.ID->thetaz);
-      } else {
-	cout << "rdmfile: undef order " << n << endl;
-	exit_(1);
-      }
-
-      if (Cell[i].Elem.ID->Pmethod == 1)
-	Cell[i].Elem.ID->linear = true;
-      else
-	Cell[i].Elem.ID->linear = false;
-
-      if (!Cell[i].Elem.ID->linear) {
-	Cell[i].Elem.ID->tx = dmatrix(1, Cell[i].Elem.ID->nz,
-				      1, Cell[i].Elem.ID->nx);
-	Cell[i].Elem.ID->tz = dmatrix(1, Cell[i].Elem.ID->nz,
-				      1, Cell[i].Elem.ID->nx);
-	Cell[i].Elem.ID->tab1 = (double *)malloc((Cell[i].Elem.ID->nx)
-						 *sizeof(double));
-	Cell[i].Elem.ID->tab2 = (double *)malloc((Cell[i].Elem.ID->nz)
-						 *sizeof(double));
-	Cell[i].Elem.ID->f2x = dmatrix(1, Cell[i].Elem.ID->nz,
-				       1, Cell[i].Elem.ID->nx);
-	Cell[i].Elem.ID->f2z = dmatrix(1, Cell[i].Elem.ID->nz,
-				       1, Cell[i].Elem.ID->nx);
-	Matrices4Spline(Cell[i].Elem.ID);
-      }
-
-/*      free_matrix(tx, 1, nz, 1, nx); free_matrix(tz, 1, nz, 1, nx);
-      free(tab1); free(tab2);
-      free_matrix(f2x, 1, nz, 1, nx); free_matrix(f2z, 1, nz, 1, nx); */
-      break;
-    case FieldMap:
-      break;
-    default:
-      cout << "rdmfile: unknown type" << endl;
-      exit_(1);
-      break;
-    }
-
-    if (i == 0)
-      Cell[i].S = 0.0;
-    else
-      Cell[i].S = Cell[i-1].S + Cell[i].Elem.PL;
-  }
-  
-  globval.Cell_nLoc = i;
- 
-  globval.dPcommon = 1e-8; globval.CODeps = 1e-14; globval.CODimax = 40;
-
-  SI_init();
-
-  cout << endl;
-  cout << "rdmfile: read " << globval.Cell_nLoc << " elements" << endl;
-
-  inf.close();
-}
+/* Tracy-2
+
+   J. Bengtsson, CBP, LBL      1990 - 1994   Pascal version
+                 SLS, PSI      1995 - 1997
+   M. Boege      SLS, PSI      1998          C translation
+   L. Nadolski   SOLEIL        2002          Link to NAFF, Radia field maps
+   J. Bengtsson  NSLS-II, BNL  2004 -        
+
+
+   To generate a lattice flat file.
+
+   Type codes:
+
+     marker     -1
+     drift	 0
+     multipole   1
+     cavity      2
+     thin kick   3
+     wiggler     4
+
+   Integration methods:
+
+     linear, matrix style (obsolete)              0
+     2nd order symplectic integrator (obsolete)   2
+     4th order symplectic integrator              4
+
+   Format:
+
+     name, family no, kid no, element no
+     type code, integration method, no of integration steps
+     apertures: xmin, xmax, ymin, ymax
+
+   The following lines follows depending on element type.
+
+     type
+
+     drift:	 L
+
+     multipole:  hor., ver. displ., roll angle (design), roll angle (error)
+                 L, 1/rho, entrance angle, exit angle
+		 no of nonzero multipole coeff., n design
+		 n, b , a
+		     n   n
+		     .
+		     .
+		     .
+
+     wiggler:    L [m], lambda [m]
+                 no of harmonics
+                 harm no, kxV [1/m], BoBrhoV [1/m], kxH, BoBrhoH, phi
+                    ...
+
+     cavity:	 cavity voltage/beam energy [eV], omega/c, beam energy [eV]
+
+     thin kick:	 hor., ver. displacement, roll angle (total)
+		 no of nonzero multipole coeff.
+		 n, b , a
+		     n   n
+		     .
+		     .
+		     .
+
+     kick_map:   scale order <file name>
+
+*/
+
+
+#define snamelen   10
+
+// numerical type codes
+#define marker_   -1
+#define drift_     0
+#define mpole_     1
+#define cavity_    2
+#define thinkick_  3
+#define wiggler_   4
+#define insertion_ 6
+
+
+ifstream  inf;
+
+
+void get_kind(const int kind, elemtype &Elem)
+{
+
+  switch (kind) {
+  case marker_:
+    Elem.Pkind = PartsKind(marker);
+    break;
+  case drift_:
+    Elem.Pkind = PartsKind(drift);
+    Drift_Alloc(&Elem);
+    break;
+  case mpole_:
+    Elem.Pkind = PartsKind(Mpole);
+    Mpole_Alloc(&Elem);
+    Elem.M->Pthick = pthicktype(thick);
+    break;
+  case cavity_:
+    Elem.Pkind = PartsKind(Cavity);
+    Cav_Alloc(&Elem);
+    break;
+  case thinkick_:
+    Elem.Pkind = PartsKind(Mpole);
+    Mpole_Alloc(&Elem);
+    Elem.M->Pthick = pthicktype(thin);
+    break;
+  case wiggler_:
+    Elem.Pkind = PartsKind(Wigl);
+    Wiggler_Alloc(&Elem);
+    break;
+  case insertion_:
+    Elem.Pkind = PartsKind(Insertion);
+    Insertion_Alloc(&Elem);
+    break;
+  default:
+    cout << "get_kind: unknown type " << kind << " " << Elem.PName << endl;
+    exit_(1);
+    break;
+  }
+}
+
+
+void rdmfile(const char *mfile_dat)
+ {
+    char line[max_str], file_name[max_str];
+    int j, nmpole, kind, method, n;
+    long int i;
+    double dTerror;
+
+    bool prt = false;
+
+    cout << endl;
+    cout << "reading machine file: " << mfile_dat << endl;
+
+    file_rd(inf, mfile_dat);
+
+    while (inf.getline(line, max_str) != NULL) {
+        if (prt)
+            printf("%s\n", line);
+        sscanf(line, "%*s %*d %*d %ld", &i);
+
+        Cell[i].dS[X_] = 0.0;
+        Cell[i].dS[Y_] = 0.0;
+        Cell[i].dT[X_] = 1.0;
+        Cell[i].dT[Y_] = 0.0;
+
+        sscanf(line, "%s %ld %ld", Cell[i].Elem.PName, &Cell[i].Fnum,
+                &Cell[i].Knum);
+
+        if (Cell[i].Knum == 1) {
+            strcpy(ElemFam[Cell[i].Fnum - 1].ElemF.PName, Cell[i].Elem.PName);
+            globval.Elem_nFam = max(Cell[i].Fnum, globval.Elem_nFam);
+        }
+
+        if (i > 0) {
+            ElemFam[Cell[i].Fnum - 1].KidList[Cell[i].Knum - 1] = i;
+            ElemFam[Cell[i].Fnum - 1].nKid = max(Cell[i].Knum,
+                    ElemFam[Cell[i].Fnum - 1].nKid);
+        }
+
+        inf.getline(line, max_str);
+        if (prt)
+            printf("%s\n", line);
+        sscanf(line, "%d %d %d", &kind, &method, &n);
+        get_kind(kind, Cell[i].Elem);
+        if (i > 0)
+            ElemFam[Cell[i].Fnum - 1].ElemF.Pkind = Cell[i].Elem.Pkind;
+
+        inf.getline(line, max_str);
+        if (prt)
+            printf("%s\n", line);
+        sscanf(line, "%lf %lf %lf %lf", &Cell[i].maxampl[X_][0],
+                &Cell[i].maxampl[X_][1], &Cell[i].maxampl[Y_][0],
+                &Cell[i].maxampl[Y_][1]);
+
+        Cell[i].Elem.PL = 0.0;
+
+        switch (Cell[i].Elem.Pkind) {
+        case undef:
+            cout << "rdmfile: unknown type " << i << endl;
+            exit_(1);
+            break;
+        case marker:
+            break;
+        case drift:
+            inf.getline(line, max_str);
+            if (prt)
+                printf("%s\n", line);
+            sscanf(line, "%lf", &Cell[i].Elem.PL);
+            break;
+        case Cavity:
+            inf.getline(line, max_str);
+            if (prt)
+                printf("%s\n", line);
+            sscanf(line, "%lf %lf %d %lf", &Cell[i].Elem.C->Pvolt,
+                    &Cell[i].Elem.C->Pfreq, &Cell[i].Elem.C->Ph,
+                    &globval.Energy);
+            globval.Energy *= 1e-9;
+            Cell[i].Elem.C->Pvolt *= globval.Energy * 1e9;
+            Cell[i].Elem.C->Pfreq *= c0 / (2.0 * M_PI);
+            break;
+        case Mpole:
+            Cell[i].Elem.M->Pmethod = method;
+            Cell[i].Elem.M->PN = n;
+
+            if (Cell[i].Elem.M->Pthick == thick) {
+                inf.getline(line, max_str);
+                if (prt)
+                    printf("%s\n", line);
+                sscanf(line, "%lf %lf %lf %lf", &Cell[i].dS[X_],
+                        &Cell[i].dS[Y_], &Cell[i].Elem.M->PdTpar, &dTerror);
+                Cell[i].dT[X_] = cos(dtor(dTerror + Cell[i].Elem.M->PdTpar));
+                Cell[i].dT[Y_] = sin(dtor(dTerror + Cell[i].Elem.M->PdTpar));
+
+                inf.getline(line, max_str);
+                if (prt)
+                    printf("%s\n", line);
+                sscanf(line, "%lf %lf %lf %lf %lf", &Cell[i].Elem.PL,
+                        &Cell[i].Elem.M->Pirho, &Cell[i].Elem.M->PTx1,
+                        &Cell[i].Elem.M->PTx2, &Cell[i].Elem.M->Pgap);
+                if (Cell[i].Elem.M->Pirho != 0.0)
+                    Cell[i].Elem.M->Porder = 1;
+            } else {
+                inf.getline(line, max_str);
+                if (prt)
+                    printf("%s\n", line);
+                sscanf(line, "%lf %lf %lf", &Cell[i].dS[X_], &Cell[i].dS[Y_],
+                        &dTerror);
+                Cell[i].dT[X_] = cos(dtor(dTerror));
+                Cell[i].dT[Y_] = sin(dtor(dTerror));
+            }
+
+            Cell[i].Elem.M->Pc0 = sin(Cell[i].Elem.PL * Cell[i].Elem.M->Pirho
+                    / 2.0);
+            Cell[i].Elem.M->Pc1 = cos(dtor(Cell[i].Elem.M->PdTpar))
+                    * Cell[i].Elem.M->Pc0;
+            Cell[i].Elem.M->Ps1 = sin(dtor(Cell[i].Elem.M->PdTpar))
+                    * Cell[i].Elem.M->Pc0;
+
+            inf.getline(line, max_str);
+            if (prt)
+                printf("%s\n", line);
+            sscanf(line, "%d %d", &nmpole, &Cell[i].Elem.M->n_design);
+            for (j = 1; j <= nmpole; j++) {
+                inf.getline(line, max_str);
+                if (prt)
+                    printf("%s\n", line);
+                sscanf(line, "%d", &n);
+                sscanf(line, "%*d %lf %lf", &Cell[i].Elem.M->PB[HOMmax + n],
+                        &Cell[i].Elem.M->PB[HOMmax - n]);
+                Cell[i].Elem.M->PBpar[HOMmax + n] = Cell[i].Elem.M->PB[HOMmax
+                        + n];
+                Cell[i].Elem.M->PBpar[HOMmax - n] = Cell[i].Elem.M->PB[HOMmax
+                        - n];
+                Cell[i].Elem.M->Porder = max(n, Cell[i].Elem.M->Porder);
+            }
+            break;
+        case Wigl:
+            Cell[i].Elem.W->Pmethod = method;
+            Cell[i].Elem.W->PN = n;
+
+            inf.getline(line, max_str);
+            if (prt)
+                printf("%s\n", line);
+            sscanf(line, "%lf %lf", &Cell[i].Elem.PL, &Cell[i].Elem.W->lambda);
+
+            inf.getline(line, max_str);
+            if (prt)
+                printf("%s\n", line);
+            sscanf(line, "%d", &Cell[i].Elem.W->n_harm);
+
+            if (Cell[i].Knum == 1)
+                Wiggler_Alloc(&ElemFam[Cell[i].Fnum - 1].ElemF);
+            for (j = 0; j < Cell[i].Elem.W->n_harm; j++) {
+                inf.getline(line, max_str);
+                if (prt)
+                    printf("%s\n", line);
+                sscanf(line, "%d %lf %lf %lf %lf %lf",
+                        &Cell[i].Elem.W->harm[j], &Cell[i].Elem.W->kxV[j],
+                        &Cell[i].Elem.W->BoBrhoV[j], &Cell[i].Elem.W->kxH[j],
+                        &Cell[i].Elem.W->BoBrhoH[j], &Cell[i].Elem.W->phi[j]);
+                ElemFam[Cell[i].Fnum - 1].ElemF.W->BoBrhoV[j]
+                        = Cell[i].Elem.W->BoBrhoV[j];
+                ElemFam[Cell[i].Fnum - 1].ElemF.W->BoBrhoH[j]
+                        = Cell[i].Elem.W->BoBrhoH[j];
+            }
+            break;
+        case Insertion:
+            Cell[i].Elem.ID->Pmethod = method;
+            Cell[i].Elem.ID->PN = n;
+
+            inf.getline(line, max_str);
+            if (prt)
+                printf("%s\n", line);
+            sscanf(line, "%lf %d %s", &Cell[i].Elem.ID->scaling1, &n, file_name);
+
+            if (n == 1) {
+                Cell[i].Elem.ID->firstorder = true;
+                Cell[i].Elem.ID->secondorder = false;
+
+                strcpy(Cell[i].Elem.ID->fname1, file_name);
+                Read_IDfile(Cell[i].Elem.ID->fname1, &Cell[i].Elem.PL,
+                        &Cell[i].Elem.ID->nx1, &Cell[i].Elem.ID->nz1,
+                        Cell[i].Elem.ID->tabx1, Cell[i].Elem.ID->tabz1,
+                        Cell[i].Elem.ID->thetax1, Cell[i].Elem.ID->thetaz1);
+            } else if (n == 2) {
+                Cell[i].Elem.ID->firstorder = false;
+                Cell[i].Elem.ID->secondorder = true;
+
+                strcpy(Cell[i].Elem.ID->fname2, file_name);
+                Read_IDfile(Cell[i].Elem.ID->fname2, &Cell[i].Elem.PL,
+                        &Cell[i].Elem.ID->nx2, &Cell[i].Elem.ID->nz2,
+                        Cell[i].Elem.ID->tabx2, Cell[i].Elem.ID->tabz2,
+                        Cell[i].Elem.ID->thetax2, Cell[i].Elem.ID->thetaz2);
+            } else {
+                cout << "rdmfile: undef order " << n << endl;
+                exit_(1);
+            }
+
+            if (Cell[i].Elem.ID->Pmethod == 1)
+                Cell[i].Elem.ID->linear = true;
+            else
+                Cell[i].Elem.ID->linear = false;
+
+            if (!Cell[i].Elem.ID->linear) {
+                Cell[i].Elem.ID->tx1 = dmatrix(1, Cell[i].Elem.ID->nz1, 1,
+                        Cell[i].Elem.ID->nx1);
+                Cell[i].Elem.ID->tz1 = dmatrix(1, Cell[i].Elem.ID->nz1, 1,
+                        Cell[i].Elem.ID->nx1);
+                Cell[i].Elem.ID->tx2 = dmatrix(1, Cell[i].Elem.ID->nz2, 1,
+                        Cell[i].Elem.ID->nx2);
+                Cell[i].Elem.ID->tz2 = dmatrix(1, Cell[i].Elem.ID->nz2, 1,
+                        Cell[i].Elem.ID->nx2);
+                Cell[i].Elem.ID->TabxOrd1 = (double *) malloc(
+                        (Cell[i].Elem.ID->nx1) * sizeof(double));
+                Cell[i].Elem.ID->TabzOrd1 = (double *) malloc(
+                        (Cell[i].Elem.ID->nz1) * sizeof(double));
+                Cell[i].Elem.ID->TabxOrd2 = (double *) malloc(
+                        (Cell[i].Elem.ID->nx2) * sizeof(double));
+                Cell[i].Elem.ID->TabzOrd2 = (double *) malloc(
+                        (Cell[i].Elem.ID->nz2) * sizeof(double));
+                Cell[i].Elem.ID->f2x1 = dmatrix(1, Cell[i].Elem.ID->nz1, 1,
+                        Cell[i].Elem.ID->nx1);
+                Cell[i].Elem.ID->f2z1 = dmatrix(1, Cell[i].Elem.ID->nz1, 1,
+                        Cell[i].Elem.ID->nx1);
+                Cell[i].Elem.ID->f2x2 = dmatrix(1, Cell[i].Elem.ID->nz2, 1,
+                        Cell[i].Elem.ID->nx2);
+                Cell[i].Elem.ID->f2z2 = dmatrix(1, Cell[i].Elem.ID->nz2, 1,
+                        Cell[i].Elem.ID->nx2);
+                Matrices4Spline(Cell[i].Elem.ID, 1);
+                Matrices4Spline(Cell[i].Elem.ID, 2);
+            }
+
+            break;
+        case FieldMap:
+            break;
+        default:
+            cout << "rdmfile: unknown type" << endl;
+            exit_(1);
+            break;
+        }
+
+        if (i == 0)
+            Cell[i].S = 0.0;
+        else
+            Cell[i].S = Cell[i - 1].S + Cell[i].Elem.PL;
+    }
+
+    globval.Cell_nLoc = i;
+
+    globval.dPcommon = 1e-8;
+    globval.CODeps = 1e-14;
+    globval.CODimax = 40;
+
+    SI_init();
+
+    cout << endl;
+    cout << "rdmfile: read " << globval.Cell_nLoc << " elements" << endl;
+
+    inf.close();
+}
diff --git a/tracy/tracy/src/soleilcommon.cc b/tracy/tracy/src/soleilcommon.cc
index 29f2267bfcc5aba97ec90ab9e4e2bc357af716b6..42614ab5678f2728685f8540ad1d5abeca6609ca 100644
--- a/tracy/tracy/src/soleilcommon.cc
+++ b/tracy/tracy/src/soleilcommon.cc
@@ -68,7 +68,7 @@
        27/04/03 energy RF acceptance added set to 6%
        29/04/03 eps added for energy RF acceptance
        28/10/03 modified for transfer lines, filename added in output
-       02/06/08 energy RF accpetance set to 1 just to avoid averflow during tracking
+       02/06/08 energy RF acceptance set to 1 just to avoid overflow during tracking
        22/06/10 add new globval.  flag and modify new name of variables
                  from Tracy III Read_Lattice(), which is defined in physlib.cc 
 
@@ -160,32 +160,28 @@ void Read_Lattice(char *fic)
     globval.hcorr = ElemIndex("ch");  /* get family index of horizontal corrector */
     globval.vcorr = ElemIndex("cv");  /* get family index of vertical corrector */
     globval.bpm = ElemIndex("bpm");   /* get family index of bpm*/
-  //  globval.g = ElemIndex("g");  /* get family index of  girder*/
+    //globval.g = ElemIndex("g");  /* get family index of  girder*/
    
    /* define x/y physical aperture  */
-    //ChamberOff();
-    ChamberOn();
+    ChamberOff();
     /* Compute and get Twiss parameters */
     Ring_GetTwiss(chroma = true, dP = 0.0);
-//        GetChromTrac(2, 1026L, 1e-6, &ksix, &ksiz);
-//        fprintf(stdout,"\n From tracking: ksix= % f ksiz= % f \n",ksix,ksiz);
 
-    Cell_SetdP(dP);  /* added for correcting BUG if non convergence: compute on momentum linear matrices */
+  //  Cell_SetdP(dP);  /* added for correcting BUG if non convergence: compute on momentum linear matrices */
   }
   
   else 
   { // for transfer lines  
     /* Initial settings : */
-    beta[0] = 8.1;
+    beta[0]  = 8.1;
     alpha[0] = 0.0;
-    beta[1] = 8.1;
+    beta[1]  = 8.1;
     alpha[1] = 0.0;
-    eta[0] = 0.0;
-    etap[0] = 0.0;
-    eta[1] = 0.0;
-    etap[1] = 0.0;
+    eta[0]   = 0.0;
+    etap[0]  = 0.0;
+    eta[1]   = 0.0;
+    etap[1]  = 0.0;
 
- //   for (i = 0; i < matdim; i++)
      for (i = 0; i < ss_dim; i++) {
     {
       codvect[i] = 0.0;
diff --git a/tracy/tracy/src/soleillib.cc b/tracy/tracy/src/soleillib.cc
index a396eb8bbbbae624cfde25227026c4bc98de85d2..53123995a6d3b34ab24af2c2eff21655e766887f 100644
--- a/tracy/tracy/src/soleillib.cc
+++ b/tracy/tracy/src/soleillib.cc
@@ -69,7 +69,7 @@ void Get_Disp_dp(void)
    Purpose:
       Compute the induced amplitude for a particle getting for a energy offset dP
         process similar to a Touschek scattering
-        The induced maplitude is trnasported to the first element of the lattice
+        The induced amplitude is transported to the first element of the lattice
         by scaling the maplitude with energy dependent betafunctions        
 
    Input:
@@ -5151,7 +5151,7 @@ void ReadFieldErr(const char *FieldErrorFile)
         /*read and assign the key words and measure radius*/
         sscanf(line, "%s", name); 
 	sscanf(line, " %*s %lf", &r0);
-	printf("\nsetting multipole error to: %-5s r0 = %7.1le\n",name,r0);	
+	if (prt) printf("\nsetting multipole error to: %-5s r0 = %7.1le\n",name,r0);
 	// skip first two parameters
 	strtok(line, " \t");
 	strtok(NULL, " \t");
@@ -5165,7 +5165,7 @@ void ReadFieldErr(const char *FieldErrorFile)
 	  prm = get_prm(); 
 	  sscanf(prm, "%lf", &An);
 	  
-	  if (!prt)
+	  if (prt)
 	    printf(" n = %2d, Bn = %9.1e, An = %9.1e\n", n, Bn, An);
 	  
 	  /* set multipole error to horizontal correctors of soleil ring*/
@@ -5617,8 +5617,8 @@ void FitTune4(long qf1,long qf2, long qd1, long qd2, double nux, double nuy)
   fitvect   qfbuf, qdbuf;
 
   /* Get elements for the first quadrupole family */
-  nq1[X_] = GetnKid(qf1);
-  nq2[X_] = GetnKid(qf2);
+  nq1[X_] = GetnKid(qf1); // get number of elements for family qf1
+  nq2[X_] = GetnKid(qf2); // get number of elements for family qf2
   for (i = 1; i <= (nq1[X_]+nq2[X_]); i++)
     {
       if(i<=nq1[X_])
@@ -5627,9 +5627,9 @@ void FitTune4(long qf1,long qf2, long qd1, long qd2, double nux, double nuy)
         qfbuf[i-1] = Elem_GetPos(qf2, (i-nq1[X_]));
     }
   
-  /* Get elements for the second quadrupole family */
-  nq1[Y_] = GetnKid(qd1);
-  nq2[Y_] = GetnKid(qd2);
+  /* Get elements for the second quadrupole family*/
+  nq1[Y_] = GetnKid(qd1);  // get number of elements for family qd1
+  nq2[Y_] = GetnKid(qd2);  // get number of elements for family qd2
   for (i = 1; i <= (nq1[Y_]+nq2[Y_]); i++)
     {
       if(i<=nq1[Y_])
@@ -5638,7 +5638,6 @@ void FitTune4(long qf1,long qf2, long qd1, long qd2, double nux, double nuy)
         qdbuf[i-1] = Elem_GetPos(qd2, (i-nq1[Y_]));
     }
     
-    
   nu[X_] = nux; nu[Y_] = nuy;
   nq[X_] = nq1[X_]+nq1[X_],nq[Y_] = nq1[Y_]+nq1[Y_];
   
diff --git a/tracy/tracy/src/t2elem.cc b/tracy/tracy/src/t2elem.cc
index a71654df21b1c51a57d182d8cef989d79a0df674..26be9933a1c685e6e777f68d90c3b3ab6763f0ed 100644
--- a/tracy/tracy/src/t2elem.cc
+++ b/tracy/tracy/src/t2elem.cc
@@ -1,3786 +1,4198 @@
 /* Tracy-2
 
-   J. Bengtsson, CBP, LBL      1990 - 1994   Pascal version
-                 SLS, PSI      1995 - 1997
-   M. Boege      SLS, PSI      1998          C translation
-   L. Nadolski   SOLEIL        2002          Link to NAFF, Radia field maps
-   J. Bengtsson  NSLS-II, BNL  2004 -        
+ J. Bengtsson, CBP, LBL      1990 - 1994   Pascal version
+ SLS, PSI      1995 - 1997
+ M. Boege      SLS, PSI      1998          C translation
+ L. Nadolski   SOLEIL        2002          Link to NAFF, Radia field maps
+ J. Bengtsson  NSLS-II, BNL  2004 -
 
-   Element propagators.                                                      */
+ Element propagators.                                                      */
 
-double        c_1, d_1, c_2, d_2, cl_rad, q_fluct;
-double        I2, I4, I5, dcurly_H, dI4;
-ElemFamType   ElemFam[Elem_nFamMax];
-CellType      Cell[Cell_nLocMax+1];
+double c_1, d_1, c_2, d_2, cl_rad, q_fluct;
+double I2, I4, I5, dcurly_H, dI4;
+ElemFamType ElemFam[Elem_nFamMax];
+CellType Cell[Cell_nLocMax + 1];
 
 // for IBS
-int     i_, j_;
-double  **C_;
+int i_, j_;
+double **C_;
 
 // Dynamic model
 
 /****************************************************************************/
 /* void GtoL(ss_vect<T> &X, Vector2 &S, Vector2 &R,
-	  const double c0, const double c1, const double s1)
+ const double c0, const double c1, const double s1)
 
-   Purpose:
-      Global to local coordinates
-      
-****************************************************************************/
+ Purpose:
+ Global to local coordinates
+
+ ****************************************************************************/
 template<typename T>
-void GtoL(ss_vect<T> &X, Vector2 &S, Vector2 &R,
-	  const double c0, const double c1, const double s1)
-{
-  ss_vect<T>  x1;
-
-  /* Simplified rotated p_rot */
-  X[px_] += c1; X[3] += s1;
-  /* Translate */
-  X[x_] -= S[X_]; X[y_] -= S[Y_];
-  /* Rotate */
-  x1 = X;
-  X[x_]  =  R[X_]*x1[x_]  + R[Y_]*x1[y_];
-  X[px_] =  R[X_]*x1[px_] + R[Y_]*x1[py_];
-  X[y_]  = -R[Y_]*x1[x_]  + R[X_]*x1[y_];
-  X[py_] = -R[Y_]*x1[px_] + R[X_]*x1[py_] ;
-  /* Simplified p_rot */
-  X[px_] -= c0;
+void GtoL(ss_vect<T> &X, Vector2 &S, Vector2 &R, const double c0,
+        const double c1, const double s1) {
+    ss_vect<T> x1;
+
+    /* Simplified rotated p_rot */
+    X[px_] += c1;
+    X[3] += s1;
+    /* Translate */
+    X[x_] -= S[X_];
+    X[y_] -= S[Y_];
+    /* Rotate */
+    x1 = X;
+    X[x_] = R[X_] * x1[x_] + R[Y_] * x1[y_];
+    X[px_] = R[X_] * x1[px_] + R[Y_] * x1[py_];
+    X[y_] = -R[Y_] * x1[x_] + R[X_] * x1[y_];
+    X[py_] = -R[Y_] * x1[px_] + R[X_] * x1[py_];
+    /* Simplified p_rot */
+    X[px_] -= c0;
 }
 
 /****************************************************************************/
 /* void LtoG(ss_vect<T> &X, Vector2 &S, Vector2 &R,
-	  double c0, double c1, double s1)
+ double c0, double c1, double s1)
 
-   Purpose:
-      Local to global coordinates
-      
-****************************************************************************/
+ Purpose:
+ Local to global coordinates
+
+ ****************************************************************************/
 template<typename T>
-void LtoG(ss_vect<T> &X, Vector2 &S, Vector2 &R,
-	  double c0, double c1, double s1)
-{
-  ss_vect<T>  x1;
-
-  /* Simplified p_rot */
-  X[px_] -= c0;
-  /* Rotate */
-  x1 = X;
-  X[x_]  = R[X_]*x1[x_]  - R[Y_]*x1[y_];
-  X[px_] = R[X_]*x1[px_] - R[Y_]*x1[py_];
-  X[y_]  = R[Y_]*x1[x_]  + R[X_]*x1[y_];
-  X[py_] = R[Y_]*x1[px_] + R[X_]*x1[py_];
-  /* Translate */
-  X[x_] += S[X_]; X[y_] += S[Y_];
-  /* p_rot rotated */
-  X[px_] += c1; X[py_] += s1;
+void LtoG(ss_vect<T> &X, Vector2 &S, Vector2 &R, double c0, double c1,
+        double s1) {
+    ss_vect<T> x1;
+
+    /* Simplified p_rot */
+    X[px_] -= c0;
+    /* Rotate */
+    x1 = X;
+    X[x_] = R[X_] * x1[x_] - R[Y_] * x1[y_];
+    X[px_] = R[X_] * x1[px_] - R[Y_] * x1[py_];
+    X[y_] = R[Y_] * x1[x_] + R[X_] * x1[y_];
+    X[py_] = R[Y_] * x1[px_] + R[X_] * x1[py_];
+    /* Translate */
+    X[x_] += S[X_];
+    X[y_] += S[Y_];
+    /* p_rot rotated */
+    X[px_] += c1;
+    X[py_] += s1;
 }
 /**********************************************************/
 /*
 
-     Purpose:
-             Get the longitudinal momentum ps
-**********************************************************/
+ Purpose:
+ Get the longitudinal momentum ps
+ **********************************************************/
 
 template<typename T>
-inline T get_p_s(ss_vect<T> &x)
-{
-  T  p_s, p_s2;
-
-  if (!globval.H_exact)
-    p_s = 1.0+x[delta_];
-  else {
-    p_s2 = sqr(1.0+x[delta_]) - sqr(x[px_]) - sqr(x[py_]);
-    if (p_s2 >= 0.0)
-      p_s = sqrt(p_s2);
+inline T get_p_s(ss_vect<T> &x) {
+    T p_s, p_s2;
+
+    if (!globval.H_exact)
+        p_s = 1.0 + x[delta_];
     else {
-      // avoid compile warning
-      p_s = 0.0;
-      printf("get_p_s: *** Speed of light exceeded!\n"); exit_(1);
+        p_s2 = sqr(1.0 + x[delta_]) - sqr(x[px_]) - sqr(x[py_]);
+        if (p_s2 >= 0.0)
+            p_s = sqrt(p_s2);
+        else {
+            // avoid compile warning
+            p_s = 0.0;
+            printf("get_p_s: *** Speed of light exceeded!\n");
+            exit_(1);
+        }
     }
-  }
-  return(p_s);
+    return (p_s);
 }
 
 /****************************************************************************/
 /* Drift(double L, ss_vect<T> &x)
 
-   Purpose:
-       Drift pass
-       
-       If H_exact = false, using approximation Hamiltonian:
-              
-	                                px^2+py^2
-	      H(x,y,l,px,py,delta) = -------------
-	                                2(1+delta)     
-       
-       Otherwise, using exact Hamiltonian
-          
-	   
-   Input:
-       L:  drift length
-      &x:  pointer to initial vector: x
+ Purpose:
+ Drift pass
+
+ If H_exact = false, using approximation Hamiltonian:
+
+ px^2+py^2
+ H(x,y,l,px,py,delta) = -------------
+ 2(1+delta)
 
-   Output:
-       none
+ Otherwise, using exact Hamiltonian
 
-   Return:
-       none
 
-   Global variables:
-       
+ Input:
+ L:  drift length
+ &x:  pointer to initial vector: x
 
-   Specific functions:
+ Output:
+ none
 
-****************************************************************************/
+ Return:
+ none
 
+ Global variables:
+
+
+ Specific functions:
+
+ ****************************************************************************/
 
 template<typename T>
-void Drift(double L, ss_vect<T> &x)
-{
-  T  u;
+void Drift(double L, ss_vect<T> &x) {
+    T u;
 
-  if (!globval.H_exact) {
-    u = L/(1.0+x[delta_]);
-    x[ct_] += u*(sqr(x[px_])+sqr(x[py_]))/(2.0*(1.0+x[delta_]));
-  } else {
-    u = L/get_p_s(x);
-    x[ct_] += u*(1.0+x[delta_]) - L;
-  }
-  x[x_] += x[px_]*u; x[y_] += x[py_]*u;
-  if (globval.pathlength) x[ct_] += L;
+    if (!globval.H_exact) {
+        u = L / (1.0 + x[delta_]);
+        x[ct_] += u * (sqr(x[px_]) + sqr(x[py_])) / (2.0 * (1.0 + x[delta_]));
+    } else {
+        u = L / get_p_s(x);
+        x[ct_] += u * (1.0 + x[delta_]) - L;
+    }
+    x[x_] += x[px_] * u;
+    x[y_] += x[py_] * u;
+    if (globval.pathlength)
+        x[ct_] += L;
 }
 
-
 template<typename T>
-void Drift_Pass(CellType &Cell, ss_vect<T> &x) 
-{ Drift(Cell.Elem.PL, x); }
+void Drift_Pass(CellType &Cell, ss_vect<T> &x) {
+    Drift(Cell.Elem.PL, x);
+}
 
 /****************************************************************************/
 /* zero_mat(const int n, double** A)
 
-   Purpose:
-       Initionize  n x n  matrix A with 0
-       
-    
-****************************************************************************/
-void zero_mat(const int n, double** A)
-{
-  int  i, j;
+ Purpose:
+ Initionize  n x n  matrix A with 0
+
 
-  for (i = 1; i <= n; i++)
-    for (j = 1; j <= n; j++)
-      A[i][j] = 0.0;
+ ****************************************************************************/
+void zero_mat(const int n, double** A) {
+    int i, j;
+
+    for (i = 1; i <= n; i++)
+        for (j = 1; j <= n; j++)
+            A[i][j] = 0.0;
 }
 
 /****************************************************************************/
 /* void identity_mat(const int n, double** A)
 
-   Purpose:
-       generate  n x n  identity matrix A
-       
-    
-****************************************************************************/
-void identity_mat(const int n, double** A)
-{
-  int  i, j;
+ Purpose:
+ generate  n x n  identity matrix A
+
 
-  for (i = 1; i <= n; i++)
-    for (j = 1; j <= n; j++)
-      A[i][j] = (i == j)? 1.0 : 0.0;
+ ****************************************************************************/
+void identity_mat(const int n, double** A) {
+    int i, j;
+
+    for (i = 1; i <= n; i++)
+        for (j = 1; j <= n; j++)
+            A[i][j] = (i == j) ? 1.0 : 0.0;
 }
 
 /****************************************************************************/
 /* void det_mat(const int n, double **A)
 
-   Purpose:
-       get the determinant of  n x n matrix A
-       
-    
-****************************************************************************/
-double det_mat(const int n, double **A)
-{
-  int     i, *indx;
-  double  **U, d;
-
-  indx = ivector(1, n); U = dmatrix(1, n, 1, n);
+ Purpose:
+ get the determinant of  n x n matrix A
 
-  dmcopy(A, n, n, U); dludcmp(U, n, indx, &d);
 
-  for (i = 1; i <= n; i++)
-    d *= U[i][i];
+ ****************************************************************************/
+double det_mat(const int n, double **A) {
+    int i, *indx;
+    double **U, d;
 
-  free_dmatrix(U, 1, n, 1, n); free_ivector(indx, 1, n);
-
-  return d;
-}
+    indx = ivector(1, n);
+    U = dmatrix(1, n, 1, n);
 
-/****************************************************************************/
-/* void trace_mat(const int n, double **A)
+    dmcopy(A, n, n, U);
+    dludcmp(U, n, indx, &d);
 
-   Purpose:
-       get the trace of  n x n matrix A
-       
-    
-****************************************************************************/
-double trace_mat(const int n, double **A)
-{
-  int     i;
-  double  d;
+    for (i = 1; i <= n; i++)
+        d *= U[i][i];
 
-  d = 0.0;
-  for (i = 1; i <= n; i++)
-    d += A[i][i];
+    free_dmatrix(U, 1, n, 1, n);
+    free_ivector(indx, 1, n);
 
-  return d;
+    return d;
 }
 
+/****************************************************************************/
+/* void trace_mat(const int n, double **A)
 
-float K_fun(float lambda)
-{
-  double  **Id, **Lambda, **Lambda_inv, **U, **V, **K_int;
-
-  Id = dmatrix(1, DOF, 1, DOF); Lambda = dmatrix(1, DOF, 1, DOF);
-  Lambda_inv = dmatrix(1, DOF, 1, DOF); U = dmatrix(1, DOF, 1, DOF);
-  V = dmatrix(1, DOF, 1, DOF); K_int = dmatrix(1, DOF, 1, DOF);
+ Purpose:
+ get the trace of  n x n matrix A
 
-  identity_mat(DOF, Id);
 
-  dmsmy(Id, DOF, DOF, lambda, U);
-//  dmsub(C_, DOF, DOF, U, Lambda);
-  dmadd(C_, DOF, DOF, U, Lambda);
-  dinverse(Lambda, DOF, Lambda_inv);
+ ****************************************************************************/
+double trace_mat(const int n, double **A) {
+    int i;
+    double d;
 
-  dmsmy(Id, DOF, DOF, trace_mat(DOF, Lambda_inv), U);
-  dmsmy(Lambda_inv, DOF, DOF, 3.0, V);
-  dmsub(U, DOF, DOF, V, K_int);
-  dmsmy(K_int, DOF, DOF, 2.0*sqr(M_PI)*sqrt(lambda/det_mat(DOF, Lambda)),
-	K_int);
+    d = 0.0;
+    for (i = 1; i <= n; i++)
+        d += A[i][i];
 
-  free_dmatrix(Id, 1, DOF, 1, DOF); free_dmatrix(Lambda, 1, DOF, 1, DOF);
-  free_dmatrix(Lambda_inv, 1, DOF, 1, DOF); free_dmatrix(U, 1, DOF, 1, DOF);
-  free_dmatrix(V, 1, DOF, 1, DOF); free_dmatrix(K_int, 1, DOF, 1, DOF);
+    return d;
+}
 
-  return K_int[i_][j_];
+float K_fun(float lambda) {
+    double **Id, **Lambda, **Lambda_inv, **U, **V, **K_int;
+
+    Id = dmatrix(1, DOF, 1, DOF);
+    Lambda = dmatrix(1, DOF, 1, DOF);
+    Lambda_inv = dmatrix(1, DOF, 1, DOF);
+    U = dmatrix(1, DOF, 1, DOF);
+    V = dmatrix(1, DOF, 1, DOF);
+    K_int = dmatrix(1, DOF, 1, DOF);
+
+    identity_mat(DOF, Id);
+
+    dmsmy(Id, DOF, DOF, lambda, U);
+    //  dmsub(C_, DOF, DOF, U, Lambda);
+    dmadd(C_, DOF, DOF, U, Lambda);
+    dinverse(Lambda, DOF, Lambda_inv);
+
+    dmsmy(Id, DOF, DOF, trace_mat(DOF, Lambda_inv), U);
+    dmsmy(Lambda_inv, DOF, DOF, 3.0, V);
+    dmsub(U, DOF, DOF, V, K_int);
+    dmsmy(K_int, DOF, DOF, 2.0 * sqr(M_PI)
+            * sqrt(lambda / det_mat(DOF, Lambda)), K_int);
+
+    free_dmatrix(Id, 1, DOF, 1, DOF);
+    free_dmatrix(Lambda, 1, DOF, 1, DOF);
+    free_dmatrix(Lambda_inv, 1, DOF, 1, DOF);
+    free_dmatrix(U, 1, DOF, 1, DOF);
+    free_dmatrix(V, 1, DOF, 1, DOF);
+    free_dmatrix(K_int, 1, DOF, 1, DOF);
+
+    return K_int[i_][j_];
 }
 
 // partial template-class specialization
 // primary version
 template<typename T>
-class is_tps { };
+class is_tps {
+};
 
 // partial specialization
 template<>
 class is_tps<double> {
- public:
-  static inline void get_ps(const ss_vect<double> &x, CellType &Cell)
-  { Cell.BeamPos = x; }
+public:
+    static inline void get_ps(const ss_vect<double> &x, CellType &Cell) {
+        Cell.BeamPos = x;
+    }
 
-  static inline double set_prm(const int k) { return 1.0; }
+    static inline double set_prm(const int k) {
+        return 1.0;
+    }
 
-  static inline double get_curly_H(const ss_vect<tps> &x)
-    {
-      cout << "get_curly_H: operation not defined for double" << endl;
-      exit_(1);
-      return 0.0;
+    static inline double get_curly_H(const ss_vect<tps> &x) {
+        cout << "get_curly_H: operation not defined for double" << endl;
+        exit_(1);
+        return 0.0;
     }
 
-  static inline double get_dI4(const double h, const double b2, const double L,
-			     const ss_vect<tps> &x)
-    {
-      cout << "get_dI4: operation not defined for double" << endl;
-      exit_(1);
-      return 0.0;
+    static inline double get_dI4(const double h, const double b2,
+            const double L, const ss_vect<tps> &x) {
+        cout << "get_dI4: operation not defined for double" << endl;
+        exit_(1);
+        return 0.0;
     }
 
-  static inline void emittance(const double B2, const double u,
-			       const double ps0, const ss_vect<double> &xp) { }
+    static inline void emittance(const double B2, const double u,
+            const double ps0, const ss_vect<double> &xp) {
+    }
 
-  static inline void do_IBS(const double L, const ss_vect<double> &A_tps) { }
+    static inline void do_IBS(const double L, const ss_vect<double> &A_tps) {
+    }
 
-  static inline void diff_mat(const double B2, const double u,
-			      const double ps0, const ss_vect<double> &xp) { }
+    static inline void diff_mat(const double B2, const double u,
+            const double ps0, const ss_vect<double> &xp) {
+    }
 
 };
 
-
 // partial specialization
 template<>
 class is_tps<tps> {
- public:
-  static inline void get_ps(const ss_vect<tps> &x, CellType &Cell)
-  { getlinmat(6, x, Cell.A); }
-
-  static inline tps set_prm(const int k) { return tps(0.0, k); }
-
-  static inline double get_curly_H(const ss_vect<tps> &A)
-  {
-    int              j;
-    double           curly_H[2];
-    ss_vect<double>  eta;
-
-    eta.zero();
-    for (j = 0; j < 4; j++)
-      eta[j] = A[j][delta_];
-
-    get_twoJ(2, eta, A, curly_H);
-
-    return curly_H[X_];
-  }
-
-  static inline double get_dI4(const ss_vect<tps> &A) { return A[x_][delta_]; }
-
-  static inline void emittance(const tps &B2, const tps &ds, const tps &ps0,
-			       const ss_vect<tps> &A) {
-    int           j;
-    double        B_66;
-    ss_vect<tps>  A_inv;
-
-    if (B2 > 0.0) {
-      B_66 = (q_fluct*pow(B2.cst(), 1.5)*pow(ps0, 4)*ds).cst();
-      A_inv = Inv(A);
-      // D_11 = D_22 = curly_H_x,y * B_66 / 2,
-      // curly_H_x,y = eta_Fl^2 + etap_Fl^2
-      for (j = 0; j < 3; j++)
-	globval.D_rad[j] +=
-	  (sqr(A_inv[j*2][delta_])+sqr(A_inv[j*2+1][delta_]))*B_66/2.0;
-    }
-  }
-
-  static void do_IBS(const double L, const ss_vect<tps> &A_tps)
-  {
-    /* A is passed, compute the invariants and emittances,
-       The invariants for the uncoupled case are:
-
-                       [gamma alpha]
-       Sigma     ^-1 = [           ]
-            x,y,z      [alpha beta ]
-
-       Note, ps = [x, y, ct, p_x, p_y, delta]                                */
-
-    int     i, j, k;
-    double  **A, **Ainv, **Ainv_tp, **Ainv_tp_Ainv, **Boost, **Boost_tp;
-    double  **G[DOF], **M_a, **U, **C_a[DOF], **K, dln_eps[DOF];
-    double  beta_x, beta_y, sigma_y, a_cst, two_Lc;
-
-    const int     n      = 2*DOF;
-    const int     indx[] = { 1, 4, 2, 5, 6, 3 };
-
-    const double  P0    = 1e9*globval.Energy*q_e/c0;
-    const double  gamma = 1e9*globval.Energy/m_e;
-    const double  beta  = sqrt(1.0-1.0/sqr(gamma));
-
-    const double  N_e   = globval.Qb/q_e;
-
-    A = dmatrix(1, n, 1, n); Ainv = dmatrix(1, n, 1, n);
-    Ainv_tp = dmatrix(1, n, 1, n); Ainv_tp_Ainv = dmatrix(1, n, 1, n);
-    Boost = dmatrix(1, n, 1, n); Boost_tp = dmatrix(1, n, 1, n);
-    U = dmatrix(1, n, 1, n); M_a = dmatrix(1, n, 1, n);
-    for (i = 0; i < DOF; i++)
-      G[i] = dmatrix(1, n, 1, n);
-    for (i = 0; i < DOF; i++)
-      C_a[i] = dmatrix(1, DOF, 1, DOF);
-    C_ = dmatrix(1, DOF, 1, DOF); K = dmatrix(1, DOF, 1, DOF);
-
-    // Compute invariants (in Floquet space): Sigma^-1 = (A^-1)^tp * A^-1
-    
-    for (i = 1; i <= n; i++)
-      for(j = 1; j <= n; j++ )
-	A[i][j] = A_tps[i-1][j-1];
+public:
+    static inline void get_ps(const ss_vect<tps> &x, CellType &Cell) {
+        getlinmat(6, x, Cell.A);
+    }
+
+    static inline tps set_prm(const int k) {
+        return tps(0.0, k);
+    }
 
-    dmcopy(A, n, n, U); dinverse(U, n, Ainv);
-    dmtranspose(Ainv, n, n, Ainv_tp);
-    dmmult(Ainv_tp, n, n, Ainv, n, n, Ainv_tp_Ainv);
+    static inline double get_curly_H(const ss_vect<tps> &A) {
+        int j;
+        double curly_H[2];
+        ss_vect<double> eta;
 
-    for (i = 0; i < DOF; i++)
-      for(j = 1; j <= n; j++ )
-	for (k = 1; k <= n; k++)
-	  G[i][indx[j-1]][indx[k-1]] =
-	    Ainv[2*i+1][j]*Ainv[2*i+1][k] + Ainv[2*i+2][j]*Ainv[2*i+2][k];
-
-    dmadd(G[0], n, n, G[1], U); dmadd(U, n, n, G[2], U);
-
-    if (trace) {
-      printf("\n");
-      dmdump(stdout, "G_1:", G[0], n, n, "%11.3e");
-      dmdump(stdout, "G_2:", G[1], n, n, "%11.3e");
-      dmdump(stdout, "G_3:", G[2], n, n, "%11.3e");
-      dmdump(stdout, "Ainv_tp*Ainv:", Ainv_tp_Ainv, n, n, "%11.3e");
-      dmdump(stdout, "Sum_a G_a", U, n, n, "%11.3e");
-    }
-
-    /* Transform from the co-moving to COM frame:
-
-        [ 1 0    0     0    0      0     ] 
-        [ 0 1    0     0    0      0     ] 
-        [ 0 0 1/gamma  0    0      0     ] 
-        [ 0 0    0    1/P0  0      0     ] 
-        [ 0 0    0     0   1/P0    0     ] 
-        [ 0 0    0     0    0   gamma/P0 ]                                  */
-
-    identity_mat(n, Boost);
-    Boost[3][3] /= gamma; Boost[4][4] /= P0; Boost[5][5] /= P0;
-    Boost[6][6] *= gamma/P0;
-
-    dmtranspose(Boost, n, n, Boost_tp);
-
-    zero_mat(DOF, C_);
-    for (i = 0; i < DOF; i++) {
-      dmmult(Boost_tp, n, n, G[i], n, n, U);
-      dmmult(U, n, n, Boost, n, n, M_a);
-
-      if (trace) dmdump(stdout, "M_a:", M_a, n, n, "%11.3e");
-
-      // Extract the C_a matrices from the momentum components of M_a
-      for(j = 1; j <= DOF; j++)
-	for(k = 1; k <= DOF; k++)
-	  C_a[i][j][k] = M_a[DOF+j][DOF+k];
-
-      dmsmy(C_a[i], DOF, DOF, sqr(P0), C_a[i]);
-
-      if (globval.eps[i] != 0.0)
-	dmsmy(C_a[i], DOF, DOF, 1.0/globval.eps[i], U);
-      else {
-	cout << "*** do_IBS: zero emittance for plane " << i+1 << endl;
-	exit(1);
-      }
-
-      dmadd(C_, DOF, DOF, U, C_);
-    }
-
-    if (trace) {
-      dmdump(stdout, "C_1:", C_a[0], DOF, DOF, "%11.3e");
-      dmdump(stdout, "C_2:", C_a[1], DOF, DOF, "%11.3e");
-      dmdump(stdout, "C_3:", C_a[2], DOF, DOF, "%11.3e");
-      dmdump(stdout, "C:", C_, DOF, DOF, "%11.3e");
-    }
-
-    for(i = 1; i <= DOF; i++)
-      for(j = 1; j <= DOF; j++) {
-	// upper bound is infinity
-	i_ = i; j_ = j;
-	K[i][j] = qromb(K_fun, 0.0, 1e8);
-      }
-
-    if (trace) dmdump(stdout, "K:", K, DOF, DOF, "%11.3e");
-  
-    // Compute the Coulomb logarithm
-    beta_x = C_a[0][1][1]; beta_y = C_a[1][2][2];
-    sigma_y = sqrt(beta_y*globval.eps[Y_]);
-    two_Lc = log(sqr(gamma*globval.eps[X_]*sigma_y/(r_e*beta_x)));
-
-    if (trace) printf("2(log) = %11.3e\n", two_Lc);
-
-    // include time dilatation and scaling of C matrix
-    a_cst =
-       L*two_Lc*N_e*sqr(r_e)*c0/(64.0*cube(M_PI*beta)*pow(gamma, 4)
-      *globval.eps[X_]*globval.eps[Y_]*globval.eps[Z_]);
-
-    // dSigma_ab/dt = a_cst * K_ab, e.g. d<delta^2>/dt = a_cst K_33.
-    // deps is obtained from C.
-
-    if (trace) printf("dln_eps:");
-    for(i = 0; i < DOF; i++) {
-      dmmult(C_a[i], DOF, DOF, K, DOF, DOF, U);
-      // Dt = L/c0
-//      dln_eps[i] = a_cst/globval.eps[i]*trace_mat(DOF, U);
-      globval.D_IBS[i] += a_cst*trace_mat(DOF, U);
-      if (trace) printf("%11.3e", dln_eps[i]);
-    }
-    if (trace) printf("\n");
-
-    free_dmatrix(A, 1, n, 1, n); free_dmatrix(Ainv, 1, n, 1, n);
-    free_dmatrix(Ainv_tp, 1, n, 1, n); free_dmatrix(Ainv_tp_Ainv, 1, n, 1, n);
-    free_dmatrix(Boost, 1, n, 1, n); free_dmatrix(Boost_tp, 1, n, 1, n);
-    free_dmatrix(U, 1, n, 1, n); free_dmatrix(M_a, 1, n, 1, n);
-    for (i = 0; i < DOF; i++)
-      free_dmatrix(G[i], 1, n, 1, n);
-    for (i = 0; i < DOF; i++)
-      free_dmatrix(C_a[i], 1, DOF, 1, DOF);
-    free_dmatrix(C_, 1, DOF, 1, DOF); free_dmatrix(K, 1, DOF, 1, DOF);
-  }
-
-  static inline void diff_mat(const tps &B2, const tps &ds, const tps &ps0,
-			      ss_vect<tps> &x) { }
+        eta.zero();
+        for (j = 0; j < 4; j++)
+            eta[j] = A[j][delta_];
 
-};
+        get_twoJ(2, eta, A, curly_H);
 
+        return curly_H[X_];
+    }
 
-template<typename T>
-void get_B2(const double h_ref, const T B[], const ss_vect<T> &xp,
-	    T &B2_perp, T &B2_par)
-{
-  // compute |B|^2_perpendicular and |B|^2_parallel
-  T  xn, e[3];
+    static inline double get_dI4(const ss_vect<tps> &A) {
+        return A[x_][delta_];
+    }
 
-  xn = 1.0/sqrt(sqr(1.0+xp[x_]*h_ref)+sqr(xp[px_])+sqr(xp[py_]));
-  e[X_] = xp[px_]*xn; e[Y_] = xp[py_]*xn; e[Z_] = (1e0+xp[x_]*h_ref)*xn;
+    static inline void emittance(const tps &B2, const tps &ds, const tps &ps0,
+            const ss_vect<tps> &A) {
+        int j;
+        double B_66;
+        ss_vect<tps> A_inv;
+
+        if (B2 > 0.0) {
+            B_66 = (q_fluct * pow(B2.cst(), 1.5) * pow(ps0, 4) * ds).cst();
+            A_inv = Inv(A);
+            // D_11 = D_22 = curly_H_x,y * B_66 / 2,
+            // curly_H_x,y = eta_Fl^2 + etap_Fl^2
+            for (j = 0; j < 3; j++)
+                globval.D_rad[j] += (sqr(A_inv[j * 2][delta_]) + sqr(A_inv[j
+                        * 2 + 1][delta_])) * B_66 / 2.0;
+        }
+    }
 
-  // left-handed coordinate system
-  B2_perp = sqr(B[Y_]*e[Z_]-B[Z_]*e[Y_]) + sqr(B[X_]*e[Y_]-B[Y_]*e[X_])
-            + sqr(B[Z_]*e[X_]-B[X_]*e[Z_]);
+    static void do_IBS(const double L, const ss_vect<tps> &A_tps) {
+        /* A is passed, compute the invariants and emittances,
+         The invariants for the uncoupled case are:
+
+         [gamma alpha]
+         Sigma     ^-1 = [           ]
+         x,y,z      [alpha beta ]
+
+         Note, ps = [x, y, ct, p_x, p_y, delta]                                */
+
+        int i, j, k;
+        double **A, **Ainv, **Ainv_tp, **Ainv_tp_Ainv, **Boost, **Boost_tp;
+        double **G[DOF], **M_a, **U, **C_a[DOF], **K, dln_eps[DOF];
+        double beta_x, beta_y, sigma_y, a_cst, two_Lc;
+
+        const int n = 2 * DOF;
+        const int indx[] = { 1, 4, 2, 5, 6, 3 };
+
+        const double P0 = 1e9 * globval.Energy * q_e / c0;
+        const double gamma = 1e9 * globval.Energy / m_e;
+        const double beta = sqrt(1.0 - 1.0 / sqr(gamma));
+
+        const double N_e = globval.Qb / q_e;
+
+        A = dmatrix(1, n, 1, n);
+        Ainv = dmatrix(1, n, 1, n);
+        Ainv_tp = dmatrix(1, n, 1, n);
+        Ainv_tp_Ainv = dmatrix(1, n, 1, n);
+        Boost = dmatrix(1, n, 1, n);
+        Boost_tp = dmatrix(1, n, 1, n);
+        U = dmatrix(1, n, 1, n);
+        M_a = dmatrix(1, n, 1, n);
+        for (i = 0; i < DOF; i++)
+            G[i] = dmatrix(1, n, 1, n);
+        for (i = 0; i < DOF; i++)
+            C_a[i] = dmatrix(1, DOF, 1, DOF);
+        C_ = dmatrix(1, DOF, 1, DOF);
+        K = dmatrix(1, DOF, 1, DOF);
+
+        // Compute invariants (in Floquet space): Sigma^-1 = (A^-1)^tp * A^-1
+
+        for (i = 1; i <= n; i++)
+            for (j = 1; j <= n; j++)
+                A[i][j] = A_tps[i - 1][j - 1];
+
+        dmcopy(A, n, n, U);
+        dinverse(U, n, Ainv);
+        dmtranspose(Ainv, n, n, Ainv_tp);
+        dmmult(Ainv_tp, n, n, Ainv, n, n, Ainv_tp_Ainv);
+
+        for (i = 0; i < DOF; i++)
+            for (j = 1; j <= n; j++)
+                for (k = 1; k <= n; k++)
+                    G[i][indx[j - 1]][indx[k - 1]] = Ainv[2 * i + 1][j]
+                            * Ainv[2 * i + 1][k] + Ainv[2 * i + 2][j] * Ainv[2
+                            * i + 2][k];
+
+        dmadd(G[0], n, n, G[1], U);
+        dmadd(U, n, n, G[2], U);
+
+        if (trace) {
+            printf("\n");
+            dmdump(stdout, "G_1:", G[0], n, n, "%11.3e");
+            dmdump(stdout, "G_2:", G[1], n, n, "%11.3e");
+            dmdump(stdout, "G_3:", G[2], n, n, "%11.3e");
+            dmdump(stdout, "Ainv_tp*Ainv:", Ainv_tp_Ainv, n, n, "%11.3e");
+            dmdump(stdout, "Sum_a G_a", U, n, n, "%11.3e");
+        }
+
+        /* Transform from the co-moving to COM frame:
+
+         [ 1 0    0     0    0      0     ]
+         [ 0 1    0     0    0      0     ]
+         [ 0 0 1/gamma  0    0      0     ]
+         [ 0 0    0    1/P0  0      0     ]
+         [ 0 0    0     0   1/P0    0     ]
+         [ 0 0    0     0    0   gamma/P0 ]                                  */
+
+        identity_mat(n, Boost);
+        Boost[3][3] /= gamma;
+        Boost[4][4] /= P0;
+        Boost[5][5] /= P0;
+        Boost[6][6] *= gamma / P0;
+
+        dmtranspose(Boost, n, n, Boost_tp);
+
+        zero_mat(DOF, C_);
+        for (i = 0; i < DOF; i++) {
+            dmmult(Boost_tp, n, n, G[i], n, n, U);
+            dmmult(U, n, n, Boost, n, n, M_a);
+
+            if (trace)
+                dmdump(stdout, "M_a:", M_a, n, n, "%11.3e");
+
+            // Extract the C_a matrices from the momentum components of M_a
+            for (j = 1; j <= DOF; j++)
+                for (k = 1; k <= DOF; k++)
+                    C_a[i][j][k] = M_a[DOF + j][DOF + k];
+
+            dmsmy(C_a[i], DOF, DOF, sqr(P0), C_a[i]);
+
+            if (globval.eps[i] != 0.0)
+                dmsmy(C_a[i], DOF, DOF, 1.0 / globval.eps[i], U);
+            else {
+                cout << "*** do_IBS: zero emittance for plane " << i + 1
+                        << endl;
+                exit(1);
+            }
+
+            dmadd(C_, DOF, DOF, U, C_);
+        }
+
+        if (trace) {
+            dmdump(stdout, "C_1:", C_a[0], DOF, DOF, "%11.3e");
+            dmdump(stdout, "C_2:", C_a[1], DOF, DOF, "%11.3e");
+            dmdump(stdout, "C_3:", C_a[2], DOF, DOF, "%11.3e");
+            dmdump(stdout, "C:", C_, DOF, DOF, "%11.3e");
+        }
+
+        for (i = 1; i <= DOF; i++)
+            for (j = 1; j <= DOF; j++) {
+                // upper bound is infinity
+                i_ = i;
+                j_ = j;
+                K[i][j] = qromb(K_fun, 0.0, 1e8);
+            }
+
+        if (trace)
+            dmdump(stdout, "K:", K, DOF, DOF, "%11.3e");
+
+        // Compute the Coulomb logarithm
+        beta_x = C_a[0][1][1];
+        beta_y = C_a[1][2][2];
+        sigma_y = sqrt(beta_y * globval.eps[Y_]);
+        two_Lc = log(sqr(gamma * globval.eps[X_] * sigma_y / (r_e * beta_x)));
+
+        if (trace)
+            printf("2(log) = %11.3e\n", two_Lc);
+
+        // include time dilatation and scaling of C matrix
+        a_cst = L * two_Lc * N_e * sqr(r_e) * c0 / (64.0 * cube(M_PI * beta)
+                * pow(gamma, 4) * globval.eps[X_] * globval.eps[Y_]
+                * globval.eps[Z_]);
+
+        // dSigma_ab/dt = a_cst * K_ab, e.g. d<delta^2>/dt = a_cst K_33.
+        // deps is obtained from C.
+
+        if (trace)
+            printf("dln_eps:");
+        for (i = 0; i < DOF; i++) {
+            dmmult(C_a[i], DOF, DOF, K, DOF, DOF, U);
+            // Dt = L/c0
+            //      dln_eps[i] = a_cst/globval.eps[i]*trace_mat(DOF, U);
+            globval.D_IBS[i] += a_cst * trace_mat(DOF, U);
+            if (trace)
+                printf("%11.3e", dln_eps[i]);
+        }
+        if (trace)
+            printf("\n");
+
+        free_dmatrix(A, 1, n, 1, n);
+        free_dmatrix(Ainv, 1, n, 1, n);
+        free_dmatrix(Ainv_tp, 1, n, 1, n);
+        free_dmatrix(Ainv_tp_Ainv, 1, n, 1, n);
+        free_dmatrix(Boost, 1, n, 1, n);
+        free_dmatrix(Boost_tp, 1, n, 1, n);
+        free_dmatrix(U, 1, n, 1, n);
+        free_dmatrix(M_a, 1, n, 1, n);
+        for (i = 0; i < DOF; i++)
+            free_dmatrix(G[i], 1, n, 1, n);
+        for (i = 0; i < DOF; i++)
+            free_dmatrix(C_a[i], 1, DOF, 1, DOF);
+        free_dmatrix(C_, 1, DOF, 1, DOF);
+        free_dmatrix(K, 1, DOF, 1, DOF);
+    }
 
-//  B2_par = sqr(B[X_]*e[X_]+B[Y_]*e[Y_]+B[Z_]*e[Z_]);
-}
+    static inline void diff_mat(const tps &B2, const tps &ds, const tps &ps0,
+            ss_vect<tps> &x) {
+    }
 
+};
 
 template<typename T>
-void radiate(ss_vect<T> &x, const double L, const double h_ref, const T B[])
-{
-  T           ps0, ps1, ds, B2_perp = 0.0, B2_par = 0.0;
-  ss_vect<T>  xp;
+void get_B2(const double h_ref, const T B[], const ss_vect<T> &xp, T &B2_perp,
+        T &B2_par) {
+    // compute |B|^2_perpendicular and |B|^2_parallel
+    T xn, e[3];
 
-  // large ring: conservation of x' and y'
-  xp = x; ps0 = get_p_s(x); xp[px_] /= ps0; xp[py_] /= ps0;
+    xn = 1.0 / sqrt(sqr(1.0 + xp[x_] * h_ref) + sqr(xp[px_]) + sqr(xp[py_]));
+    e[X_] = xp[px_] * xn;
+    e[Y_] = xp[py_] * xn;
+    e[Z_] = (1e0 + xp[x_] * h_ref) * xn;
 
-  // H = -p_s => ds = H*L
-  ds = (1.0+xp[x_]*h_ref+(sqr(xp[px_])+sqr(xp[py_]))/2.0)*L;
-  get_B2(h_ref, B, xp, B2_perp, B2_par);
- 
-  if (globval.radiation) {
-    x[delta_] -= cl_rad*sqr(ps0)*B2_perp*ds;
-    ps1 = get_p_s(x); x[px_] = xp[px_]*ps1; x[py_] = xp[py_]*ps1;
-  }
+    // left-handed coordinate system
+    B2_perp = sqr(B[Y_] * e[Z_] - B[Z_] * e[Y_]) + sqr(B[X_] * e[Y_] - B[Y_]
+            * e[X_]) + sqr(B[Z_] * e[X_] - B[X_] * e[Z_]);
 
-  if (globval.emittance) is_tps<T>::emittance(B2_perp, ds, ps0, xp);
+    //  B2_par = sqr(B[X_]*e[X_]+B[Y_]*e[Y_]+B[Z_]*e[Z_]);
 }
 
+template<typename T>
+void radiate(ss_vect<T> &x, const double L, const double h_ref, const T B[]) {
+    T ps0, ps1, ds, B2_perp = 0.0, B2_par = 0.0;
+    ss_vect<T> xp;
 
-static double get_psi(double irho, double phi, double gap)
-{
-  /* Correction for magnet gap (longitudinal fringe field)
-
-       irho h = 1/rho [1/m]
-       phi  dipole edge angle
-       gap  full gap between poles
-       
-                                    2
-                   K1*gap*h*(1 + sin phi)
-            psi = ----------------------- * (1 - K2*g*gap*tan phi)
-                        cos phi
-
-            K1 is usually 1/2
-            K2 is zero here                                                  */
+    // large ring: conservation of x' and y'
+    xp = x;
+    ps0 = get_p_s(x);
+    xp[px_] /= ps0;
+    xp[py_] /= ps0;
 
-  double  psi;
+    // H = -p_s => ds = H*L
+    ds = (1.0 + xp[x_] * h_ref + (sqr(xp[px_]) + sqr(xp[py_])) / 2.0) * L;
+    get_B2(h_ref, B, xp, B2_perp, B2_par);
 
-  const double k1 = 0.5, k2 = 0.0;
-            
-  if (phi == 0.0)
-    psi = 0.0;
-  else
-    psi = k1*gap*irho*(1.0+sqr(sin(dtor(phi))))/cos(dtor(phi))
-          *(1.0 - k2*gap*irho*tan(dtor(phi)));
+    if (globval.radiation) {
+        x[delta_] -= cl_rad * sqr(ps0) * B2_perp * ds;
+        ps1 = get_p_s(x);
+        x[px_] = xp[px_] * ps1;
+        x[py_] = xp[py_] * ps1;
+    }
 
-  return psi;
+    if (globval.emittance)
+        is_tps<T>::emittance(B2_perp, ds, ps0, xp);
 }
 
+static double get_psi(double irho, double phi, double gap) {
+    /* Correction for magnet gap (longitudinal fringe field)
 
-/****************************************************************************/
-/* template<typename T>
-void thin_kick(int Order, double MB[], double L, double h_bend, double h_ref,ss_vect<T> &x)
-
-   Purpose:
-        Calculate multipole kick. The Hamiltonian is
-
-            H = A + B where A and B are the kick part defined by
-                                         2    2
-                                       px + py
-                 A(x,y,-l,px,py,dP) = ---------
-                                       2(1+dP)
-                                                   2 2
-                 B(x,y,-l,px,py,dP) = -h*x*dP + 0.5 h x + int(Re(By+iBx)/Brho)
-
-                 so this is the appproximation for large ring
-                 the chromatic term is missing hx*A
-
-
-		The kick is given by
-
-              e L       L delta    L x              e L
-     Dp_x = - --- B_y + ------- - ----- ,    Dp_y = --- B_x
-              p_0         rho     rho^2             p_0
-
-    where
-        e      1
-      --- = -----
-      p_0   B rho   
-                           ====
-                           \ 
-      (B_y + iB_x) = B rho  >   (ia_n  + b_n ) (x + iy)^n-1
-                           /
-                           ====
-  
-   Input:
-       Order  maximum non zero multipole component
-       MB     array of an and bn, magnetic field components
-       L      multipole length
-     h_bend   1/rho in curvilinear coordinate,
-               0    in cartisian cooridinate.
-     h_ref   1/rho [m^-1]
-       x      initial coordinates vector
-
-   Output:
-       x      final coordinates vector
-
-   Return:
-       none
-
-   Global variables:
-       none
-
-   Specific functions:
-       none
-
-   Comments:
-       none
-
-**************************************************************************/
-template<typename T>
-void thin_kick(int Order, double MB[], double L, double h_bend, double h_ref,
-	       ss_vect<T> &x)
-{
-  int         j;
-  T           BxoBrho, ByoBrho, ByoBrho1, B[3];
-  ss_vect<T>  x0, cod;
-
-  if ((h_bend != 0.0) || ((1 <= Order) && (Order <= HOMmax))) 
-   {
-      x0 = x;
-     /* compute field with Horner's rule */
-     ByoBrho = MB[HOMmax+Order];    // normalized By, By/(p0/e)
-     BxoBrho = MB[HOMmax-Order];    // normalized Bx, Bx/(p0/e)
-     
-      for (j = Order-1; j >= 1; j--) {
-       ByoBrho1 = x0[x_]*ByoBrho - x0[y_]*BxoBrho + MB[j+HOMmax];
-       BxoBrho  = x0[y_]*ByoBrho + x0[x_]*BxoBrho + MB[HOMmax-j];
-       ByoBrho  = ByoBrho1;
-      }
-    
-      if (globval.radiation || globval.emittance) {
-       B[X_] = BxoBrho; 
-       B[Y_] = ByoBrho + h_bend; 
-       B[Z_] = 0.0;
-       radiate(x, L, h_ref, B);
-      }
-    
-      if (h_ref != 0.0) {
-       x[px_] -= L*(ByoBrho+(h_bend-h_ref)/2.0+h_ref*h_bend*x0[x_]
-		-h_ref*x0[delta_]);
-       x[ct_] += L*h_ref*x0[x_];
-      } 
-      else x[px_] -= L*(ByoBrho+h_bend);
-  
-  x[py_] += L*BxoBrho;
-  }
-}
-
-/****************************************************************************/
-/* template<typename T>
-static void EdgeFocus(double irho, double phi, double gap, ss_vect<T> &x)
-
-   Purpose:
-       Compute edge focusing for a dipole
-       There is no radiation coming from the edge
-       The standard formula used is :
-                    irho
-       px = px0 + ------ tan(phi) *x0
-                  1 + dP
-
-                    irho
-       pz = pz0 - ------ tan(phi - psi) *z0
-                  1 + dP
-
-       for psi definition  see its function
-
-   Input:
-       irho = inverse of curvature radius (rho = 5.36 m for SOLEIL)
-       phi  = entrance/exit angle of the dipole edge,usually half the 
-               curvature angle of a dipole
-       gap  = gap of the dipole for longitudinal fringing field (see psi)
-       x    = input particle coordinates
-
-   Output:
-       x    output particle coordinates
-
-   Return:
-       none
-
-   Global variables:
-       none
-
-   Specific functions:
-       none
-
-   Comments:
-       05/07/10 Add energy dependence part irho replaced by irho/(1.0+x[delta_])
-                 now the chromaticity attribution of the dipole edge is used
-		 by a simple 1.0+x[delta_], but not a complicated Hamiltonian
-		 expansion. 
-		 Now chromaticities in Tracy II and Tracy III are the same.
-		 Modification based on Tracy II soleil version.
- ****************************************************************************/      
-template<typename T>
-static void EdgeFocus(double irho, double phi, double gap, ss_vect<T> &x)
-{
-  if (true){
-   // warning: => diverging Taylor map (see SSC-141)
-     x[px_] += irho*tan(dtor(phi))*x[x_]/(1.0+x[delta_]);
-     x[py_] -= irho*tan(dtor(phi)-get_psi(irho, phi, gap))*x[y_]
-              /(1.0+x[delta_]);
-     }
-  else{
-     x[px_] += irho*tan(dtor(phi))*x[x_];
-     x[py_] -= irho*tan(dtor(phi)-get_psi(irho, phi, gap))*x[y_];
-     }
-}
+     irho h = 1/rho [1/m]
+     phi  dipole edge angle
+     gap  full gap between poles
 
+     2
+     K1*gap*h*(1 + sin phi)
+     psi = ----------------------- * (1 - K2*g*gap*tan phi)
+     cos phi
 
-template<typename T>
-void p_rot(double phi, ss_vect<T> &x)
-{
-  T           c, s, ps, p;
-  ss_vect<T>  x1;
+     K1 is usually 1/2
+     K2 is zero here                                                  */
 
-  c = cos(dtor(phi)); s = sin(dtor(phi));
-  x1 = x; ps = get_p_s(x); p = c*ps - s*x1[px_]; 
-  x[x_] = x1[x_]*ps/p; x[px_] = s*ps + c*x1[px_];
-  x[y_] += x1[x_]*x1[py_]*s/p;
-  x[ct_] += (1.0+x1[delta_])*x1[x_]*s/p;
-}
+    double psi;
 
+    const double k1 = 0.5, k2 = 0.0;
 
-template<typename T>
-void bend_fringe(double hb, ss_vect<T> &x)
-{
-  T           coeff, u, ps, ps2, ps3;
-  ss_vect<T>  x1;
+    if (phi == 0.0)
+        psi = 0.0;
+    else
+        psi = k1 * gap * irho * (1.0 + sqr(sin(dtor(phi)))) / cos(dtor(phi))
+                * (1.0 - k2 * gap * irho * tan(dtor(phi)));
 
-  coeff = -hb/2.0; x1 = x; ps = get_p_s(x); ps2 = sqr(ps); ps3 = ps*ps2;
-  u = 1.0 + 4.0*coeff*x1[px_]*x1[y_]*x1[py_]/ps3;
-  if (u >= 0.0) {
-    x[y_] = 2.0*x1[y_]/(1.0+sqrt(u));
-    x[x_] = x1[x_] - coeff*sqr(x[y_])*(ps2+sqr(x1[px_]))/ps3;
-    x[py_] = x1[py_] + 2.0*coeff*x1[px_]*x[y_]/ps;
-    x[ct_] = x1[ct_] - coeff*x1[px_]*sqr(x[y_])*(1.0+x1[delta_])/ps3;
-  } else {
-    printf("bend_fringe: *** Speed of light exceeded!\n"); exit_(1);
-  }
+    return psi;
 }
 
-/****************************************************************************
- * template<typename T>
-  void quad_fringe(double b2, ss_vect<T> &x)
+/****************************************************************************/
+/* template<typename T>
+ void thin_kick(int Order, double MB[], double L, double h_bend, double h_ref,ss_vect<T> &x)
 
-   Purpose:
-       Compute edge focusing for a quadrupole
-       There is no radiation coming from the edge
+ Purpose:
+ Calculate multipole kick. The Hamiltonian is
 
-       The standard formula used is using more general form with exponential
-       form. If keep up to the 4-th order nonlinear terms, the formula with goes to the 
-       following:
-       (see E. Forest's book (Beam Dynamics: A New Attitude and Framework), p390):
-                      b2
-       x = x0 +/- ---------- (x0^3 + 3*z0^2*x0)
-                  12(1 + dP)
+ H = A + B where A and B are the kick part defined by
+ 2    2
+ px + py
+ A(x,y,-l,px,py,dP) = ---------
+ 2(1+dP)
+ 2 2
+ B(x,y,-l,px,py,dP) = -h*x*dP + 0.5 h x + int(Re(By+iBx)/Brho)
 
-                         b2
-       px = px0 +/-  ---------- (2*x0*y0*py0 - x0^2*px0 - y0^2*py0)
-                     4(1 + dP)
+ so this is the appproximation for large ring
+ the chromatic term is missing hx*A
 
-                      b2
-       y = y0 -/+ ---------- (y0^3 + 3*x0^2*y0)
-                  12(1 + dP)
 
-                        b2
-       py = py0 -/+  ---------- (2*x0*y0*px0 - y0^2*py0 - x0^2*py0)
-                     4(1 + dP)
+ The kick is given by
 
-       dP = dP0;
-       
+ e L       L delta    L x              e L
+ Dp_x = - --- B_y + ------- - ----- ,    Dp_y = --- B_x
+ p_0         rho     rho^2             p_0
 
-                          b2
-       tau = tau0 -/+ ----------- (y0^3*px - x0^3*py + 3*x0^2*y*py - 3*y0^2*x0*px)
-                      12(1 + dP)^2
+ where
+ e      1
+ --- = -----
+ p_0   B rho
+ ====
+ \
+ (B_y + iB_x) = B rho  >   (ia_n  + b_n ) (x + iy)^n-1
+ /
+ ====
 
-   Input:
-       b2       = quadrupole strength
-       x        = input particle coordinates
+ Input:
+ Order  maximum non zero multipole component
+ MB     array of an and bn, magnetic field components
+ L      multipole length
+ h_bend   1/rho in curvilinear coordinate,
+ 0    in cartisian cooridinate.
+ h_ref   1/rho [m^-1]
+ x      initial coordinates vector
 
-   Output:
-       x    output particle coordinates
+ Output:
+ x      final coordinates vector
 
-   Return:
-       none
+ Return:
+ none
 
-   Global variables:
-       none
+ Global variables:
+ none
 
-   Specific functions:
-       none
+ Specific functions:
+ none
 
-   Comments:
-     Now in Tracy III, no definition "entrance" and "exit", when called in Mpole_pass,
-     first call with  M --> PB[quad+HOMmax], then 
-           call with -M --> PB[quad+HOMmax] 
+ Comments:
+ none
 
-****************************************************************************/
+ **************************************************************************/
 template<typename T>
-void quad_fringe(double b2, ss_vect<T> &x)
-{
-  T  u, ps;
-  
-   u = b2/(12.0*(1.0+x[delta_])); 
-  ps = u/(1.0+x[delta_]);
-  
-  x[py_] /= 1.0 - 3.0*u*sqr(x[y_]);        
-   x[y_] -= u*cube(x[y_]);  
-  
-  if (globval.Cavity_on) 
-    x[ct_] -= ps*cube(x[y_])*x[py_]; //-y^3*py
-  
-  x[px_] /= 1.0 + 3.0*u*sqr(x[x_]);  //+x^2
-  
-  if (globval.Cavity_on) 
-   x[ct_] += ps*cube(x[x_])*x[px_];      //+x^3*px
-  
-  x[x_] += u*cube(x[x_]);    //+x^3
-       u = u*3.0; ps = ps*3.0;
-   x[y_] = exp(-u*sqr(x[x_]))*x[y_];   //+x^2*y
-  x[py_] = exp(u*sqr(x[x_]))*x[py_];   //+x^2*py
-  x[px_]+= 2.0*u*x[x_]*x[y_]*x[py_];   //+2*x*y*py
-  
-  if (globval.Cavity_on) 
-   x[ct_] -= ps*sqr(x[x_])*x[y_]*x[py_];  // -3*x^2*y*py
-   
-   x[x_] = exp(u*sqr(x[y_]))*x[x_];       //+x*y^2
-  x[px_] = exp(-u*sqr(x[y_]))*x[px_];     // -x^2*px-y^2*px
-  x[py_]-= 2.0*u*x[y_]*x[x_]*x[px_];      //-2*x*y*px
-  
-  if (globval.Cavity_on) x[ct_] += ps*sqr(x[y_])*x[x_]*x[px_]; // +3*y^2*x*px
+void thin_kick(int Order, double MB[], double L, double h_bend, double h_ref,
+        ss_vect<T> &x) {
+    int j;
+    T BxoBrho, ByoBrho, ByoBrho1, B[3];
+    ss_vect<T> x0, cod;
+
+    if ((h_bend != 0.0) || ((1 <= Order) && (Order <= HOMmax))) {
+        x0 = x;
+        /* compute field with Horner's rule */
+        ByoBrho = MB[HOMmax + Order]; // normalized By, By/(p0/e)
+        BxoBrho = MB[HOMmax - Order]; // normalized Bx, Bx/(p0/e)
+
+        for (j = Order - 1; j >= 1; j--) {
+            ByoBrho1 = x0[x_] * ByoBrho - x0[y_] * BxoBrho + MB[j + HOMmax];
+            BxoBrho = x0[y_] * ByoBrho + x0[x_] * BxoBrho + MB[HOMmax - j];
+            ByoBrho = ByoBrho1;
+        }
+
+        if (globval.radiation || globval.emittance) {
+            B[X_] = BxoBrho;
+            B[Y_] = ByoBrho + h_bend;
+            B[Z_] = 0.0;
+            radiate(x, L, h_ref, B);
+        }
+
+        if (h_ref != 0.0) {
+            x[px_] -= L * (ByoBrho + (h_bend - h_ref) / 2.0 + h_ref * h_bend
+                    * x0[x_] - h_ref * x0[delta_]);
+            x[ct_] += L * h_ref * x0[x_];
+        } else
+            x[px_] -= L * (ByoBrho + h_bend);
+
+        x[py_] += L * BxoBrho;
+    }
 }
 
-
 /****************************************************************************/
-/* void Mpole_Pass(CellType &Cell, ss_vect<T> &x)
+/* template<typename T>
+ static void EdgeFocus(double irho, double phi, double gap, ss_vect<T> &x)
+
+ Purpose:
+ Compute edge focusing for a dipole
+ There is no radiation coming from the edge
+ The standard formula used is :
+ irho
+ px = px0 + ------ tan(phi) *x0
+ 1 + dP
+
+ irho
+ pz = pz0 - ------ tan(phi - psi) *z0
+ 1 + dP
+
+ for psi definition  see its function
+
+ Input:
+ irho = inverse of curvature radius (rho = 5.36 m for SOLEIL)
+ phi  = entrance/exit angle of the dipole edge,usually half the
+ curvature angle of a dipole
+ gap  = gap of the dipole for longitudinal fringing field (see psi)
+ x    = input particle coordinates
+
+ Output:
+ x    output particle coordinates
+
+ Return:
+ none
+
+ Global variables:
+ none
+
+ Specific functions:
+ none
+
+ Comments:
+ 05/07/10 Add energy dependence part irho replaced by irho/(1.0+x[delta_])
+ now the chromaticity attribution of the dipole edge is used
+ by a simple 1.0+x[delta_], but not a complicated Hamiltonian
+ expansion.
+ Now chromaticities in Tracy II and Tracy III are the same.
+ Modification based on Tracy II soleil version.
+ ****************************************************************************/
+template<typename T>
+static void EdgeFocus(double irho, double phi, double gap, ss_vect<T> &x) {
+    if (true) {
+        // warning: => diverging Taylor map (see SSC-141)
+        x[px_] += irho * tan(dtor(phi)) * x[x_] / (1.0 + x[delta_]);
+        x[py_] -= irho * tan(dtor(phi) - get_psi(irho, phi, gap)) * x[y_]
+                / (1.0 + x[delta_]);
+    } else {
+        x[px_] += irho * tan(dtor(phi)) * x[x_];
+        x[py_] -= irho * tan(dtor(phi) - get_psi(irho, phi, gap)) * x[y_];
+    }
+}
 
-   Purpose:
-       multipole pass,for dipole, quadrupole,sextupole,decupole,etc
-       Using DA method.
-       
-  Input:
-       
-   Output:
-      
+template<typename T>
+void p_rot(double phi, ss_vect<T> &x) {
+    T c, s, ps, p;
+    ss_vect<T> x1;
+
+    c = cos(dtor(phi));
+    s = sin(dtor(phi));
+    x1 = x;
+    ps = get_p_s(x);
+    p = c * ps - s * x1[px_];
+    x[x_] = x1[x_] * ps / p;
+    x[px_] = s * ps + c * x1[px_];
+    x[y_] += x1[x_] * x1[py_] * s / p;
+    x[ct_] += (1.0 + x1[delta_]) * x1[x_] * s / p;
+}
 
-   Return:
-       none
+template<typename T>
+void bend_fringe(double hb, ss_vect<T> &x) {
+    T coeff, u, ps, ps2, ps3;
+    ss_vect<T> x1;
+
+    coeff = -hb / 2.0;
+    x1 = x;
+    ps = get_p_s(x);
+    ps2 = sqr(ps);
+    ps3 = ps * ps2;
+    u = 1.0 + 4.0 * coeff * x1[px_] * x1[y_] * x1[py_] / ps3;
+    if (u >= 0.0) {
+        x[y_] = 2.0 * x1[y_] / (1.0 + sqrt(u));
+        x[x_] = x1[x_] - coeff * sqr(x[y_]) * (ps2 + sqr(x1[px_])) / ps3;
+        x[py_] = x1[py_] + 2.0 * coeff * x1[px_] * x[y_] / ps;
+        x[ct_] = x1[ct_] - coeff * x1[px_] * sqr(x[y_]) * (1.0 + x1[delta_])
+                / ps3;
+    } else {
+        printf("bend_fringe: *** Speed of light exceeded!\n");
+        exit_(1);
+    }
+}
 
-   Global variables:
-       none
+/****************************************************************************
+ * template<typename T>
+ void quad_fringe(double b2, ss_vect<T> &x)
 
-   Specific functions:
-       none
+ Purpose:
+ Compute edge focusing for a quadrupole
+ There is no radiation coming from the edge
 
-   Comments:
-       none     
-    
-****************************************************************************/
+ The standard formula used is using more general form with exponential
+ form. If keep up to the 4-th order nonlinear terms, the formula with goes to the
+ following:
+ (see E. Forest's book (Beam Dynamics: A New Attitude and Framework), p390):
+ b2
+ x = x0 +/- ---------- (x0^3 + 3*z0^2*x0)
+ 12(1 + dP)
 
-template<typename T>
-void Mpole_Pass(CellType &Cell, ss_vect<T> &x)
-{
-  int        seg  = 0;
-  double     k    = 0.0, dL   = 0.0, dL1   = 0.0, dL2 = 0.0;
-  double     dkL1 = 0.0, dkL2 = 0.0, h_ref = 0.0;
-  elemtype   *elemp;
-  MpoleType  *M;
-   
-  elemp = &Cell.Elem; M = elemp->M;
-  
-  /* Global -> Local */
-  GtoL(x, Cell.dS, Cell.dT, M->Pc0, M->Pc1, M->Ps1);
-
-  if ((M->Pmethod == Meth_Second) || (M->Pmethod == Meth_Fourth)) 
-  {  /* fringe fields */ 
-  
-    if (globval.quad_fringe && (M->PB[Quad+HOMmax] != 0.0) &&  (M->quadFF1 == 1)){
-      quad_fringe(M->quadFFscaling*M->PB[Quad+HOMmax], x);}
-
-    
-    if (!globval.H_exact) 
-       {	 
-        if (M->Pirho != 0.0)
-          EdgeFocus(M->Pirho, M->PTx1, M->Pgap, x); 
-       } 
-    else 
-       {
-         p_rot(M->PTx1, x); 
-         bend_fringe(M->Pirho, x);
-       }
-  }
-
-  
-  if (M->Pthick == thick) 
-  {
-    if (!globval.H_exact || ((M->PTx1 == 0.0) && (M->PTx2 == 0.0))) 
-    {// polar coordinates,curvilinear coordinates
-      h_ref = M->Pirho; 
-         dL = elemp->PL/M->PN;
-    } 
-    else 
-    {// Cartesian coordinates
-      h_ref = 0.0;
-      if (M->Pirho == 0.0)
-	dL = elemp->PL/M->PN;
-      else
-	dL = 1.0/M->Pirho*(sin(dtor(M->PTx1)) + sin(dtor(M->PTx2)))/M->PN;
-    }
-  }
-
-  switch (M->Pmethod) 
- {
+ b2
+ px = px0 +/-  ---------- (2*x0*y0*py0 - x0^2*px0 - y0^2*py0)
+ 4(1 + dP)
 
-  case Meth_Linear:
-    
-  case Meth_First:  
-    if (M->Pthick == thick) {
-      /* First Linear  */
-//      LinTrans(5L, M->AU55, x);
-      k = M->PB[Quad+HOMmax];
-      /* retrieve normal quad component already in AU55 */
-      M->PB[Quad+HOMmax] = 0.0; 
-      /* Kick w/o quad component */
-      thin_kick(M->Porder, M->PB, elemp->PL, 0.0, 0.0, x);
-      /* restore quad component */
-      M->PB[Quad+HOMmax] = k;
-      /* Second Linear */
-//      LinTrans(5L, M->AD55, x);
-    } else /* thin kick */      
-      thin_kick(M->Porder, M->PB, 1.0, 0.0, 0.0, x);
-    break;
-
-  case Meth_Second:
-    cout << "Mpole_Pass: Meth_Second not supported" << endl;
-    exit_(0);
-    break;
-
-  case Meth_Fourth:
-    if (M->Pthick == thick) {
-      dL1 = c_1*dL; 
-      dL2 = c_2*dL; 
-      dkL1 = d_1*dL; 
-      dkL2 = d_2*dL;
-
-      dcurly_H = 0.0; 
-           dI4 = 0.0;
-      for (seg = 1; seg <= M->PN; seg++) {
-	if (globval.emittance && (!globval.Cavity_on) && (M->Pirho != 0.0)) {
-	  dcurly_H += is_tps<tps>::get_curly_H(x);
-	       dI4 += is_tps<tps>::get_dI4(x);
-	}
-
-	Drift(dL1, x);
-        thin_kick(M->Porder, M->PB, dkL1, M->Pirho, h_ref, x);
-	Drift(dL2, x);
-        thin_kick(M->Porder, M->PB, dkL2, M->Pirho, h_ref, x);
-
-	if (globval.emittance && (!globval.Cavity_on) && (M->Pirho != 0.0)) {
-	  dcurly_H += 4.0*is_tps<tps>::get_curly_H(x);
-	       dI4 += 4.0*is_tps<tps>::get_dI4(x);
-	}
-
-	Drift(dL2, x);
-        thin_kick(M->Porder, M->PB, dkL1, M->Pirho, h_ref, x);
-	Drift(dL1, x);
-
-	if (globval.emittance && (!globval.Cavity_on) && (M->Pirho != 0.0)) {
-	  dcurly_H += is_tps<tps>::get_curly_H(x);
-	       dI4 += is_tps<tps>::get_dI4(x);
-	}
-      }
-
-      if (globval.emittance && (!globval.Cavity_on) && (M->Pirho != 0)) {
-	dcurly_H /= 6.0*M->PN;
-	     dI4 *= M->Pirho*(sqr(M->Pirho)+2.0*M->PBpar[Quad+HOMmax])/(6.0*M->PN);
-
-	I2 += elemp->PL*sqr(M->Pirho); I4 += elemp->PL*dI4;
-	I5 += elemp->PL*fabs(cube(M->Pirho))*dcurly_H;
-      }
-    } else
-      thin_kick(M->Porder, M->PB, 1.0, 0.0, 0.0, x);
+ b2
+ y = y0 -/+ ---------- (y0^3 + 3*x0^2*y0)
+ 12(1 + dP)
 
-    break;
-  }
+ b2
+ py = py0 -/+  ---------- (2*x0*y0*px0 - y0^2*py0 - x0^2*py0)
+ 4(1 + dP)
 
-  
-  if ((M->Pmethod == Meth_Second) || (M->Pmethod == Meth_Fourth)) 
-  {
-    /* fringe fields */
-    if (!globval.H_exact) 
-    {
-        if (M->Pirho != 0.0) 
-        EdgeFocus(M->Pirho, M->PTx2, M->Pgap, x);
-    } 
-    else 
-    {
-      bend_fringe(-M->Pirho, x); p_rot(M->PTx2, x);
-    }
-    if (globval.quad_fringe && (M->PB[Quad+HOMmax] != 0.0) &&  (M->quadFF2 == 1))
-      quad_fringe(-M->quadFFscaling*M->PB[Quad+HOMmax], x);
-  } 
+ dP = dP0;
 
-  /* Local -> Global */
-  LtoG(x, Cell.dS, Cell.dT, M->Pc0, M->Pc1, M->Ps1);
-} 
 
+ b2
+ tau = tau0 -/+ ----------- (y0^3*px - x0^3*py + 3*x0^2*y*py - 3*y0^2*x0*px)
+ 12(1 + dP)^2
 
-template<typename T>
-void Marker_Pass(CellType &Cell, ss_vect<T> &X)
-{
-  elemtype *elemp;
+ Input:
+ b2       = quadrupole strength
+ x        = input particle coordinates
 
-  elemp = &Cell.Elem;
-  /* Global -> Local */
-  GtoL(X, Cell.dS, Cell.dT, 0.0, 0.0, 0.0);
-  /* Local -> Global */
-  LtoG(X, Cell.dS, Cell.dT, 0.0, 0.0, 0.0);
-}
+ Output:
+ x    output particle coordinates
 
+ Return:
+ none
 
-/****************************************************************************
- * void Cav_Pass(CellType *Cell, double *X)
+ Global variables:
+ none
 
-   Purpose:
-       Tracking through a cavity
+ Specific functions:
+ none
 
-   Input:
-       Cell cavity element to track through
-       X    input coordinates
+ Comments:
+ Now in Tracy III, no definition "entrance" and "exit", when called in Mpole_pass,
+ first call with  M --> PB[quad+HOMmax], then
+ call with -M --> PB[quad+HOMmax]
 
-   Output:
-       X output coordinates
+ ****************************************************************************/
+template<typename T>
+void quad_fringe(double b2, ss_vect<T> &x) {
+    T u, ps;
 
-   Return:
-       none
+    u = b2 / (12.0 * (1.0 + x[delta_]));
+    ps = u / (1.0 + x[delta_]);
 
-   Global variables:
-       none
+    x[py_] /= 1.0 - 3.0 * u * sqr(x[y_]);
+    x[y_] -= u * cube(x[y_]);
 
-   Specific functions:
-       none
+    if (globval.Cavity_on)
+        x[ct_] -= ps * cube(x[y_]) * x[py_]; //-y^3*py
 
-   Comments:
-       none
+    x[px_] /= 1.0 + 3.0 * u * sqr(x[x_]); //+x^2
 
-****************************************************************************/
-template<typename T>
-void Cav_Pass(CellType &Cell, ss_vect<T> &X)
-{
-  elemtype    *elemp;
-  CavityType  *C;
-  T           delta;
+    if (globval.Cavity_on)
+        x[ct_] += ps * cube(x[x_]) * x[px_]; //+x^3*px
+
+    x[x_] += u * cube(x[x_]); //+x^3
+    u = u * 3.0;
+    ps = ps * 3.0;
+    x[y_] = exp(-u * sqr(x[x_])) * x[y_]; //+x^2*y
+    x[py_] = exp(u * sqr(x[x_])) * x[py_]; //+x^2*py
+    x[px_] += 2.0 * u * x[x_] * x[y_] * x[py_]; //+2*x*y*py
 
-  elemp = &Cell.Elem; C = elemp->C;
-  if (globval.Cavity_on && C->Pvolt != 0.0) {
-    delta = -C->Pvolt/(globval.Energy*1e9)
-            *sin(2.0*M_PI*C->Pfreq/c0*X[ct_]+C->phi);
-    X[delta_] += delta;
+    if (globval.Cavity_on)
+        x[ct_] -= ps * sqr(x[x_]) * x[y_] * x[py_]; // -3*x^2*y*py
 
-    if (globval.radiation) globval.dE -= is_double<T>::cst(delta);
+    x[x_] = exp(u * sqr(x[y_])) * x[x_]; //+x*y^2
+    x[px_] = exp(-u * sqr(x[y_])) * x[px_]; // -x^2*px-y^2*px
+    x[py_] -= 2.0 * u * x[y_] * x[x_] * x[px_]; //-2*x*y*px
 
-    if (globval.pathlength) X[ct_] -= C->Ph/C->Pfreq*c0;
-  }
+    if (globval.Cavity_on)
+        x[ct_] += ps * sqr(x[y_]) * x[x_] * x[px_]; // +3*y^2*x*px
 }
 
+/****************************************************************************/
+/* void Mpole_Pass(CellType &Cell, ss_vect<T> &x)
 
-template<typename T>
-inline void get_Axy(const WigglerType *W, const double z,
-		    ss_vect<T> &x, T AxoBrho[], T AyoBrho[])
+ Purpose:
+ multipole pass,for dipole, quadrupole,sextupole,decupole,etc
+ Using DA method.
 
-{
-  int     i;
-  double  ky, kz_n;
-  T       cx, cz, sx, sz, chy, shy;
+ Input:
 
-  for (i = 0; i <= 3; ++i) {
-    AxoBrho[i] = 0.0; AyoBrho[i] = 0.0;
-  }
+ Output:
 
-  for (i = 0; i < W->n_harm; i ++) {
-    kz_n = W->harm[i]*2.0*M_PI/W->lambda; ky = sqrt(sqr(W->kxV[i])+sqr(kz_n));
-    cx = cos(W->kxV[i]*x[x_]); sx = sin(W->kxV[i]*x[x_]);
-    chy = cosh(ky*x[y_]); shy = sinh(ky*x[y_]); sz = sin(kz_n*z);
 
-    AxoBrho[0] += W->BoBrhoV[i]/kz_n*cx*chy*sz;
-    AyoBrho[0] += W->BoBrhoV[i]*W->kxV[i]/(ky*kz_n)*sx*shy*sz;
+ Return:
+ none
 
-    // derivatives with respect to x
-    AxoBrho[1] -= W->BoBrhoV[i]*W->kxV[i]/kz_n*sx*chy*sz;
-    AyoBrho[1] += W->BoBrhoV[i]*sqr(W->kxV[i])/(ky*kz_n)*cx*shy*sz;
+ Global variables:
+ none
 
-    // derivatives with respect to y
-    AxoBrho[2] += W->BoBrhoV[i]*ky/kz_n*cx*shy*sz;
-    AyoBrho[2] += W->BoBrhoV[i]*W->kxV[i]/kz_n*sx*chy*sz;
+ Specific functions:
+ none
 
-    if (globval.radiation) {
-      cz = cos(kz_n*z);
-      // derivatives with respect to z
-      AxoBrho[3] += W->BoBrhoV[i]*cx*chy*cz;
-      AyoBrho[3] += W->BoBrhoV[i]*W->kxV[i]/ky*sx*shy*cz;
-    }
-  }
-}
+ Comments:
+ none
 
-/*
-template<typename T>
-inline void get_Axy_map(const FieldMapType *FM, const double z,
-			const ss_vect<T> &x, T AxoBrho[], T AyoBrho[])
-{
-  float  y, ax0, ax1, ax2, ay0, ay1, ay2;
-
-  const  float dy = 1e-3, dz = 1e-3;
-
-  y = is_double<T>::cst(x[y_]);
-
-  if ((z < FM->s_pos[1]) || (z > FM->s_pos[FM->n_s])) {
-    cout << scientific << setprecision(3)
-	 << "get_Axy_map: s out of range " << z << endl;
-    exit_(1);
-  }
-
-  if ((y < FM->y_pos[1]) || (y > FM->y_pos[FM->m_y])) {
-    cout << scientific << setprecision(3)
-	 << "get_Axy_map: y out of range " << y << endl;
-    exit_(1);
-  }
-
-  splin2(FM->y_pos, FM->s_pos, FM->AxoBrho, FM->AxoBrho2, FM->m_y, FM->n_s,
-	 y, z, &ax1);
-  AxoBrho[0] = FM->scl*ax1;
-
-  splin2(FM->y_pos, FM->s_pos, FM->AyoBrho, FM->AyoBrho2, FM->m_y, FM->n_s,
-	 y, z, &ay1);
-  AyoBrho[0] = FM->scl*ay1;
-
-  // derivatives with respect to x
-  AxoBrho[1] = FM->scl*0.0; AyoBrho[1] = FM->scl*0.0;
-
-  // derivatives with respect to y
-  splin2(FM->y_pos, FM->s_pos, FM->AxoBrho, FM->AxoBrho2, FM->m_y, FM->n_s,
-	 y+dy, z, &ax2);
-  splin2(FM->y_pos, FM->s_pos, FM->AxoBrho, FM->AxoBrho2, FM->m_y, FM->n_s,
-	 y-dy, z, &ax1);
-  splin2(FM->y_pos, FM->s_pos, FM->AxoBrho, FM->AxoBrho2, FM->m_y, FM->n_s,
-	 y, z, &ax0);
-  AxoBrho[2] =
-    (ax2-ax1)/(2.0*dy) + (ax2+ax1-2.0*ax0)/sqr(dy)*is_tps<T>::set_prm(y_+1);
-  AxoBrho[2] *= FM->scl;
-
-  splin2(FM->y_pos, FM->s_pos, FM->AyoBrho, FM->AyoBrho2, FM->m_y, FM->n_s,
-	 y+dy, z, &ay2);
-  splin2(FM->y_pos, FM->s_pos, FM->AyoBrho, FM->AyoBrho2, FM->m_y, FM->n_s,
-	 y-dy, z, &ay1);
-  splin2(FM->y_pos, FM->s_pos, FM->AyoBrho, FM->AyoBrho2, FM->m_y, FM->n_s,
-	 y, z, &ay0);
-  AyoBrho[2] =
-    (ay2-ay1)/(2.0*dy) + (ay2+ay1-2.0*ay0)/sqr(dy)*is_tps<T>::set_prm(y_+1);
-  AyoBrho[2] *= FM->scl;
-
-  if (globval.radiation) {
-    // derivatives with respect to z
-    splin2(FM->y_pos, FM->s_pos, FM->AxoBrho, FM->AxoBrho2, FM->m_y, FM->n_s,
-	   y, z+dz, &ax2);
-    splin2(FM->y_pos, FM->s_pos, FM->AxoBrho, FM->AxoBrho2, FM->m_y, FM->n_s,
-	   y, z-dz, &ax1);
-    AxoBrho[3] = (ax2-ax1)/(2.0*dz); AxoBrho[3] *= FM->scl;
-
-    splin2(FM->y_pos, FM->s_pos, FM->AyoBrho, FM->AyoBrho2, FM->m_y, FM->n_s,
-	   y, z+dz, &ay2);
-    splin2(FM->y_pos, FM->s_pos, FM->AyoBrho, FM->AyoBrho2, FM->m_y, FM->n_s,
-	   y, z-dz, &ay1);
-    AyoBrho[3] = (ay2-ay1)/(2.0*dz); AyoBrho[3] *= FM->scl;
-    if (false)
-      cout << fixed << setprecision(5)
-	   << setw(8) << z << setw(9) << is_double<T>::cst(AxoBrho[3]) << endl;
-  }
-}
-*/
+ ****************************************************************************/
 
 template<typename T>
-void Wiggler_pass_EF(const elemtype &elem, ss_vect<T> &x)
-{
-  // First order symplectic integrator for wiggler using expanded Hamiltonian
-
-  int     i, nstep = 0;
-  double  h, z;
-  T       AxoBrho[4], AyoBrho[4], psi, hodp, a12, a21, a22, det;
-  T       d1, d2, a11, c11, c12, c21, c22, x2, B[3];
-
-  switch (elem.Pkind) {
-  case Wigl:
-    nstep = elem.W->PN;
-    break;
-  case FieldMap:
-    nstep = elem.FM->n_step;
-    break;
-  default:
-    cout << "Wiggler_pass_EF: unknown element type" << endl;
-    exit_(1);
-    break;
-  }
-
-  h = elem.PL/nstep; z = 0.0;
-  for (i = 1; i <= nstep; ++i) {
-    switch (elem.Pkind) {
-    case Wigl:
-      get_Axy(elem.W, z, x, AxoBrho, AyoBrho);
-      break;
-    case FieldMap:
-//      get_Axy_map(elem.FM, z, x, AxoBrho, AyoBrho);
-      break;
-    default:
-      cout << "Wiggler_pass_EF: unknown element type" << endl;
-      exit_(1);
-      break;
+void Mpole_Pass(CellType &Cell, ss_vect<T> &x) {
+    int seg = 0;
+    double k = 0.0, dL = 0.0, dL1 = 0.0, dL2 = 0.0;
+    double dkL1 = 0.0, dkL2 = 0.0, h_ref = 0.0;
+    elemtype *elemp;
+    MpoleType *M;
+
+    elemp = &Cell.Elem;
+    M = elemp->M;
+
+    /* Global -> Local */
+    GtoL(x, Cell.dS, Cell.dT, M->Pc0, M->Pc1, M->Ps1);
+
+    if ((M->Pmethod == Meth_Second) || (M->Pmethod == Meth_Fourth)) { /* fringe fields */
+
+        if (globval.quad_fringe && (M->PB[Quad + HOMmax] != 0.0) && (M->quadFF1
+                == 1)) {
+            quad_fringe(M->quadFFscaling * M->PB[Quad + HOMmax], x);
+        }
+
+        if (!globval.H_exact) {
+            if (M->Pirho != 0.0)
+                EdgeFocus(M->Pirho, M->PTx1, M->Pgap, x);
+        } else {
+            p_rot(M->PTx1, x);
+            bend_fringe(M->Pirho, x);
+        }
     }
 
-    psi = 1.0 + x[delta_]; hodp = h/psi;
-    a11 = hodp*AxoBrho[1]; a12 = hodp*AyoBrho[1];
-    a21 = hodp*AxoBrho[2]; a22 = hodp*AyoBrho[2];
-    det = 1.0 - a11 - a22 + a11*a22 - a12*a21;
-    d1 = hodp*AxoBrho[0]*AxoBrho[1]; d2 = hodp*AxoBrho[0]*AxoBrho[2];
-    c11 = (1.0-a22)/det; c12 = a12/det; c21 = a21/det; c22 = (1.0-a11)/det;
-    x2 = c11*(x[px_]-d1) + c12*(x[py_]-d2);
-
-    x[py_] = c21*(x[px_]-d1) + c22*(x[py_]-d2); x[px_] = x2;
-    x[x_] += hodp*(x[px_]-AxoBrho[0]); x[y_] += hodp*x[py_];
-    x[ct_] += h*(sqr((x[px_]-AxoBrho[0])/psi)
-	      + sqr((x[py_]-AyoBrho[0])/psi))/2.0;
-
-    if (false)
-      cout << scientific << setprecision(3)
-	   << setw(8) << z
-	   << setw(11) << is_double<T>::cst(x[x_])
-	   << setw(11) << is_double<T>::cst(x[px_])
-	   << setw(11) << is_double<T>::cst(x[y_])
-	   << setw(11) << is_double<T>::cst(x[py_])
-	   << endl;
+    if (M->Pthick == thick) {
+        if (!globval.H_exact || ((M->PTx1 == 0.0) && (M->PTx2 == 0.0))) {// polar coordinates,curvilinear coordinates
+            h_ref = M->Pirho;
+            dL = elemp->PL / M->PN;
+        } else {// Cartesian coordinates
+            h_ref = 0.0;
+            if (M->Pirho == 0.0)
+                dL = elemp->PL / M->PN;
+            else
+                dL = 1.0 / M->Pirho * (sin(dtor(M->PTx1)) + sin(dtor(M->PTx2)))
+                        / M->PN;
+        }
+    }
 
-    if (globval.pathlength) x[ct_] += h;
+    switch (M->Pmethod) {
+
+    case Meth_Linear:
+
+    case Meth_First:
+        if (M->Pthick == thick) {
+            /* First Linear  */
+            //      LinTrans(5L, M->AU55, x);
+            k = M->PB[Quad + HOMmax];
+            /* retrieve normal quad component already in AU55 */
+            M->PB[Quad + HOMmax] = 0.0;
+            /* Kick w/o quad component */
+            thin_kick(M->Porder, M->PB, elemp->PL, 0.0, 0.0, x);
+            /* restore quad component */
+            M->PB[Quad + HOMmax] = k;
+            /* Second Linear */
+            //      LinTrans(5L, M->AD55, x);
+        } else
+            /* thin kick */
+            thin_kick(M->Porder, M->PB, 1.0, 0.0, 0.0, x);
+        break;
+
+    case Meth_Second:
+        cout << "Mpole_Pass: Meth_Second not supported" << endl;
+        exit_(0);
+        break;
+
+    case Meth_Fourth:
+        if (M->Pthick == thick) {
+            dL1 = c_1 * dL;
+            dL2 = c_2 * dL;
+            dkL1 = d_1 * dL;
+            dkL2 = d_2 * dL;
+
+            dcurly_H = 0.0;
+            dI4 = 0.0;
+            for (seg = 1; seg <= M->PN; seg++) {
+                if (globval.emittance && (!globval.Cavity_on) && (M->Pirho
+                        != 0.0)) {
+                    dcurly_H += is_tps<tps>::get_curly_H(x);
+                    dI4 += is_tps<tps>::get_dI4(x);
+                }
+
+                Drift(dL1, x);
+                thin_kick(M->Porder, M->PB, dkL1, M->Pirho, h_ref, x);
+                Drift(dL2, x);
+                thin_kick(M->Porder, M->PB, dkL2, M->Pirho, h_ref, x);
+
+                if (globval.emittance && (!globval.Cavity_on) && (M->Pirho
+                        != 0.0)) {
+                    dcurly_H += 4.0 * is_tps<tps>::get_curly_H(x);
+                    dI4 += 4.0 * is_tps<tps>::get_dI4(x);
+                }
+
+                Drift(dL2, x);
+                thin_kick(M->Porder, M->PB, dkL1, M->Pirho, h_ref, x);
+                Drift(dL1, x);
+
+                if (globval.emittance && (!globval.Cavity_on) && (M->Pirho
+                        != 0.0)) {
+                    dcurly_H += is_tps<tps>::get_curly_H(x);
+                    dI4 += is_tps<tps>::get_dI4(x);
+                }
+            }
+
+            if (globval.emittance && (!globval.Cavity_on) && (M->Pirho != 0)) {
+                dcurly_H /= 6.0 * M->PN;
+                dI4 *= M->Pirho * (sqr(M->Pirho) + 2.0
+                        * M->PBpar[Quad + HOMmax]) / (6.0 * M->PN);
+
+                I2 += elemp->PL * sqr(M->Pirho);
+                I4 += elemp->PL * dI4;
+                I5 += elemp->PL * fabs(cube(M->Pirho)) * dcurly_H;
+            }
+        } else
+            thin_kick(M->Porder, M->PB, 1.0, 0.0, 0.0, x);
+
+        break;
+    }
 
-    if (globval.radiation || globval.emittance) {
-      B[X_] = -AyoBrho[3]; B[Y_] = AxoBrho[3]; B[Z_] = AyoBrho[1] - AxoBrho[2];
-      radiate(x, h, 0.0, B);
+    if ((M->Pmethod == Meth_Second) || (M->Pmethod == Meth_Fourth)) {
+        /* fringe fields */
+        if (!globval.H_exact) {
+            if (M->Pirho != 0.0)
+                EdgeFocus(M->Pirho, M->PTx2, M->Pgap, x);
+        } else {
+            bend_fringe(-M->Pirho, x);
+            p_rot(M->PTx2, x);
+        }
+        if (globval.quad_fringe && (M->PB[Quad + HOMmax] != 0.0) && (M->quadFF2
+                == 1))
+            quad_fringe(-M->quadFFscaling * M->PB[Quad + HOMmax], x);
     }
 
-    z += h;
-  }
+    /* Local -> Global */
+    LtoG(x, Cell.dS, Cell.dT, M->Pc0, M->Pc1, M->Ps1);
 }
 
-
 template<typename T>
-inline void get_Axy2(const double z,
-		     const double kxV, const double kxH, const double kz,
-		     const double BoBrhoV, const double BoBrhoH,
-		     const double phi,
-		     ss_vect<T> &x, T AxoBrho[], T AyoBrho[])
-{
-  int  i;
-  T    cx, sx, cz1, cz2, sz1, sz2, chy, shy, kyH, kyV, chx, shx, cy, sy;
-
-  for (i = 0; i <= 3; ++i) {
-    AxoBrho[i] = 0.0; AyoBrho[i] = 0.0;
-  }
-
-  kyV = sqrt(sqr(kz)+sqr(kxV)); kyH = sqrt(sqr(kz)+sqr(kxH));
-  cx = cos(kxV*x[x_]); sx = sin(kxV*x[x_]);
-  cy = cos(kxH*x[y_]); sy = sin(kxH*x[y_]);
-  chx = cosh(kyH*x[x_]); shx = sinh(kyH*x[x_]);
-  chy = cosh(kyV*x[y_]); shy = sinh(kyV*x[y_]); 
-  sz1 = sin(kz*z); sz2 = sin(kz*z+phi);
-
-  AxoBrho[0] += BoBrhoV/kz*cx*chy*sz1;
-  AxoBrho[0] -= BoBrhoH*kxH/(kyH*kz)*shx*sy*sz2;
-  AyoBrho[0] += BoBrhoV*kxV/(kyV*kz)*sx*shy*sz1;
-  AyoBrho[0] -= BoBrhoH/kz*chx*cy*sz2;
-
-  /* derivatives with respect to x */
-  AxoBrho[1] -= BoBrhoV*kxV/kz*sx*chy*sz1;
-  AxoBrho[1] -= BoBrhoH*kxH/kz*chx*sy*sz2;
-  AyoBrho[1] += BoBrhoV*sqr(kxV)/(kyV*kz)*cx*shy*sz1;
-  AyoBrho[1] -= BoBrhoH*kyH/kz*shx*cy*sz2;
-
-  /* derivatives with respect to y */
-  AxoBrho[2] += BoBrhoV*kyV/kz*cx*shy*sz1;
-  AxoBrho[2] -= BoBrhoH*sqr(kxH)/(kyH*kz)*shx*cy*sz2;
-  AyoBrho[2] += BoBrhoV*kxV/kz*sx*chy*sz1;
-  AyoBrho[2] += BoBrhoH*kxH/kz*chx*sy*sz2;
-
-  if (globval.radiation) {
-    cz1 = cos(kz*z); cz2=cos(kz*z+phi);
-    /* derivatives with respect to z */
-    AxoBrho[3] += BoBrhoV*cx*chy*cz1;
-    AxoBrho[3] -= BoBrhoH*kxH/kyH*shx*sy*cz2;
-    AyoBrho[3] += BoBrhoV*kxV/kyV*sx*shy*cz1;
-    AyoBrho[3] -= BoBrhoH*chx*cy*cz2;
-  }
+void Marker_Pass(CellType &Cell, ss_vect<T> &X) {
+    elemtype *elemp;
+
+    elemp = &Cell.Elem;
+    /* Global -> Local */
+    GtoL(X, Cell.dS, Cell.dT, 0.0, 0.0, 0.0);
+    /* Local -> Global */
+    LtoG(X, Cell.dS, Cell.dT, 0.0, 0.0, 0.0);
 }
 
+/****************************************************************************
+ * void Cav_Pass(CellType *Cell, double *X)
 
-template<typename T>
-void Wiggler_pass_EF2(int nstep, double L, double kxV, double kxH, double kz, 
-		      double BoBrhoV, double BoBrhoH, double phi,
-		      ss_vect<T> &x)
-{
-  // First order symplectic integrator for wiggler using expanded Hamiltonian
-
-  int     i;
-  double  h, z;
-  T       hodp, B[3], px1, px2, px3, py1, py2, AxoBrho[4], AyoBrho[4], psi;
-  T       px = 0.0, py = 0.0;
+ Purpose:
+ Tracking through a cavity
 
-  h = L/nstep; z = 0.0;
-  for (i = 1; i <= nstep; ++i) { 
-    get_Axy2(z, kxV, kxH, kz, BoBrhoV, BoBrhoH, phi, x, AxoBrho, AyoBrho);
+ Input:
+ Cell cavity element to track through
+ X    input coordinates
 
-    psi = 1.0 + x[delta_]; hodp = h/psi;
+ Output:
+ X output coordinates
 
-    px1 = (x[px_]-(AxoBrho[0]*AxoBrho[1]+AyoBrho[0]*AyoBrho[1])*hodp)
-          *(1-AyoBrho[2]*hodp);
-    px2 = (x[py_]-(AxoBrho[0]*AxoBrho[2]+AyoBrho[0]*AyoBrho[2])*hodp)
-          *AyoBrho[1]*hodp;
-    px3 = (1-AxoBrho[1]*hodp)*(1-AyoBrho[2]*hodp)
-          - AxoBrho[2]*AyoBrho[1]*hodp*hodp;
+ Return:
+ none
 
-    py1 = (x[py_]-(AxoBrho[0]*AxoBrho[2]+AyoBrho[0]*AyoBrho[2])*hodp)
-          *(1-AxoBrho[1]*hodp);
-    py2 = (x[px_]-(AxoBrho[0]*AxoBrho[1]+AyoBrho[0]*AyoBrho[1])*hodp)
-          *AxoBrho[2]*hodp;
+ Global variables:
+ none
 
-    py = (py1+py2)/px3; px = (px1+px2)/px3;
-    x[x_] += hodp*(px-AxoBrho[0]); x[y_] += hodp*(py-AyoBrho[0]);
-    x[ct_] += h*(sqr((px-AxoBrho[0])/psi) + sqr((py-AyoBrho[0])/psi))/2.0;
+ Specific functions:
+ none
 
-    if (globval.pathlength) x[ct_] += h;
+ Comments:
+ none
 
-    if (globval.radiation || globval.emittance) {
-      B[X_] = -AyoBrho[3]; B[Y_] = AxoBrho[3]; B[Z_] = AyoBrho[1] - AxoBrho[2];
-      radiate(x, h, 0.0, B);
+ ****************************************************************************/
+template<typename T>
+void Cav_Pass(CellType &Cell, ss_vect<T> &X) {
+    elemtype *elemp;
+    CavityType *C;
+    T delta;
+
+    elemp = &Cell.Elem;
+    C = elemp->C;
+    if (globval.Cavity_on && C->Pvolt != 0.0) {
+        delta = -C->Pvolt / (globval.Energy * 1e9) * sin(2.0 * M_PI * C->Pfreq
+                / c0 * X[ct_] + C->phi);
+        X[delta_] += delta;
+
+        if (globval.radiation)
+            globval.dE -= is_double<T>::cst(delta);
+
+        if (globval.pathlength)
+            X[ct_] -= C->Ph / C->Pfreq * c0;
     }
+}
 
-    z += h;
-  }
+template<typename T>
+inline void get_Axy(const WigglerType *W, const double z, ss_vect<T> &x,
+        T AxoBrho[], T AyoBrho[])
+
+{
+    int i;
+    double ky, kz_n;
+    T cx, cz, sx, sz, chy, shy;
+
+    for (i = 0; i <= 3; ++i) {
+        AxoBrho[i] = 0.0;
+        AyoBrho[i] = 0.0;
+    }
 
-  x[px_] = px; x[py_] = py;
+    for (i = 0; i < W->n_harm; i++) {
+        kz_n = W->harm[i] * 2.0 * M_PI / W->lambda;
+        ky = sqrt(sqr(W->kxV[i]) + sqr(kz_n));
+        cx = cos(W->kxV[i] * x[x_]);
+        sx = sin(W->kxV[i] * x[x_]);
+        chy = cosh(ky * x[y_]);
+        shy = sinh(ky * x[y_]);
+        sz = sin(kz_n * z);
+
+        AxoBrho[0] += W->BoBrhoV[i] / kz_n * cx * chy * sz;
+        AyoBrho[0] += W->BoBrhoV[i] * W->kxV[i] / (ky * kz_n) * sx * shy * sz;
+
+        // derivatives with respect to x
+        AxoBrho[1] -= W->BoBrhoV[i] * W->kxV[i] / kz_n * sx * chy * sz;
+        AyoBrho[1] += W->BoBrhoV[i] * sqr(W->kxV[i]) / (ky * kz_n) * cx * shy
+                * sz;
+
+        // derivatives with respect to y
+        AxoBrho[2] += W->BoBrhoV[i] * ky / kz_n * cx * shy * sz;
+        AyoBrho[2] += W->BoBrhoV[i] * W->kxV[i] / kz_n * sx * chy * sz;
+
+        if (globval.radiation) {
+            cz = cos(kz_n * z);
+            // derivatives with respect to z
+            AxoBrho[3] += W->BoBrhoV[i] * cx * chy * cz;
+            AyoBrho[3] += W->BoBrhoV[i] * W->kxV[i] / ky * sx * shy * cz;
+        }
+    }
 }
 
+/*
+ template<typename T>
+ inline void get_Axy_map(const FieldMapType *FM, const double z,
+ const ss_vect<T> &x, T AxoBrho[], T AyoBrho[])
+ {
+ float  y, ax0, ax1, ax2, ay0, ay1, ay2;
+
+ const  float dy = 1e-3, dz = 1e-3;
+
+ y = is_double<T>::cst(x[y_]);
+
+ if ((z < FM->s_pos[1]) || (z > FM->s_pos[FM->n_s])) {
+ cout << scientific << setprecision(3)
+ << "get_Axy_map: s out of range " << z << endl;
+ exit_(1);
+ }
+
+ if ((y < FM->y_pos[1]) || (y > FM->y_pos[FM->m_y])) {
+ cout << scientific << setprecision(3)
+ << "get_Axy_map: y out of range " << y << endl;
+ exit_(1);
+ }
+
+ splin2(FM->y_pos, FM->s_pos, FM->AxoBrho, FM->AxoBrho2, FM->m_y, FM->n_s,
+ y, z, &ax1);
+ AxoBrho[0] = FM->scl*ax1;
+
+ splin2(FM->y_pos, FM->s_pos, FM->AyoBrho, FM->AyoBrho2, FM->m_y, FM->n_s,
+ y, z, &ay1);
+ AyoBrho[0] = FM->scl*ay1;
+
+ // derivatives with respect to x
+ AxoBrho[1] = FM->scl*0.0; AyoBrho[1] = FM->scl*0.0;
+
+ // derivatives with respect to y
+ splin2(FM->y_pos, FM->s_pos, FM->AxoBrho, FM->AxoBrho2, FM->m_y, FM->n_s,
+ y+dy, z, &ax2);
+ splin2(FM->y_pos, FM->s_pos, FM->AxoBrho, FM->AxoBrho2, FM->m_y, FM->n_s,
+ y-dy, z, &ax1);
+ splin2(FM->y_pos, FM->s_pos, FM->AxoBrho, FM->AxoBrho2, FM->m_y, FM->n_s,
+ y, z, &ax0);
+ AxoBrho[2] =
+ (ax2-ax1)/(2.0*dy) + (ax2+ax1-2.0*ax0)/sqr(dy)*is_tps<T>::set_prm(y_+1);
+ AxoBrho[2] *= FM->scl;
+
+ splin2(FM->y_pos, FM->s_pos, FM->AyoBrho, FM->AyoBrho2, FM->m_y, FM->n_s,
+ y+dy, z, &ay2);
+ splin2(FM->y_pos, FM->s_pos, FM->AyoBrho, FM->AyoBrho2, FM->m_y, FM->n_s,
+ y-dy, z, &ay1);
+ splin2(FM->y_pos, FM->s_pos, FM->AyoBrho, FM->AyoBrho2, FM->m_y, FM->n_s,
+ y, z, &ay0);
+ AyoBrho[2] =
+ (ay2-ay1)/(2.0*dy) + (ay2+ay1-2.0*ay0)/sqr(dy)*is_tps<T>::set_prm(y_+1);
+ AyoBrho[2] *= FM->scl;
+
+ if (globval.radiation) {
+ // derivatives with respect to z
+ splin2(FM->y_pos, FM->s_pos, FM->AxoBrho, FM->AxoBrho2, FM->m_y, FM->n_s,
+ y, z+dz, &ax2);
+ splin2(FM->y_pos, FM->s_pos, FM->AxoBrho, FM->AxoBrho2, FM->m_y, FM->n_s,
+ y, z-dz, &ax1);
+ AxoBrho[3] = (ax2-ax1)/(2.0*dz); AxoBrho[3] *= FM->scl;
+
+ splin2(FM->y_pos, FM->s_pos, FM->AyoBrho, FM->AyoBrho2, FM->m_y, FM->n_s,
+ y, z+dz, &ay2);
+ splin2(FM->y_pos, FM->s_pos, FM->AyoBrho, FM->AyoBrho2, FM->m_y, FM->n_s,
+ y, z-dz, &ay1);
+ AyoBrho[3] = (ay2-ay1)/(2.0*dz); AyoBrho[3] *= FM->scl;
+ if (false)
+ cout << fixed << setprecision(5)
+ << setw(8) << z << setw(9) << is_double<T>::cst(AxoBrho[3]) << endl;
+ }
+ }
+ */
 
 template<typename T>
-inline void get_Axy_EF3(const WigglerType *W, const double z,
-		       const ss_vect<T> &x,
-		       T &AoBrho, T dAoBrho[], T &dp, const bool hor) 
-{
-  int     i;
-  double  ky, kz_n;
-  T       cx, sx, sz, chy, shy, cz;
+void Wiggler_pass_EF(const elemtype &elem, ss_vect<T> &x) {
+    // First order symplectic integrator for wiggler using expanded Hamiltonian
 
-  AoBrho = 0.0; dp = 0.0;
+    int i, nstep = 0;
+    double h, z;
+    T AxoBrho[4], AyoBrho[4], psi, hodp, a12, a21, a22, det;
+    T d1, d2, a11, c11, c12, c21, c22, x2, B[3];
 
-  for (i = 0; i < 3; i++)
-    dAoBrho[i] = 0.0;
+    switch (elem.Pkind) {
+    case Wigl:
+        nstep = elem.W->PN;
+        break;
+    case FieldMap:
+        nstep = elem.FM->n_step;
+        break;
+    default:
+        cout << "Wiggler_pass_EF: unknown element type" << endl;
+        exit_(1);
+        break;
+    }
 
-  for (i = 0; i < W->n_harm; i++) {
-    kz_n = W->harm[i]*2.0*M_PI/W->lambda; ky = sqrt(sqr(W->kxV[i])+sqr(kz_n));
+    h = elem.PL / nstep;
+    z = 0.0;
+    for (i = 1; i <= nstep; ++i) {
+        switch (elem.Pkind) {
+        case Wigl:
+            get_Axy(elem.W, z, x, AxoBrho, AyoBrho);
+            break;
+        case FieldMap:
+            //      get_Axy_map(elem.FM, z, x, AxoBrho, AyoBrho);
+            break;
+        default:
+            cout << "Wiggler_pass_EF: unknown element type" << endl;
+            exit_(1);
+            break;
+        }
+
+        psi = 1.0 + x[delta_];
+        hodp = h / psi;
+        a11 = hodp * AxoBrho[1];
+        a12 = hodp * AyoBrho[1];
+        a21 = hodp * AxoBrho[2];
+        a22 = hodp * AyoBrho[2];
+        det = 1.0 - a11 - a22 + a11 * a22 - a12 * a21;
+        d1 = hodp * AxoBrho[0] * AxoBrho[1];
+        d2 = hodp * AxoBrho[0] * AxoBrho[2];
+        c11 = (1.0 - a22) / det;
+        c12 = a12 / det;
+        c21 = a21 / det;
+        c22 = (1.0 - a11) / det;
+        x2 = c11 * (x[px_] - d1) + c12 * (x[py_] - d2);
+
+        x[py_] = c21 * (x[px_] - d1) + c22 * (x[py_] - d2);
+        x[px_] = x2;
+        x[x_] += hodp * (x[px_] - AxoBrho[0]);
+        x[y_] += hodp * x[py_];
+        x[ct_] += h * (sqr((x[px_] - AxoBrho[0]) / psi) + sqr((x[py_]
+                - AyoBrho[0]) / psi)) / 2.0;
+
+        if (false)
+            cout << scientific << setprecision(3) << setw(8) << z << setw(11)
+                    << is_double<T>::cst(x[x_]) << setw(11)
+                    << is_double<T>::cst(x[px_]) << setw(11)
+                    << is_double<T>::cst(x[y_]) << setw(11)
+                    << is_double<T>::cst(x[py_]) << endl;
+
+        if (globval.pathlength)
+            x[ct_] += h;
+
+        if (globval.radiation || globval.emittance) {
+            B[X_] = -AyoBrho[3];
+            B[Y_] = AxoBrho[3];
+            B[Z_] = AyoBrho[1] - AxoBrho[2];
+            radiate(x, h, 0.0, B);
+        }
+
+        z += h;
+    }
+}
 
-    cx  = cos(W->kxV[i]*x[x_]); sx = sin(W->kxV[i]*x[x_]);
-    chy = cosh(ky*x[y_]); shy = sinh(ky*x[y_]); sz = sin(kz_n*z);
+template<typename T>
+inline void get_Axy2(const double z, const double kxV, const double kxH,
+        const double kz, const double BoBrhoV, const double BoBrhoH,
+        const double phi, ss_vect<T> &x, T AxoBrho[], T AyoBrho[]) {
+    int i;
+    T cx, sx, cz1, cz2, sz1, sz2, chy, shy, kyH, kyV, chx, shx, cy, sy;
+
+    for (i = 0; i <= 3; ++i) {
+        AxoBrho[i] = 0.0;
+        AyoBrho[i] = 0.0;
+    }
 
-    if (hor) {
-      // A_x/Brho
-      AoBrho += W->BoBrhoV[i]/kz_n*cx*chy*sz;
+    kyV = sqrt(sqr(kz) + sqr(kxV));
+    kyH = sqrt(sqr(kz) + sqr(kxH));
+    cx = cos(kxV * x[x_]);
+    sx = sin(kxV * x[x_]);
+    cy = cos(kxH * x[y_]);
+    sy = sin(kxH * x[y_]);
+    chx = cosh(kyH * x[x_]);
+    shx = sinh(kyH * x[x_]);
+    chy = cosh(kyV * x[y_]);
+    shy = sinh(kyV * x[y_]);
+    sz1 = sin(kz * z);
+    sz2 = sin(kz * z + phi);
+
+    AxoBrho[0] += BoBrhoV / kz * cx * chy * sz1;
+    AxoBrho[0] -= BoBrhoH * kxH / (kyH * kz) * shx * sy * sz2;
+    AyoBrho[0] += BoBrhoV * kxV / (kyV * kz) * sx * shy * sz1;
+    AyoBrho[0] -= BoBrhoH / kz * chx * cy * sz2;
+
+    /* derivatives with respect to x */
+    AxoBrho[1] -= BoBrhoV * kxV / kz * sx * chy * sz1;
+    AxoBrho[1] -= BoBrhoH * kxH / kz * chx * sy * sz2;
+    AyoBrho[1] += BoBrhoV * sqr(kxV) / (kyV * kz) * cx * shy * sz1;
+    AyoBrho[1] -= BoBrhoH * kyH / kz * shx * cy * sz2;
+
+    /* derivatives with respect to y */
+    AxoBrho[2] += BoBrhoV * kyV / kz * cx * shy * sz1;
+    AxoBrho[2] -= BoBrhoH * sqr(kxH) / (kyH * kz) * shx * cy * sz2;
+    AyoBrho[2] += BoBrhoV * kxV / kz * sx * chy * sz1;
+    AyoBrho[2] += BoBrhoH * kxH / kz * chx * sy * sz2;
 
-      if (globval.radiation) {
-	cz = cos(kz_n*z);
-	dAoBrho[X_] -= W->BoBrhoV[i]*W->kxV[i]/kz_n*sx*chy*sz;
-	dAoBrho[Y_] += W->BoBrhoV[i]*ky/kz_n*cx*shy*sz;
-	dAoBrho[Z_] += W->BoBrhoV[i]*cx*chy*cz;
-      }
+    if (globval.radiation) {
+        cz1 = cos(kz * z);
+        cz2 = cos(kz * z + phi);
+        /* derivatives with respect to z */
+        AxoBrho[3] += BoBrhoV * cx * chy * cz1;
+        AxoBrho[3] -= BoBrhoH * kxH / kyH * shx * sy * cz2;
+        AyoBrho[3] += BoBrhoV * kxV / kyV * sx * shy * cz1;
+        AyoBrho[3] -= BoBrhoH * chx * cy * cz2;
+    }
+}
 
-      // dp_y
-      if (W->kxV[i] == 0.0)
-	dp += W->BoBrhoV[i]/kz_n*ky*x[x_]*shy*sz;
-      else
-	dp += W->BoBrhoV[i]/(W->kxV[i]*kz_n)*ky*sx*shy*sz;
-    } else {
-      // A_y/Brho
-      AoBrho += W->BoBrhoV[i]*W->kxV[i]/(ky*kz_n)*sx*shy*sz;
+template<typename T>
+void Wiggler_pass_EF2(int nstep, double L, double kxV, double kxH, double kz,
+        double BoBrhoV, double BoBrhoH, double phi, ss_vect<T> &x) {
+    // First order symplectic integrator for wiggler using expanded Hamiltonian
+
+    int i;
+    double h, z;
+    T hodp, B[3], px1, px2, px3, py1, py2, AxoBrho[4], AyoBrho[4], psi;
+    T px = 0.0, py = 0.0;
+
+    h = L / nstep;
+    z = 0.0;
+    for (i = 1; i <= nstep; ++i) {
+        get_Axy2(z, kxV, kxH, kz, BoBrhoV, BoBrhoH, phi, x, AxoBrho, AyoBrho);
+
+        psi = 1.0 + x[delta_];
+        hodp = h / psi;
+
+        px1 = (x[px_] - (AxoBrho[0] * AxoBrho[1] + AyoBrho[0] * AyoBrho[1])
+                * hodp) * (1 - AyoBrho[2] * hodp);
+        px2 = (x[py_] - (AxoBrho[0] * AxoBrho[2] + AyoBrho[0] * AyoBrho[2])
+                * hodp) * AyoBrho[1] * hodp;
+        px3 = (1 - AxoBrho[1] * hodp) * (1 - AyoBrho[2] * hodp) - AxoBrho[2]
+                * AyoBrho[1] * hodp * hodp;
+
+        py1 = (x[py_] - (AxoBrho[0] * AxoBrho[2] + AyoBrho[0] * AyoBrho[2])
+                * hodp) * (1 - AxoBrho[1] * hodp);
+        py2 = (x[px_] - (AxoBrho[0] * AxoBrho[1] + AyoBrho[0] * AyoBrho[1])
+                * hodp) * AxoBrho[2] * hodp;
+
+        py = (py1 + py2) / px3;
+        px = (px1 + px2) / px3;
+        x[x_] += hodp * (px - AxoBrho[0]);
+        x[y_] += hodp * (py - AyoBrho[0]);
+        x[ct_] += h * (sqr((px - AxoBrho[0]) / psi) + sqr((py - AyoBrho[0])
+                / psi)) / 2.0;
+
+        if (globval.pathlength)
+            x[ct_] += h;
+
+        if (globval.radiation || globval.emittance) {
+            B[X_] = -AyoBrho[3];
+            B[Y_] = AxoBrho[3];
+            B[Z_] = AyoBrho[1] - AxoBrho[2];
+            radiate(x, h, 0.0, B);
+        }
+
+        z += h;
+    }
 
-      if (globval.radiation) {
-	cz = cos(kz_n*z);
-	dAoBrho[X_] += W->BoBrhoV[i]*sqr(W->kxV[i])/(ky*kz_n)*cx*shy*sz;
-	dAoBrho[Y_] += W->BoBrhoV[i]*W->kxV[i]/kz_n*sx*chy*sz;
-	dAoBrho[Z_] += W->BoBrhoV[i]*W->kxV[i]/ky*sx*shy*cz;
-      }
+    x[px_] = px;
+    x[py_] = py;
+}
 
-      // dp_x
-      dp += W->BoBrhoV[i]/kz_n*sqr(W->kxV[i]/ky)*cx*chy*sz;
+template<typename T>
+inline void get_Axy_EF3(const WigglerType *W, const double z,
+        const ss_vect<T> &x, T &AoBrho, T dAoBrho[], T &dp, const bool hor) {
+    int i;
+    double ky, kz_n;
+    T cx, sx, sz, chy, shy, cz;
+
+    AoBrho = 0.0;
+    dp = 0.0;
+
+    for (i = 0; i < 3; i++)
+        dAoBrho[i] = 0.0;
+
+    for (i = 0; i < W->n_harm; i++) {
+        kz_n = W->harm[i] * 2.0 * M_PI / W->lambda;
+        ky = sqrt(sqr(W->kxV[i]) + sqr(kz_n));
+
+        cx = cos(W->kxV[i] * x[x_]);
+        sx = sin(W->kxV[i] * x[x_]);
+        chy = cosh(ky * x[y_]);
+        shy = sinh(ky * x[y_]);
+        sz = sin(kz_n * z);
+
+        if (hor) {
+            // A_x/Brho
+            AoBrho += W->BoBrhoV[i] / kz_n * cx * chy * sz;
+
+            if (globval.radiation) {
+                cz = cos(kz_n * z);
+                dAoBrho[X_] -= W->BoBrhoV[i] * W->kxV[i] / kz_n * sx * chy * sz;
+                dAoBrho[Y_] += W->BoBrhoV[i] * ky / kz_n * cx * shy * sz;
+                dAoBrho[Z_] += W->BoBrhoV[i] * cx * chy * cz;
+            }
+
+            // dp_y
+            if (W->kxV[i] == 0.0)
+                dp += W->BoBrhoV[i] / kz_n * ky * x[x_] * shy * sz;
+            else
+                dp += W->BoBrhoV[i] / (W->kxV[i] * kz_n) * ky * sx * shy * sz;
+        } else {
+            // A_y/Brho
+            AoBrho += W->BoBrhoV[i] * W->kxV[i] / (ky * kz_n) * sx * shy * sz;
+
+            if (globval.radiation) {
+                cz = cos(kz_n * z);
+                dAoBrho[X_] += W->BoBrhoV[i] * sqr(W->kxV[i]) / (ky * kz_n)
+                        * cx * shy * sz;
+                dAoBrho[Y_] += W->BoBrhoV[i] * W->kxV[i] / kz_n * sx * chy * sz;
+                dAoBrho[Z_] += W->BoBrhoV[i] * W->kxV[i] / ky * sx * shy * cz;
+            }
+
+            // dp_x
+            dp += W->BoBrhoV[i] / kz_n * sqr(W->kxV[i] / ky) * cx * chy * sz;
+        }
     }
-  }
 }
 
-
 template<typename T>
-void Wiggler_pass_EF3(const elemtype &elem, ss_vect<T> &x)
-{
-  /* Second order symplectic integrator for insertion devices based on:
+void Wiggler_pass_EF3(const elemtype &elem, ss_vect<T> &x) {
+    /* Second order symplectic integrator for insertion devices based on:
+
+     E. Forest, et al "Explicit Symplectic Integrator for s-dependent
+     Static Magnetic Field"                                                */
+
+    int i;
+    double h, z;
+    T hd, AxoBrho, AyoBrho, dAxoBrho[3], dAyoBrho[3], dpy, dpx, B[3];
 
-       E. Forest, et al "Explicit Symplectic Integrator for s-dependent
-       Static Magnetic Field"                                                */
+    h = elem.PL / elem.W->PN;
+    z = 0.0;
 
-  int     i;
-  double  h, z;
-  T       hd, AxoBrho, AyoBrho, dAxoBrho[3], dAyoBrho[3], dpy, dpx, B[3];
-  
-  h = elem.PL/elem.W->PN; z = 0.0;
+    for (i = 1; i <= elem.W->PN; i++) {
+        hd = h / (1.0 + x[delta_]);
 
-  for (i = 1; i <= elem.W->PN; i++) {
-    hd = h/(1.0+x[delta_]);
+        // 1: half step in z
+        z += 0.5 * h;
 
-    // 1: half step in z
-    z += 0.5*h;
+        // 2: half drift in y
+        get_Axy_EF3(elem.W, z, x, AyoBrho, dAyoBrho, dpx, false);
 
-    // 2: half drift in y
-    get_Axy_EF3(elem.W, z, x, AyoBrho, dAyoBrho, dpx, false);
+        x[px_] -= dpx;
+        x[py_] -= AyoBrho;
+        x[y_] += 0.5 * hd * x[py_];
+        x[ct_] += sqr(0.5) * hd * sqr(x[py_]) / (1.0 + x[delta_]);
 
-    x[px_] -= dpx; x[py_] -= AyoBrho;
-    x[y_] += 0.5*hd*x[py_];
-    x[ct_] += sqr(0.5)*hd*sqr(x[py_])/(1.0+x[delta_]);
+        get_Axy_EF3(elem.W, z, x, AyoBrho, dAyoBrho, dpx, false);
 
-    get_Axy_EF3(elem.W, z, x, AyoBrho, dAyoBrho, dpx, false);
+        x[px_] += dpx;
+        x[py_] += AyoBrho;
 
-    x[px_] += dpx; x[py_] += AyoBrho;
+        // 3: full drift in x
+        get_Axy_EF3(elem.W, z, x, AxoBrho, dAxoBrho, dpy, true);
 
-    // 3: full drift in x
-    get_Axy_EF3(elem.W, z, x, AxoBrho, dAxoBrho, dpy, true);
+        x[px_] -= AxoBrho;
+        x[py_] -= dpy;
+        x[x_] += hd * x[px_];
+        x[ct_] += 0.5 * hd * sqr(x[px_]) / (1.0 + x[delta_]);
 
-    x[px_] -= AxoBrho; x[py_] -= dpy; x[x_] += hd*x[px_];
-    x[ct_] += 0.5*hd*sqr(x[px_])/(1.0+x[delta_]);
+        if (globval.pathlength)
+            x[ct_] += h;
 
-    if (globval.pathlength) x[ct_] += h;
-   
-    get_Axy_EF3(elem.W, z, x, AxoBrho, dAxoBrho, dpy, true);
+        get_Axy_EF3(elem.W, z, x, AxoBrho, dAxoBrho, dpy, true);
 
-    x[px_] += AxoBrho; x[py_] += dpy;
+        x[px_] += AxoBrho;
+        x[py_] += dpy;
 
-    // 4: a half drift in y
-    get_Axy_EF3(elem.W, z, x, AyoBrho, dAyoBrho, dpx, false);
+        // 4: a half drift in y
+        get_Axy_EF3(elem.W, z, x, AyoBrho, dAyoBrho, dpx, false);
 
-    x[px_] -= dpx; x[py_] -= AyoBrho;
-    x[y_] += 0.5*hd*x[py_];
-    x[ct_] += sqr(0.5)*hd*sqr(x[py_])/(1.0+x[delta_]);
+        x[px_] -= dpx;
+        x[py_] -= AyoBrho;
+        x[y_] += 0.5 * hd * x[py_];
+        x[ct_] += sqr(0.5) * hd * sqr(x[py_]) / (1.0 + x[delta_]);
 
-    get_Axy_EF3(elem.W, z, x, AyoBrho, dAyoBrho, dpx, false);
+        get_Axy_EF3(elem.W, z, x, AyoBrho, dAyoBrho, dpx, false);
 
-    x[px_] += dpx; x[py_] += AyoBrho;
+        x[px_] += dpx;
+        x[py_] += AyoBrho;
 
-    // 5: half step in z
-    z += 0.5*h;
+        // 5: half step in z
+        z += 0.5 * h;
 
-    if (globval.radiation || globval.emittance) {
-      get_Axy_EF3(elem.W, z, x, AyoBrho, dAyoBrho, dpx, false);
-      get_Axy_EF3(elem.W, z, x, AxoBrho, dAxoBrho, dpy, true);
-      B[X_] = -dAyoBrho[Z_]; B[Y_] = dAxoBrho[Z_];
-      B[Z_] = dAyoBrho[X_] - dAxoBrho[Y_];
-      radiate(x, h, 0.0, B);
+        if (globval.radiation || globval.emittance) {
+            get_Axy_EF3(elem.W, z, x, AyoBrho, dAyoBrho, dpx, false);
+            get_Axy_EF3(elem.W, z, x, AxoBrho, dAxoBrho, dpy, true);
+            B[X_] = -dAyoBrho[Z_];
+            B[Y_] = dAxoBrho[Z_];
+            B[Z_] = dAyoBrho[X_] - dAxoBrho[Y_];
+            radiate(x, h, 0.0, B);
+        }
     }
-  }
 }
 
-
 template<typename T>
-void Wiggler_Pass(CellType &Cell, ss_vect<T> &X)
-{
-  int          seg;
-  double       L, L1, L2, K1, K2;
-  elemtype     *elemp;
-  WigglerType  *W;
-  ss_vect<T>   X1;
-
-  elemp = &Cell.Elem; W = elemp->W;
-  /* Global -> Local */
-  GtoL(X, Cell.dS, Cell.dT, 0.0, 0.0, 0.0);
-  switch (W->Pmethod) {
-
-  case Meth_Linear:
-//    LinTrans(5L, W->W55, X);
-    cout << "Wiggler_Pass: Meth_Linear not supported" << endl;
-    exit_(1);
-    break;
-
-  case Meth_First:
-    if ((W->BoBrhoV[0] != 0.0) || (W->BoBrhoH[0] != 0.0)) {
-      if (!globval.EPU)
-	Wiggler_pass_EF(Cell.Elem, X);
-      else {
-	Wiggler_pass_EF2(W->PN, elemp->PL, W->kxV[0], W->kxH[0],
-		2.0*M_PI/W->lambda, W->BoBrhoV[0], W->BoBrhoH[0],
-		W->phi[0], X);
-      }
-    } else
-      // drift if field = 0
-      Drift(elemp->PL, X);
-    break;
-
-  case Meth_Second:
-    if ((W->BoBrhoV[0] != 0.0) || (W->BoBrhoH[0] != 0.0)) {
-      Wiggler_pass_EF3(Cell.Elem, X);
-    } else
-      // drift if field = 0
-      Drift(elemp->PL, X);
-    break;
-
-  case Meth_Fourth:  /* 4-th order integrator */
-    L = elemp->PL/W->PN;
-    L1 = c_1*L; L2 = c_2*L; K1 = d_1*L; K2 = d_2*L;
-    for (seg = 1; seg <= W->PN; seg++) {
-      Drift(L1, X); X1 = X;
-      thin_kick(W->Porder, W->PBW, K1, 0.0, 0.0, X1);
-      X[py_] = X1[py_]; Drift(L2, X); X1 = X;
-      thin_kick(W->Porder, W->PBW, K2, 0.0, 0.0, X1);
-      X[py_] = X1[py_]; Drift(L2, X); X1 = X;
-      thin_kick(W->Porder, W->PBW, K1, 0.0, 0.0, X1);
-      X[py_] = X1[py_]; Drift(L1, X);
-    }
-    break;
-  }
-  /* Local -> Global */
-  LtoG(X, Cell.dS, Cell.dT, 0.0, 0.0, 0.0);
+void Wiggler_Pass(CellType &Cell, ss_vect<T> &X) {
+    int seg;
+    double L, L1, L2, K1, K2;
+    elemtype *elemp;
+    WigglerType *W;
+    ss_vect<T> X1;
+
+    elemp = &Cell.Elem;
+    W = elemp->W;
+    /* Global -> Local */
+    GtoL(X, Cell.dS, Cell.dT, 0.0, 0.0, 0.0);
+    switch (W->Pmethod) {
+
+    case Meth_Linear:
+        //    LinTrans(5L, W->W55, X);
+        cout << "Wiggler_Pass: Meth_Linear not supported" << endl;
+        exit_(1);
+        break;
+
+    case Meth_First:
+        if ((W->BoBrhoV[0] != 0.0) || (W->BoBrhoH[0] != 0.0)) {
+            if (!globval.EPU)
+                Wiggler_pass_EF(Cell.Elem, X);
+            else {
+                Wiggler_pass_EF2(W->PN, elemp->PL, W->kxV[0], W->kxH[0], 2.0
+                        * M_PI / W->lambda, W->BoBrhoV[0], W->BoBrhoH[0],
+                        W->phi[0], X);
+            }
+        } else
+            // drift if field = 0
+            Drift(elemp->PL, X);
+        break;
+
+    case Meth_Second:
+        if ((W->BoBrhoV[0] != 0.0) || (W->BoBrhoH[0] != 0.0)) {
+            Wiggler_pass_EF3(Cell.Elem, X);
+        } else
+            // drift if field = 0
+            Drift(elemp->PL, X);
+        break;
+
+    case Meth_Fourth: /* 4-th order integrator */
+        L = elemp->PL / W->PN;
+        L1 = c_1 * L;
+        L2 = c_2 * L;
+        K1 = d_1 * L;
+        K2 = d_2 * L;
+        for (seg = 1; seg <= W->PN; seg++) {
+            Drift(L1, X);
+            X1 = X;
+            thin_kick(W->Porder, W->PBW, K1, 0.0, 0.0, X1);
+            X[py_] = X1[py_];
+            Drift(L2, X);
+            X1 = X;
+            thin_kick(W->Porder, W->PBW, K2, 0.0, 0.0, X1);
+            X[py_] = X1[py_];
+            Drift(L2, X);
+            X1 = X;
+            thin_kick(W->Porder, W->PBW, K1, 0.0, 0.0, X1);
+            X[py_] = X1[py_];
+            Drift(L1, X);
+        }
+        break;
+    }
+    /* Local -> Global */
+    LtoG(X, Cell.dS, Cell.dT, 0.0, 0.0, 0.0);
 }
 
 #undef eps
 #undef kx
 
-
 template<typename T>
-void FieldMap_Pass(CellType &Cell, ss_vect<T> &X)
-{
+void FieldMap_Pass(CellType &Cell, ss_vect<T> &X) {
 
-  GtoL(X, Cell.dS, Cell.dT, 0.0, 0.0, 0.0);
+    GtoL(X, Cell.dS, Cell.dT, 0.0, 0.0, 0.0);
 
-  Wiggler_pass_EF(Cell.Elem, X);
+    Wiggler_pass_EF(Cell.Elem, X);
 
-  LtoG(X, Cell.dS, Cell.dT, 0.0, 0.0, 0.0);
+    LtoG(X, Cell.dS, Cell.dT, 0.0, 0.0, 0.0);
 }
 
-
 template<typename T>
-void Insertion_Pass(CellType &Cell, ss_vect<T> &x)
-{
-  /* Purpose:
-       Track vector x through an insertion
-       If radiation or cavity on insertion is like a drift
-
-   Input:
-       Cell element to track through
-       x initial coordinates vector
-
-   Output:
-       x final coordinates vector
-
-   Return:
-       none
-
-   Global variables:
-       none
-
-   Specific functions:
-       LinearInterpolation2
-       Drft
-       CopyVec
-
-   Comments:
-       Outside of interpolation table simulated by putting 1 in x[4]
-       01/07/03 6D tracking activated
-       10/01/05 First order kick part added                                  */
-
-  elemtype  *elemp;
-  double    LN = 0.0;
-  T         tx1, tz1;      /* thetax and thetaz retrieved from
-			      interpolation routine */
-  T         tx2, tz2;      /* thetax and thetaz retrieved from
-			      interpolation routine */
-  T         d;
-  double    alpha0 = 0.0;  // 1/ brh0
-  double    alpha02= 0.0;  // alpha square
-  int       Nslice = 0;
-  int       i = 0;
-  bool      outoftable = false;
-     
-  elemp  = &Cell.Elem; Nslice = elemp->ID->PN;
-  alpha0 = c0/globval.Energy*1E-9*elemp->ID->scaling; alpha02= alpha0*alpha0;
-  
-//  /* Global -> Local */
-//  GtoL(X, Cell->dS, Cell->dT, 0.0, 0.0, 0.0);
-
-  // (Nslice+1) drifts, nslice kicks
-  LN = elemp->PL/(Nslice+1);
-  Drift(LN, x);
-
-  for (i = 1; i <= Nslice; i++) {
-    // First order kick
-    if (elemp->ID->firstorder) {
-      if (!elemp->ID->linear){
-    	//cout << "InsertionPass: Spline\n";
-        SplineInterpolation2(x[x_], x[y_], tx1, tz1, Cell, outoftable);}
-      else
-        LinearInterpolation2(x[x_], x[y_], tx1, tz1, Cell, outoftable, 1);
-      if (outoftable) {
-	x[x_] = 1e30;
-        return;
-      }
-
-      d = alpha0/Nslice; x[px_] += d*tx1; x[py_] += d*tz1;
-    } 
-      
-    // Second order kick
-    if (elemp->ID->secondorder){
-      if (!elemp->ID->linear){
-    	//cout << "InsertionPass: Spline\n";
-        SplineInterpolation2(x[x_], x[y_], tx2, tz2, Cell, outoftable);}
-      else{
-      	//cout << "InsertionPass: Linear\n";
-        LinearInterpolation2(x[x_], x[y_], tx2, tz2, Cell, outoftable, 2);}
-      if (outoftable) {
-	x[x_] = 1e30;
-        return;
-      }
-
-      d = alpha02/Nslice/(1.0+x[delta_]); x[px_] += d*tx2; x[py_] += d*tz2;
-    }  
+void Insertion_Pass(CellType &Cell, ss_vect<T> &x) {
+    /* Purpose:
+     Track vector x through an insertion
+     If radiation or cavity on insertion is like a drift
+
+     Input:
+     Cell element to track through
+     x initial coordinates vector
+
+     Output:
+     x final coordinates vector
+
+     Return:
+     none
+
+     Global variables:
+     none
+
+     Specific functions:
+     LinearInterpolation2
+     Drft
+     CopyVec
+
+     Comments:
+     Outside of interpolation table simulated by putting 1 in x[4]
+     01/07/03 6D tracking activated
+     10/01/05 First order kick part added                                  */
+
+    elemtype *elemp;
+    double LN = 0.0;
+    T tx1, tz1; /* thetax and thetaz retrieved from
+     interpolation routine First order kick*/
+    T tx2, tz2; /* thetax and thetaz retrieved from
+     interpolation routine Second order Kick */
+    T d;
+    double alpha0 = 0.0; // 1/ brh0
+    double alpha02 = 0.0; // alpha square
+    int Nslice = 0;
+    int i = 0;
+    bool outoftable = false;
+
+    elemp = &Cell.Elem;
+    Nslice = elemp->ID->PN;
+    alpha0 = c0 / globval.Energy * 1E-9 * elemp->ID->scaling1;
+    alpha02 = (c0 / globval.Energy * 1E-9) * (c0 / globval.Energy * 1E-9)
+            * elemp->ID->scaling2;
+
+    //  /* Global -> Local */
+    //  GtoL(X, Cell->dS, Cell->dT, 0.0, 0.0, 0.0);
+
+    // (Nslice+1) drifts, n slice kicks
+    LN = elemp->PL / (Nslice + 1);
     Drift(LN, x);
-  }
-//  CopyVec(6L, x, Cell->BeamPos);
-  
-//  /* Local -> Global */
-//  LtoG(X, Cell->dS, Cell->dT, 0.0, 0.0, 0.0);
-}
 
+    for (i = 1; i <= Nslice; i++) {
+        // First order kick map
+        if (elemp->ID->firstorder) {
+            if (!elemp->ID->linear) {
+                //cout << "InsertionPass: Spline\n";
+                SplineInterpolation2(x[x_], x[y_], tx1, tz1, Cell, outoftable,
+                        1);
+            } else{
+                LinearInterpolation2(x[x_], x[y_], tx1, tz1, Cell, outoftable,
+                        1);
+            }
+            if (outoftable) {
+                x[x_] = 1e30;
+                return;
+            }
+
+            d = alpha0 / Nslice;
+            x[px_] += d * tx1;
+            x[py_] += d * tz1;
+        }
+
+        // Second order kick map
+        if (elemp->ID->secondorder) {
+            if (!elemp->ID->linear) {
+                //cout << "InsertionPass: Spline\n";
+                SplineInterpolation2(x[x_], x[y_], tx2, tz2, Cell, outoftable,
+                        2);
+            } else {
+                //cout << "InsertionPass: Linear\n";
+                LinearInterpolation2(x[x_], x[y_], tx2, tz2, Cell, outoftable,
+                        2);
+            }
+            if (outoftable) {
+                x[x_] = 1e30;
+                return;
+            }
+
+            d = alpha02 / Nslice / (1.0 + x[delta_]);
+            x[px_] += d * tx2;
+            x[py_] += d * tz2;
+        }
+        Drift(LN, x);
+    }
+    //  CopyVec(6L, x, Cell->BeamPos);
+
+    //  /* Local -> Global */
+    //  LtoG(X, Cell->dS, Cell->dT, 0.0, 0.0, 0.0);
+}
 
 template<typename T>
-void sol_pass(const elemtype &elem, ss_vect<T> &x)
-{
-  int     i;
-  double  h, z;
-  T       hd, AxoBrho, AyoBrho, dAxoBrho[3], dAyoBrho[3], dpy, dpx, B[3];
-  
-  h = elem.PL/elem.Sol->N; z = 0.0;
+void sol_pass(const elemtype &elem, ss_vect<T> &x) {
+    int i;
+    double h, z;
+    T hd, AxoBrho, AyoBrho, dAxoBrho[3], dAyoBrho[3], dpy, dpx, B[3];
+
+    h = elem.PL / elem.Sol->N;
+    z = 0.0;
+
+    for (i = 1; i <= elem.Sol->N; i++) {
+        hd = h / (1.0 + x[delta_]);
+
+        // 1: half step in z
+        z += 0.5 * h;
+
+        // 2: half drift in y
+        AyoBrho = elem.Sol->BoBrho * x[x_] / 2.0;
+        dpx = elem.Sol->BoBrho * x[y_] / 2.0;
+        //    get_Axy_EF3(elem.W, z, x, AyoBrho, dAyoBrho, dpx, false);
+
+        x[px_] -= dpx;
+        x[py_] -= AyoBrho;
+        x[y_] += 0.5 * hd * x[py_];
+        x[ct_] += sqr(0.5) * hd * sqr(x[py_]) / (1.0 + x[delta_]);
+
+        AyoBrho = elem.Sol->BoBrho * x[x_] / 2.0;
+        dpx = elem.Sol->BoBrho * x[y_] / 2.0;
+        //    get_Axy_EF3(elem.W, z, x, AyoBrho, dAyoBrho, dpx, false);
+
+        x[px_] += dpx;
+        x[py_] += AyoBrho;
+
+        // 3: full drift in x
+        AxoBrho = -elem.Sol->BoBrho * x[y_] / 2.0;
+        dpy = -elem.Sol->BoBrho * x[x_] / 2.0;
+        //    get_Axy_EF3(elem.W, z, x, AxoBrho, dAxoBrho, dpy, true);
+
+        x[px_] -= AxoBrho;
+        x[py_] -= dpy;
+        x[x_] += hd * x[px_];
+        x[ct_] += 0.5 * hd * sqr(x[px_]) / (1.0 + x[delta_]);
+
+        if (globval.pathlength)
+            x[ct_] += h;
+
+        AxoBrho = -elem.Sol->BoBrho * x[y_] / 2.0;
+        dpy = -elem.Sol->BoBrho * x[x_] / 2.0;
+        //    get_Axy_EF3(elem.W, z, x, AxoBrho, dAxoBrho, dpy, true);
+
+        x[px_] += AxoBrho;
+        x[py_] += dpy;
+
+        // 4: a half drift in y
+        AyoBrho = elem.Sol->BoBrho * x[x_] / 2.0;
+        dpx = elem.Sol->BoBrho * x[y_] / 2.0;
+        //    get_Axy_EF3(elem.W, z, x, AyoBrho, dAyoBrho, dpx, false);
+
+        x[px_] -= dpx;
+        x[py_] -= AyoBrho;
+        x[y_] += 0.5 * hd * x[py_];
+        x[ct_] += sqr(0.5) * hd * sqr(x[py_]) / (1.0 + x[delta_]);
+
+        AyoBrho = elem.Sol->BoBrho * x[x_] / 2.0;
+        dpx = elem.Sol->BoBrho * x[y_] / 2.0;
+        //    get_Axy_EF3(elem.W, z, x, AyoBrho, dAyoBrho, dpx, false);
+
+        x[px_] += dpx;
+        x[py_] += AyoBrho;
+
+        // 5: half step in z
+        z += 0.5 * h;
+
+        if (globval.radiation || globval.emittance) {
+            dAxoBrho[X_] = 0.0;
+            dAxoBrho[Y_] = -elem.Sol->BoBrho / 2.0;
+            dAxoBrho[Z_] = 0.0;
+            dAyoBrho[X_] = elem.Sol->BoBrho / 2.0;
+            dAyoBrho[Y_] = 0.0;
+            dAyoBrho[Z_] = 0.0;
+            //      get_Axy_EF3(elem.W, z, x, AyoBrho, dAyoBrho, dpx, false);
+            //      get_Axy_EF3(elem.W, z, x, AxoBrho, dAxoBrho, dpy, true);
+            B[X_] = -dAyoBrho[Z_];
+            B[Y_] = dAxoBrho[Z_];
+            B[Z_] = dAyoBrho[X_] - dAxoBrho[Y_];
+            radiate(x, h, 0.0, B);
+        }
+    }
+}
 
-  for (i = 1; i <= elem.Sol->N; i++) {
-    hd = h/(1.0+x[delta_]);
+template<typename T>
+void Solenoid_Pass(CellType &Cell, ss_vect<T> &ps) {
 
-    // 1: half step in z
-    z += 0.5*h;
+    GtoL(ps, Cell.dS, Cell.dT, 0.0, 0.0, 0.0);
 
-    // 2: half drift in y
-    AyoBrho = elem.Sol->BoBrho*x[x_]/2.0; dpx = elem.Sol->BoBrho*x[y_]/2.0;
-//    get_Axy_EF3(elem.W, z, x, AyoBrho, dAyoBrho, dpx, false);
+    sol_pass(Cell.Elem, ps);
 
-    x[px_] -= dpx; x[py_] -= AyoBrho;
-    x[y_] += 0.5*hd*x[py_];
-    x[ct_] += sqr(0.5)*hd*sqr(x[py_])/(1.0+x[delta_]);
+    LtoG(ps, Cell.dS, Cell.dT, 0.0, 0.0, 0.0);
+}
 
-    AyoBrho = elem.Sol->BoBrho*x[x_]/2.0; dpx = elem.Sol->BoBrho*x[y_]/2.0;
-//    get_Axy_EF3(elem.W, z, x, AyoBrho, dAyoBrho, dpx, false);
+// Matrix model
 
-    x[px_] += dpx; x[py_] += AyoBrho;
+void GtoL_M(Matrix &X, Vector2 &T) {
+    Matrix R;
+
+    /* Rotate */
+    R[0][0] = T[0];
+    R[0][1] = 0.0;
+    R[0][2] = T[1];
+    R[0][3] = 0.0;
+    R[1][0] = 0.0;
+    R[1][1] = T[0];
+    R[1][2] = 0.0;
+    R[1][3] = T[1];
+    R[2][0] = -T[1];
+    R[2][1] = 0.0;
+    R[2][2] = T[0];
+    R[2][3] = 0.0;
+    R[3][0] = 0.0;
+    R[3][1] = -T[1];
+    R[3][2] = 0.0;
+    R[3][3] = T[0];
+    MulLMat(4L, R, X);
+}
 
-    // 3: full drift in x
-    AxoBrho = -elem.Sol->BoBrho*x[y_]/2.0; dpy = -elem.Sol->BoBrho*x[x_]/2.0;
-//    get_Axy_EF3(elem.W, z, x, AxoBrho, dAxoBrho, dpy, true);
+void LtoG_M(Matrix &X, Vector2 &T) {
+    Matrix R;
+
+    /* Rotate */
+    R[0][0] = T[0];
+    R[0][1] = 0.0;
+    R[0][2] = -T[1];
+    R[0][3] = 0.0;
+    R[1][0] = 0.0;
+    R[1][1] = T[0];
+    R[1][2] = 0.0;
+    R[1][3] = -T[1];
+    R[2][0] = T[1];
+    R[2][1] = 0.0;
+    R[2][2] = T[0];
+    R[2][3] = 0.0;
+    R[3][0] = 0.0;
+    R[3][1] = T[1];
+    R[3][2] = 0.0;
+    R[3][3] = T[0];
+    MulLMat(4, R, X);
+}
 
-    x[px_] -= AxoBrho; x[py_] -= dpy; x[x_] += hd*x[px_];
-    x[ct_] += 0.5*hd*sqr(x[px_])/(1.0+x[delta_]);
+/****************************************************************************
+ * void Drift_Pass_M(CellType *Cell, double *xref, vector *x)
 
-    if (globval.pathlength) x[ct_] += h;
-   
-    AxoBrho = -elem.Sol->BoBrho*x[y_]/2.0; dpy = -elem.Sol->BoBrho*x[x_]/2.0;
-//    get_Axy_EF3(elem.W, z, x, AxoBrho, dAxoBrho, dpy, true);
+ Purpose:
+ matrix propagation through a drift
+ x   = D55*x
+ xref= drift(xref)
 
-    x[px_] += AxoBrho; x[py_] += dpy;
+ Input:
+ xref vector
+ x    matrix
 
-    // 4: a half drift in y
-    AyoBrho = elem.Sol->BoBrho*x[x_]/2.0; dpx = elem.Sol->BoBrho*x[y_]/2.0;
-//    get_Axy_EF3(elem.W, z, x, AyoBrho, dAyoBrho, dpx, false);
+ Output:
+ xref
+ x
 
-    x[px_] -= dpx; x[py_] -= AyoBrho;
-    x[y_] += 0.5*hd*x[py_];
-    x[ct_] += sqr(0.5)*hd*sqr(x[py_])/(1.0+x[delta_]);
+ Return:
+ none
 
-    AyoBrho = elem.Sol->BoBrho*x[x_]/2.0; dpx = elem.Sol->BoBrho*x[y_]/2.0;
-//    get_Axy_EF3(elem.W, z, x, AyoBrho, dAyoBrho, dpx, false);
+ Global variables:
+ none
 
-    x[px_] += dpx; x[py_] += AyoBrho;
+ Specific functions:
+ MulLMat, Drft
 
-    // 5: half step in z
-    z += 0.5*h;
+ Comments:
+ none
 
-    if (globval.radiation || globval.emittance) {
-      dAxoBrho[X_] = 0.0;
-      dAxoBrho[Y_] = -elem.Sol->BoBrho/2.0;
-      dAxoBrho[Z_] = 0.0;
-      dAyoBrho[X_] = elem.Sol->BoBrho/2.0;
-      dAyoBrho[Y_] = 0.0;
-      dAyoBrho[Z_] = 0.0;
-//      get_Axy_EF3(elem.W, z, x, AyoBrho, dAyoBrho, dpx, false);
-//      get_Axy_EF3(elem.W, z, x, AxoBrho, dAxoBrho, dpy, true);
-      B[X_] = -dAyoBrho[Z_]; B[Y_] = dAxoBrho[Z_];
-      B[Z_] = dAyoBrho[X_] - dAxoBrho[Y_];
-      radiate(x, h, 0.0, B);
-    }
-  }
-}
+ ****************************************************************************/
 
+void Drift_Pass_M(CellType &Cell, Vector &xref, Matrix &X) {
 
-template<typename T>
-void Solenoid_Pass(CellType &Cell, ss_vect<T> &ps)
-{
+    MulLMat(5, Cell.Elem.D->D55, X);
+    Drift(Cell.Elem.PL, xref);
+}
 
-  GtoL(ps, Cell.dS, Cell.dT, 0.0, 0.0, 0.0);
+void thin_kick_M(int Order, double MB[], double L, double irho, Vector &xref,
+        Matrix &x) {
+    int i;
+    mpolArray MMB;
+    Vector z;
+    Matrix Mk;
 
-  sol_pass(Cell.Elem, ps);
+    if (2 > Order || Order > HOMmax)
+        return;
+    for (i = 2; i <= Order; i++) {
+        MMB[i + HOMmax - 1] = (i - 1) * MB[i + HOMmax];
+        MMB[HOMmax - i + 1] = (i - 1) * MB[HOMmax - i];
+    }
+    z[0] = xref[0];
+    z[1] = 0.0;
+    z[2] = xref[2];
+    z[3] = 0.0;
+    z[4] = 0.0;
+    z[5] = 0.0;
+    thin_kick(Order - 1, MMB, L, 0.0, 0.0, z);
+    z[1] -= L * sqr(irho);
+    UnitMat(5L, Mk);
+    Mk[1][0] = z[1];
+    Mk[1][2] = z[3];
+    Mk[3][0] = z[3];
+    Mk[3][2] = -z[1];
+    MulLMat(5L, Mk, x);
+}
 
-  LtoG(ps, Cell.dS, Cell.dT, 0.0, 0.0, 0.0);
+static void make3by3(Matrix &A, double a11, double a12, double a13, double a21,
+        double a22, double a23, double a31, double a32, double a33) {
+    /*
+     Set the 3x3 matrix A to:
+     (a11 a12 a13)
+     A = (a21 a22 a23)
+     (a31 a32 a33)
+     */
+
+    UnitMat(ss_dim, A); /* set matrix to unit 3x3 matrix */
+    A[0][0] = a11;
+    A[0][1] = a12;
+    A[0][2] = a13;
+    A[1][0] = a21;
+    A[1][1] = a22;
+    A[1][2] = a23;
+    A[2][0] = a31;
+    A[2][1] = a32;
+    A[2][2] = a33;
 }
 
+/****************************************************************************
+ * void make4by5(vector *A, double a11, double a12, double a15,
+ double a21, double a22, double a25, double a33,
+ double a34, double a35, double a43, double a44,
+ double a45)
+ Purpose:
+ Constructor for matrix A
+ All the matrix terms  are explicitly given as input
+
+ Input:
+ A matrix to initialize
+ aij matrix terms
+
+ Output:
+ A initialized matrix
+
+ Return:
+ none
+
+ Global variables:
+ none
+
+ Specific functions:
+ UnitMat
+
+ Comments:
+ none
+
+ ****************************************************************************/
+
+static void make4by5(Matrix &A, double a11, double a12, double a15, double a21,
+        double a22, double a25, double a33, double a34, double a35, double a43,
+        double a44, double a45) {
+    UnitMat(ss_dim, A); /* Initializes A to identity matrix */
+    A[0][0] = a11;
+    A[0][1] = a12;
+    A[0][4] = a15;
+    A[1][0] = a21;
+    A[1][1] = a22;
+    A[1][4] = a25;
+    A[2][2] = a33;
+    A[2][3] = a34;
+    A[2][4] = a35;
+    A[3][2] = a43;
+    A[3][3] = a44;
+    A[3][4] = a45;
+}
 
-// Matrix model
+static void mergeto4by5(Matrix &A, Matrix &AH, Matrix &AV) {
+    /*
+     merges two 3x3 matrices AH (H-plane) and AV (V-plane) into one
+     big 4x5 matrix
+
+     (ah11 ah12    0    0    ah13)
+     (ah21 ah22    0    0    ah23)
+     A=  (  0    0   av11 av12   av13)
+     (  0    0   av21 av22   ah13)
+     (  0    0     0    0       1)
+     */
+    int i, j;
+
+    UnitMat(ss_dim, A);
+    for (i = 1; i <= 2; i++) {
+        A[i - 1][4] = AH[i - 1][2];
+        A[i + 1][4] = AV[i - 1][2];
+        for (j = 1; j <= 2; j++) {
+            A[i - 1][j - 1] = AH[i - 1][j - 1];
+            A[i + 1][j + 1] = AV[i - 1][j - 1];
+        }
+    }
+}
 
-void GtoL_M(Matrix &X, Vector2 &T)
-{
-  Matrix R;
+void Drift_SetMatrix(int Fnum1, int Knum1) {
+    /*
+     Make transport matrix for drift from
+     familiy Fnum1 and Kid number Knum
+     L = L / (1 + dP)
+
+     ( 1 L 0 0 0)
+     D55  =  ( 0 1 0 0 0)
+     ( 0 0 1 L 0)
+     ( 0 0 0 1 0)
+     */
+
+    double L;
+    CellType *cellp;
+    elemtype *elemp;
+    DriftType *D;
+
+    if (ElemFam[Fnum1 - 1].nKid <= 0)
+        return;
+    cellp = &Cell[ElemFam[Fnum1 - 1].KidList[Knum1 - 1]];
+    elemp = &cellp->Elem;
+    D = elemp->D;
+    L = elemp->PL / (1.0 + globval.dPparticle); /* L = L / (1 + dP) */
+    make4by5(D->D55, 1.0, L, 0.0, 0.0, 1.0, 0.0, 1.0, L, 0.0, 0.0, 1.0, 0.0);
+}
 
-  /* Rotate */
-  R[0][0] = T[0];  R[0][1] = 0.0;   R[0][2] = T[1]; R[0][3] = 0.0;
-  R[1][0] = 0.0;   R[1][1] = T[0];  R[1][2] = 0.0;  R[1][3] = T[1];
-  R[2][0] = -T[1]; R[2][1] = 0.0;   R[2][2] = T[0]; R[2][3] = 0.0;
-  R[3][0] = 0.0;   R[3][1] = -T[1]; R[3][2] = 0.0;  R[3][3] = T[0];
-  MulLMat(4L, R, X);
+static void driftmat(Matrix &ah, double L) {
+    L /= 1 + globval.dPparticle;
+    make4by5(ah, 1.0, L, 0.0, 0.0, 1.0, 0.0, 1.0, L, 0.0, 0.0, 1.0, 0.0);
 }
 
+static void quadmat(Matrix &ahv, double L, double k) {
+    /*
+     creates the avh matrix for a quadrupole
+     where av and ah are the horizontal and vertical
+     focusing or defocusing matrices
 
-void LtoG_M(Matrix &X, Vector2 &T)
-{
-  Matrix  R;
 
-  /* Rotate */
-  R[0][0] = T[0]; R[0][1] = 0.0;  R[0][2] = -T[1]; R[0][3] = 0.0;
-  R[1][0] = 0.0;  R[1][1] = T[0]; R[1][2] = 0.0;   R[1][3] = -T[1];
-  R[2][0] = T[1]; R[2][1] = 0.0;  R[2][2] = T[0];  R[2][3] = 0.0;
-  R[3][0] = 0.0;  R[3][1] = T[1]; R[3][2] = 0.0;   R[3][3] = T[0];
-  MulLMat(4, R, X);
-}
+     1/2                         1/2
+     cos(L* (|K|)   )            sin(L* (|K|)   )
+     c = ---------------          s = ---------------
+     1/2                         1/2
+     (1  + Dp)                    (1  + Dp)
+     1/2
+     sk = (|K|(1+dP))
 
+     - if k > 0
+     H plane                      V plane
 
-void Drift_Pass_M(CellType &Cell, Vector &xref, Matrix &X)
-{
+     (  c   s/sk 0 )              (   ch sh/k 0 )
+     ah = ( sk*s  c   0 )         av = ( sk*sh ch  0 )
+     (  0    0   1 )              (   0   0   1 )
 
-  MulLMat(5, Cell.Elem.D->D55, X); Drift(Cell.Elem.PL, xref);
-}
 
+     ( ah11 ah12    0    0    ah13 )
+     ( ah21 ah22    0    0    ah23 )
+     avh =  (  0    0    av11 av12   av13 )
+     (  0    0    av21 av22   ah13 )
+     (  0    0     0    0       1  )                     */
 
-void thin_kick_M(int Order, double MB[], double L, double irho,
-		 Vector &xref, Matrix &x)
-{
-  int        i;
-  mpolArray  MMB;
-  Vector     z;
-  Matrix     Mk;
-
-  if (2 > Order || Order > HOMmax)
-    return;
-  for (i = 2; i <= Order; i++) {
-    MMB[i+HOMmax-1] = (i-1)*MB[i+HOMmax]; MMB[HOMmax-i+1] = (i-1)*MB[HOMmax-i];
-  }
-  z[0] = xref[0]; z[1] = 0.0; z[2] = xref[2]; z[3] = 0.0;
-  z[4] = 0.0; z[5] = 0.0;
-  thin_kick(Order-1, MMB, L, 0.0, 0.0, z);
-  z[1] -= L*sqr(irho);
-  UnitMat(5L, Mk);
-  Mk[1][0] = z[1]; Mk[1][2] = z[3]; Mk[3][0] = z[3]; Mk[3][2] = -z[1];
-  MulLMat(5L, Mk, x);
-}
-
-
-static void make3by3(Matrix &A,
-		     double a11, double a12, double a13,
-		     double a21, double  a22, double a23,
-		     double a31, double a32, double a33)
-{
-  /*
-       Set the 3x3 matrix A to:
-                                     (a11 a12 a13)
-                                 A = (a21 a22 a23)
-                                     (a31 a32 a33)
-  */
-       
-  UnitMat(ss_dim, A);  /* set matrix to unit 3x3 matrix */
-  A[0][0] = a11; A[0][1] = a12; A[0][2] = a13;
-  A[1][0] = a21; A[1][1] = a22; A[1][2] = a23;
-  A[2][0] = a31; A[2][1] = a32; A[2][2] = a33;
-}
-
-
-static void make4by5(Matrix &A, double a11, double a12, double a15,
-                     double a21, double a22, double a25, double a33,
-                     double a34, double a35, double a43, double a44,
-                     double a45)
-{
-  UnitMat(ss_dim, A);  /* Initializes A to identity matrix */
-  A[0][0] = a11; A[0][1] = a12; A[0][4] = a15;
-  A[1][0] = a21; A[1][1] = a22; A[1][4] = a25;
-  A[2][2] = a33; A[2][3] = a34; A[2][4] = a35;
-  A[3][2] = a43; A[3][3] = a44; A[3][4] = a45;
+    double t, sk, sk0, s, c;
+    Matrix a, ah, av;
+
+    if (k == 0.0) {
+        /* pure drift focusing */
+        driftmat(ahv, L);
+        return;
+    }
+    sk0 = sqrt(fabs(k));
+    t = L * sk0 / sqrt(1.0 + globval.dPparticle);
+    c = cos(t);
+    s = sin(t);
+    sk = sk0 * sqrt(1.0 + globval.dPparticle);
+    make3by3(a, c, s / sk, 0.0, -sk * s, c, 0.0, 0.0, 0.0, 1.0);
+    if (k > 0.0)
+        CopyMat(3L, a, ah);
+    else
+        CopyMat(3L, a, av);
+    c = cosh(t);
+    s = sinh(t);
+    sk = sk0 * sqrt(1.0 + globval.dPparticle);
+    make3by3(a, c, s / sk, 0.0, sk * s, c, 0.0, 0.0, 0.0, 1.0);
+    if (k > 0.0)
+        CopyMat(3L, a, av);
+    else
+        CopyMat(3L, a, ah);
+    mergeto4by5(ahv, ah, av);
 }
 
+/****************************************************************************/
+/* static void bendmat(vector *M, double L, double irho, double phi1,
+ double phi2, double gap, double k)
 
-static void mergeto4by5(Matrix &A, Matrix &AH, Matrix &AV)
-{
-  /*
-       merges two 3x3 matrices AH (H-plane) and AV (V-plane) into one
-       big 4x5 matrix
+ Purpose:  called  by Mpole_Setmatrix
 
-                   (ah11 ah12    0    0    ah13)
-                   (ah21 ah22    0    0    ah23)
-               A=  (  0    0   av11 av12   av13)
-                   (  0    0   av21 av22   ah13)
-                   (  0    0     0    0       1)
-  */
-  int i, j;
+ For a quadrupole  see quadmat routine for explanation
 
-  UnitMat(ss_dim, A);
-  for (i = 1; i <= 2; i++) {
-    A[i-1][4] = AH[i-1][2]; A[i+1][4] = AV[i-1][2];
-    for (j = 1; j <= 2; j++) {
-      A[i-1][j-1] = AH[i-1][j-1]; A[i+1][j+1] = AV[i-1][j-1];
-    }
-  }
-}
+ For a dipole
 
+ (1            0 0)
+ Edge(theta) = (h*tan(theta) 1 0)
+ (0            0 1)
 
-void Drift_SetMatrix(int Fnum1, int Knum1)
-{
-  /*
-        Make transport matrix for drift from
-        familiy Fnum1 and Kid number Knum
-              L = L / (1 + dP)
-        
-                     ( 1 L 0 0 0)
-             D55  =  ( 0 1 0 0 0)
-                     ( 0 0 1 L 0)
-                     ( 0 0 0 1 0)
-  */
-
-  double    L;
-  CellType  *cellp;
-  elemtype  *elemp;
-  DriftType *D;
-
-  if (ElemFam[Fnum1-1].nKid <= 0) return;
-  cellp  = &Cell[ElemFam[Fnum1-1].KidList[Knum1-1]];
-  elemp = &cellp->Elem;
-  D = elemp->D;
-  L = elemp->PL/(1.0+globval.dPparticle);  /* L = L / (1 + dP) */
-  make4by5(D->D55,
-	   1.0, L, 0.0, 0.0, 1.0, 0.0,
-	   1.0, L, 0.0, 0.0, 1.0, 0.0);
-}
-
-
-static void driftmat(Matrix &ah, double L)
-{
-  L /= 1 + globval.dPparticle;
-  make4by5(ah,
-	   1.0, L, 0.0, 0.0, 1.0, 0.0,
-	   1.0, L, 0.0, 0.0, 1.0, 0.0);
-}
+ (1                 0 0)
+ Edge(theta) = (-h*tan(theta-psi) 1 0)
+ (0                 0 1)
 
+ 2
+ K1*gap*h*(1 + sin phi)
+ psi = -----------------------, K1 = 1/2
+ cos phi
 
-static void quadmat(Matrix &ahv, double L, double k)
-{
-  /*
-     creates the avh matrix for a quadrupole
-     where av and ah are the horizontal and vertical
-     focusing or defocusing matrices
-                     
-                     
-                            1/2                         1/2
-                cos(L* (|K|)   )            sin(L* (|K|)   )
-            c = ---------------          s = ---------------
-                          1/2                         1/2
-                 (1  + Dp)                    (1  + Dp)
-                            1/2
-            sk = (|K|(1+dP))     
-                
-        - if k > 0
-                  H plane                      V plane
-                  
-                (  c   s/sk 0 )              (   ch sh/k 0 )
-           ah = ( sk*s  c   0 )         av = ( sk*sh ch  0 )
-                (  0    0   1 )              (   0   0   1 )
-
-
-                         ( ah11 ah12    0    0    ah13 )
-                         ( ah21 ah22    0    0    ah23 )
-                  avh =  (  0    0    av11 av12   av13 )
-                         (  0    0    av21 av22   ah13 )
-                         (  0    0     0    0       1  )                     */
-                      
-  double t, sk, sk0, s, c;
-  Matrix a, ah, av;
-
-  if (k == 0.0) {
-    /* pure drift focusing */
-    driftmat(ahv, L);
-    return;
-  }
-  sk0 = sqrt(fabs(k));
-  t = L*sk0/sqrt(1.0+globval.dPparticle);
-  c = cos(t); s = sin(t);
-  sk = sk0*sqrt(1.0+globval.dPparticle);
-  make3by3(a, c, s/sk, 0.0, -sk*s, c, 0.0, 0.0, 0.0, 1.0);
-  if (k > 0.0)
-    CopyMat(3L, a, ah);
-  else
-    CopyMat(3L, a, av);
-  c  = cosh(t); s  = sinh(t);
-  sk = sk0*sqrt(1.0+globval.dPparticle);
-  make3by3(a, c, s/sk, 0.0, sk*s, c, 0.0, 0.0, 0.0, 1.0);
-  if (k > 0.0)
-    CopyMat(3L, a, av);
-  else
-    CopyMat(3L, a, ah);
-  mergeto4by5(ahv, ah, av);
-}
+ Input:
+ L   : length [m]
+ irho: 1/rho [1/m]
+ phi1: entrance edge angle [degres]
+ phi2: exit edge angle [degres]
+ K   : gradient = n/Rho
 
+ Output:
+ M transfer matrix
 
-/****************************************************************************/
-/* static void bendmat(vector *M, double L, double irho, double phi1,
-                    double phi2, double gap, double k)
+ Return:
+ none
 
-   Purpose:  called  by Mpole_Setmatrix
+ Global variables:
+ none
 
-       For a quadrupole  see quadmat routine for explanation
+ Specific functions:
+ quadmat, make3by3
+ UnitMat, MulRMat, psi
 
-       For a dipole
+ Comments:
+ none
 
-                         (1            0 0)
-           Edge(theta) = (h*tan(theta) 1 0)
-                         (0            0 1)
+ ****************************************************************************/
+static void bendmat(Matrix &M, double L, double irho, double phi1, double phi2,
+        double gap, double k) {
+    /*  called  by Mpole_Setmatrix
 
-                         (1                 0 0)
-           Edge(theta) = (-h*tan(theta-psi) 1 0)
-                         (0                 0 1)
+     For a quadrupole  see quadmat routine for explanation
 
-                                    2
-                   K1*gap*h*(1 + sin phi)
-            psi = -----------------------, K1 = 1/2
-                        cos phi
+     For a dipole
 
-   Input:
-      L   : length [m]
-      irho: 1/rho [1/m]
-      phi1: entrance edge angle [degres]
-      phi2: exit edge angle [degres]
-      K   : gradient = n/Rho
+     (1            0 0)
+     Edge(theta) = (h*tan(theta) 1 0)
+     (0            0 1)
 
-   Output:
-       M transfer matrix
+     (1                 0 0)
+     Edge(theta) = (-h*tan(theta-psi) 1 0)
+     (0                 0 1)
 
-   Return:
-       none
+     2
+     K1*gap*h*(1 + sin phi)
+     psi = -----------------------, K1 = 1/2
+     cos phi                                              */
 
-   Global variables:
-       none
+    double r, s, c, sk, p, fk, afk;
+    Matrix edge, ah, av;
+    double coef, scoef;
 
-   Specific functions:
-       quadmat, make3by3
-       UnitMat, MulRMat, psi
+    if (irho == 0.0) {
+        /* Quadrupole matrix */
+        quadmat(M, L, k);
+        return;
+    }
 
-   Comments:
-       none
+    /* For multipole w/ irho !=0 eg dipole */
+    coef = 1.0 + globval.dPparticle;
+    scoef = sqrt(coef);
+    r = L * irho / scoef;
+
+    if (k == 0.0) {
+        /* simple vertical dipole magnet */
+        /*
+         H-plane
+         2    2                2
+         px + py              2 x
+         H = --------  - h*x*dP + h ---
+         2*(1+dP)               2
+
+         2     2
+         dx     h        h*dP
+         --2 + ---- x = -----
+         ds    1+dP      1+dP
+
+
+         let be u = Lh/sqrt(1+dP) then the transfert matrix becomes:
+
+         (                              sin(u)              1- cos(u)      )
+         (          cos(u)         --------------       -----------------  )
+         (                          h sqrt(1+dP)                 h         )
+         (  -sin(u)*sqrt(1+dP)*h        cos(u)           sin(u)*sqrt(1+dP) )
+         (            0                  0                       1         )
+
+         */
+        c = cos(r);
+        s = sin(r);
+        make3by3(ah, c, s / (irho * scoef), (1.0 - c) / irho,
+                -s * scoef * irho, c, s * scoef, 0.0, 0.0, 1.0);
+        /*
+         V-plane: it is just a drift
+         (        L     )
+         (   1   ----  0)
+         (       1+dP   )
+         (   0     1   0)
+         (   0     0   1)
+         */
+        make3by3(av, 1.0, L / coef, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 1.0);
+    } else {
+        /* gradient bend, k= n/rho^2 */
+        /*
+         K = -k -h*h
+         p = L*sqrt(|K|)/sqrt(1+dP)
+         */
+        fk = -k - irho * irho;
+        afk = fabs(fk);
+        sk = sqrt(afk);
+        p = L * sk / scoef;
+        if (fk < 0.0) {
+            /*
+             H-plane
+             2    2                     2
+             px + py                 2   x
+             H = --------  - h*x*dP + (k+h ) ---
+             2*(1+dP)                    2
+
+             2      2
+             dx    k+h        h*dP
+             --2 + ---- x = -----
+             ds    1+dP      1+dP
+
+
+             let be u = Lsqrt(|h*h+b2|)/sqrt(1+dP)
+             then the transfert matrix becomes:
+
+             (                              sin(u)              1- cos(u)      )
+             (          cos(u)         --------------       -----------------  )
+             (                          sk*sqrt(1+dP)           |k+h*h|*h      )
+             (  -sin(u)*sqrt(1+dP)*sk      cos(u)        h*sin(u)*sqrt(1+dP)/sk)
+             (            0                  0                       1         )
+
+             */
+            c = cos(p);
+            s = sin(p);
+            make3by3(ah, c, s / sk / scoef, irho * (1.0 - c) / (coef * afk),
+                    -scoef * sk * s, c, scoef * irho / sk * s, 0.0, 0.0, 1.0);
+            sk = sqrt(fabs(k));
+            p = L * sk / scoef;
+            c = cosh(p);
+            s = sinh(p);
+            make3by3(av, c, s / sk / scoef, 0.0, sk * s * scoef, c, 0.0, 0.0,
+                    0.0, 1.0);
+        } else {
+            /* vertically focusing */
+            c = cosh(p);
+            s = sinh(p);
+            make3by3(ah, c, s / sk / scoef, (c - 1.0) * irho / afk, scoef * s
+                    * sk, c, scoef * s * irho / sk, 0.0, 0.0, 1.0);
+            sk = sqrt(fabs(k));
+            p = L * sk / scoef;
+            c = cos(p);
+            s = sin(p);
+            make3by3(av, c, s / sk / scoef, 0.0, -sk * s * scoef, c, 0.0, 0.0,
+                    0.0, 1.0);
+        }
+    }
+    /* Edge focusing, no effect due to gap between AU and AD */
 
-****************************************************************************/
-static void bendmat(Matrix &M, double L, double irho, double phi1,
-                    double phi2, double gap, double k)
-{
-  /*  called  by Mpole_Setmatrix
-
-       For a quadrupole  see quadmat routine for explanation
-   
-       For a dipole
-           
-                         (1            0 0)
-           Edge(theta) = (h*tan(theta) 1 0)
-                         (0            0 1)
-
-                         (1                 0 0)
-           Edge(theta) = (-h*tan(theta-psi) 1 0)
-                         (0                 0 1)
-
-                                    2
-                   K1*gap*h*(1 + sin phi)
-            psi = -----------------------, K1 = 1/2
-                        cos phi                                              */
-
-  double r, s, c, sk, p, fk, afk;
-  Matrix edge, ah, av;
-  double coef, scoef;
-
-  if (irho == 0.0) {
-    /* Quadrupole matrix */
-    quadmat(M, L, k);
-    return;
-  }
-
-  /* For multipole w/ irho !=0 eg dipole */
-  coef  = 1.0 + globval.dPparticle; scoef = sqrt(coef); r = L*irho/scoef;
-
-  if (k == 0.0) {
-    /* simple vertical dipole magnet */
-    /*
-       H-plane
-                          2    2                2
-                        px + py              2 x
-                   H = --------  - h*x*dP + h ---
-                        2*(1+dP)               2
-
-                     2     2
-                   dx     h        h*dP
-                   --2 + ---- x = -----
-                   ds    1+dP      1+dP
-
-                   
-       let be u = Lh/sqrt(1+dP) then the transfert matrix becomes:
-        
-    (                              sin(u)              1- cos(u)      )
-    (          cos(u)         --------------       -----------------  )
-    (                          h sqrt(1+dP)                 h         )
-    (  -sin(u)*sqrt(1+dP)*h        cos(u)           sin(u)*sqrt(1+dP) )
-    (            0                  0                       1         )
-     
-    */
-    c = cos(r); s = sin(r);
-    make3by3(ah, c, s/(irho*scoef), (1.0-c)/irho, -s*scoef*irho, c,
-             s*scoef, 0.0, 0.0, 1.0);
     /*
-      V-plane: it is just a drift
-      (        L     )
-      (   1   ----  0)
-      (       1+dP   )
-      (   0     1   0)
-      (   0     0   1)
-    */
-    make3by3(av, 1.0, L/coef, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 1.0);
-  } else {
-    /* gradient bend, k= n/rho^2 */
-    /*         
-      K = -k -h*h
-      p = L*sqrt(|K|)/sqrt(1+dP)
-    */
-    fk  = -k - irho*irho; afk = fabs(fk); sk = sqrt(afk); p = L*sk/scoef;
-    if (fk < 0.0) {      
-     /*
-       H-plane
-                          2    2                     2
-                        px + py                 2   x
-                   H = --------  - h*x*dP + (k+h ) ---
-                        2*(1+dP)                    2
-
-                     2      2
-                   dx    k+h        h*dP
-                   --2 + ---- x = -----
-                   ds    1+dP      1+dP
-
-
-       let be u = Lsqrt(|h*h+b2|)/sqrt(1+dP)
-       then the transfert matrix becomes:
-
-    (                              sin(u)              1- cos(u)      )
-    (          cos(u)         --------------       -----------------  )
-    (                          sk*sqrt(1+dP)           |k+h*h|*h      )
-    (  -sin(u)*sqrt(1+dP)*sk      cos(u)        h*sin(u)*sqrt(1+dP)/sk)
-    (            0                  0                       1         )
-
-    */
-      c = cos(p); s = sin(p);
-      make3by3(ah, c, s/sk/scoef, irho*(1.0-c)/(coef*afk),
-              -scoef*sk*s, c, scoef*irho/sk*s, 0.0, 0.0, 1.0);
-      sk = sqrt(fabs(k)); p = L*sk/scoef; c = cosh(p); s = sinh(p);
-      make3by3(av, c, s/sk/scoef, 0.0, sk*s*scoef, c, 0.0, 0.0, 0.0,
-               1.0);
-    } else {
-      /* vertically focusing */
-      c = cosh(p); s = sinh(p);
-      make3by3(ah, c, s/sk/scoef, (c-1.0)*irho/afk, scoef*s*sk, c,
-               scoef*s*irho/sk, 0.0, 0.0, 1.0);
-      sk = sqrt(fabs(k)); p = L*sk/scoef; c = cos(p); s = sin(p);
-      make3by3(av, c, s/sk/scoef, 0.0, -sk*s*scoef, c, 0.0, 0.0, 0.0, 1.0);
-    }
-  }
-  /* Edge focusing, no effect due to gap between AU and AD */
-
-  /*
-                          (1            0 0)
-            Edge(theta) = (h*tan(theta) 1 0)
-                          (0            0 1)
-
-                          (1                 0 0)
-            Edge(theta) = (-h*tan(theta-psi) 1 0)
-                          (0                 0 1)
-
-                                    2
-                   K1*gap*h*(1 + sin phi)
-            psi = -----------------------, K1 = 1/2
-                        cos phi
-                
-  */
-  if (phi1 != 0.0 || gap > 0.0) {
-    UnitMat(3L, edge);
-    edge[1][0] = irho*tan(dtor(phi1));
-    MulRMat(3L, ah, edge); /* ah <- ah*edge */
-    if (true)
-      edge[1][0] = -irho*tan(dtor(phi1)-get_psi(irho, phi1, gap))/coef;
-    else
-      edge[1][0] = -irho*tan(dtor(phi1)-get_psi(irho, phi1, gap));
-    MulRMat(3L, av, edge); /* av <- av*edge */
-  } else if (phi2 != 0.0 || gap < 0.0) {
-    UnitMat(3L, edge);
-    edge[1][0] = irho*tan(dtor(phi2));
-    MulLMat(3L, edge, ah); /* av <- edge*av */
-    if (true)
-      edge[1][0] = -irho*tan(dtor(phi2)-get_psi(irho, phi2, fabs(gap)))/coef;
-    else
-      edge[1][0] = -irho*tan(dtor(phi2)-get_psi(irho, phi2, fabs(gap)));
-    MulLMat(3L, edge, av); /* av <- edge*av */
-  }
-  mergeto4by5(M, ah, av);
+     (1            0 0)
+     Edge(theta) = (h*tan(theta) 1 0)
+     (0            0 1)
+
+     (1                 0 0)
+     Edge(theta) = (-h*tan(theta-psi) 1 0)
+     (0                 0 1)
+
+     2
+     K1*gap*h*(1 + sin phi)
+     psi = -----------------------, K1 = 1/2
+     cos phi
+
+     */
+    if (phi1 != 0.0 || gap > 0.0) {
+        UnitMat(3L, edge);
+        edge[1][0] = irho * tan(dtor(phi1));
+        MulRMat(3L, ah, edge); /* ah <- ah*edge */
+        if (true)
+            edge[1][0] = -irho * tan(dtor(phi1) - get_psi(irho, phi1, gap))
+                    / coef;
+        else
+            edge[1][0] = -irho * tan(dtor(phi1) - get_psi(irho, phi1, gap));
+        MulRMat(3L, av, edge); /* av <- av*edge */
+    } else if (phi2 != 0.0 || gap < 0.0) {
+        UnitMat(3L, edge);
+        edge[1][0] = irho * tan(dtor(phi2));
+        MulLMat(3L, edge, ah); /* av <- edge*av */
+        if (true)
+            edge[1][0] = -irho * tan(dtor(phi2)
+                    - get_psi(irho, phi2, fabs(gap))) / coef;
+        else
+            edge[1][0] = -irho * tan(dtor(phi2)
+                    - get_psi(irho, phi2, fabs(gap)));
+        MulLMat(3L, edge, av); /* av <- edge*av */
+    }
+    mergeto4by5(M, ah, av);
 }
 
+void Mpole_Setmatrix(int Fnum1, int Knum1, double K) {
+    /*   Compute transfert matrix for a quadrupole magnet
+     the transfert matrix A is plitted into two part
+     A = AD55xAU55
 
-void Mpole_Setmatrix(int Fnum1, int Knum1, double K)
-{
-  /*   Compute transfert matrix for a quadrupole magnet
-       the transfert matrix A is plitted into two part
-           A = AD55xAU55
-
-           where AD55 is the downstream transfert matrix
-           corresponding to a half magnet w/ an exit angle
-           and no entrance angle.
-           The linear frindge field is taken into account
+     where AD55 is the downstream transfert matrix
+     corresponding to a half magnet w/ an exit angle
+     and no entrance angle.
+     The linear frindge field is taken into account
 
-           where AU55 is the upstream transfert matrix
-           corresponding to a half magnet w/ an entrance
-           angle and no exit angle.
-           The linear frindge field is taken into account                    */
+     where AU55 is the upstream transfert matrix
+     corresponding to a half magnet w/ an entrance
+     angle and no exit angle.
+     The linear frindge field is taken into account                    */
 
-  CellType  *cellp;
-  elemtype  *elemp;
-  MpoleType *M;
+    CellType *cellp;
+    elemtype *elemp;
+    MpoleType *M;
 
-  if (ElemFam[Fnum1-1].nKid <= 0) {
-    printf("Mpole_Setmatrix: no kids in famile %d\n", Fnum1);
-    return;
-  }
-  cellp  = &Cell[ElemFam[Fnum1-1].KidList[Knum1-1]]; elemp = &cellp->Elem;
-  M = elemp->M;
+    if (ElemFam[Fnum1 - 1].nKid <= 0) {
+        printf("Mpole_Setmatrix: no kids in famile %d\n", Fnum1);
+        return;
+    }
+    cellp = &Cell[ElemFam[Fnum1 - 1].KidList[Knum1 - 1]];
+    elemp = &cellp->Elem;
+    M = elemp->M;
 
-  bendmat(M->AU55, elemp->PL/2.0, M->Pirho,
-          M->PTx1, 0.0, M->Pgap, K);
-  bendmat(M->AD55, elemp->PL/2.0, M->Pirho, 0.0,
-          M->PTx2, -M->Pgap, K);
+    bendmat(M->AU55, elemp->PL / 2.0, M->Pirho, M->PTx1, 0.0, M->Pgap, K);
+    bendmat(M->AD55, elemp->PL / 2.0, M->Pirho, 0.0, M->PTx2, -M->Pgap, K);
 }
 
-
 void Wiggler_Setmatrix(int Fnum1, int Knum1, double L, double kx, double kz,
-		       double k0)
-{
-  double       t, s, c, k, ky, LL;
-  Matrix       ah, av;
-  double       TEMP;
-  WigglerType  *W;
-
-  LL = L/(1.0+globval.dPparticle);
-  if (kx == 0e0)
-    make3by3(ah, 1.0, LL, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 1.0);
-  else {
-    TEMP = kx/kz; k = sqrt(TEMP*TEMP*fabs(k0));
-    t = LL*k; c = cosh(t); s = sinh(t);
-    make3by3(ah, c, s/k, 0.0, k*s, c, 0.0, 0.0, 0.0, 1.0);
-  }
-  if (k0 == 0e0)
-    make3by3(av, 1.0, LL, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 1.0);
-  else {
-    ky = sqrt(kx*kx+kz*kz); TEMP = ky/kz; k = sqrt(TEMP*TEMP*fabs(k0));
-    t = LL*k; c = cos(t); s = sin(t);
-    make3by3(av, c, s/k, 0.0, -k*s, c, 0.0, 0.0, 0.0, 1.0);
-  }
-  W = Cell[ElemFam[Fnum1-1].KidList[Knum1-1]].Elem.W;
-  mergeto4by5(W->W55, ah, av);
-}
-
-
-void Mpole_Pass_M(CellType &Cell, Vector &xref, Matrix &x)
-{
-  double     k;
-  elemtype   *elemp;
-  MpoleType  *M;
-
-  elemp = &Cell.Elem; M = elemp->M;
-  /* Global -> Local */
-  GtoL_M(x, Cell.dT); GtoL(xref, Cell.dS, Cell.dT, M->Pc0, M->Pc1, M->Ps1);
-  
-  switch (M->Pmethod) {
-
-  case Meth_Linear:
-
-  case Meth_Fourth:   /* Nothing */
-// Laurent
-//  case Meth_First:   /* Nothing */
-    /* Tracy integrator */
-    if (M->Pthick == thick) {
-      /* thick element */
-      /* First Linear */
-      MulLMat(5, M->AU55, x); LinTrans(5, M->AU55, xref);
-      k = M->PB[Quad+HOMmax];
-      M->PB[Quad+HOMmax] = 0.0;
-      /* Kick */
-      thin_kick_M(M->Porder, M->PB, elemp->PL, 0.0, xref, x);
-      thin_kick(M->Porder, M->PB, elemp->PL, 0.0, 0.0, xref);
-      M->PB[Quad+HOMmax] = k;
-      /* Second Linear */
-      MulLMat(5L, M->AD55, x); LinTrans(5L, M->AD55, xref);
+        double k0) {
+    double t, s, c, k, ky, LL;
+    Matrix ah, av;
+    double TEMP;
+    WigglerType *W;
+
+    LL = L / (1.0 + globval.dPparticle);
+    if (kx == 0e0)
+        make3by3(ah, 1.0, LL, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 1.0);
+    else {
+        TEMP = kx / kz;
+        k = sqrt(TEMP * TEMP * fabs(k0));
+        t = LL * k;
+        c = cosh(t);
+        s = sinh(t);
+        make3by3(ah, c, s / k, 0.0, k * s, c, 0.0, 0.0, 0.0, 1.0);
     }
+    if (k0 == 0e0)
+        make3by3(av, 1.0, LL, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 1.0);
     else {
-      /* thin kick */
-      thin_kick_M(M->Porder, M->PB, 1.0, 0.0, xref, x);
-      thin_kick(M->Porder, M->PB, 1.0, 0.0, 0.0, xref);
+        ky = sqrt(kx * kx + kz * kz);
+        TEMP = ky / kz;
+        k = sqrt(TEMP * TEMP * fabs(k0));
+        t = LL * k;
+        c = cos(t);
+        s = sin(t);
+        make3by3(av, c, s / k, 0.0, -k * s, c, 0.0, 0.0, 0.0, 1.0);
     }
-    break;
-  }
-
-  /* Local -> Global */
-  LtoG_M(x, Cell.dT);
-  LtoG(xref, Cell.dS, Cell.dT, M->Pc0, M->Pc1, M->Ps1);
+    W = Cell[ElemFam[Fnum1 - 1].KidList[Knum1 - 1]].Elem.W;
+    mergeto4by5(W->W55, ah, av);
 }
 
+void Mpole_Pass_M(CellType &Cell, Vector &xref, Matrix &x) {
+    double k;
+    elemtype *elemp;
+    MpoleType *M;
+
+    elemp = &Cell.Elem;
+    M = elemp->M;
+    /* Global -> Local */
+    GtoL_M(x, Cell.dT);
+    GtoL(xref, Cell.dS, Cell.dT, M->Pc0, M->Pc1, M->Ps1);
+
+    switch (M->Pmethod) {
+
+    case Meth_Linear:
+
+    case Meth_Fourth: /* Nothing */
+        // Laurent
+        //  case Meth_First:   /* Nothing */
+        /* Tracy integrator */
+        if (M->Pthick == thick) {
+            /* thick element */
+            /* First Linear */
+            MulLMat(5, M->AU55, x);
+            LinTrans(5, M->AU55, xref);
+            k = M->PB[Quad + HOMmax];
+            M->PB[Quad + HOMmax] = 0.0;
+            /* Kick */
+            thin_kick_M(M->Porder, M->PB, elemp->PL, 0.0, xref, x);
+            thin_kick(M->Porder, M->PB, elemp->PL, 0.0, 0.0, xref);
+            M->PB[Quad + HOMmax] = k;
+            /* Second Linear */
+            MulLMat(5L, M->AD55, x);
+            LinTrans(5L, M->AD55, xref);
+        } else {
+            /* thin kick */
+            thin_kick_M(M->Porder, M->PB, 1.0, 0.0, xref, x);
+            thin_kick(M->Porder, M->PB, 1.0, 0.0, 0.0, xref);
+        }
+        break;
+    }
 
-void Wiggler_Pass_M(CellType &Cell, Vector &xref, Matrix &x)
-{
-  elemtype     *elemp;
-  WigglerType  *W;
+    /* Local -> Global */
+    LtoG_M(x, Cell.dT);
+    LtoG(xref, Cell.dS, Cell.dT, M->Pc0, M->Pc1, M->Ps1);
+}
 
-  elemp = &Cell.Elem; W = elemp->W;
+void Wiggler_Pass_M(CellType &Cell, Vector &xref, Matrix &x) {
+    elemtype *elemp;
+    WigglerType *W;
 
-  /* Global -> Local */
-  GtoL_M(x, Cell.dT); GtoL(xref, Cell.dS, Cell.dT, 0.0, 0.0, 0.0);
+    elemp = &Cell.Elem;
+    W = elemp->W;
 
-  switch (W->Pmethod) {
-  case Meth_Linear:   /* Nothing */
-    /* Tracy integrator */
-    MulLMat(5, W->W55, x); LinTrans(5L, W->W55, xref);
-    break;
-  }
+    /* Global -> Local */
+    GtoL_M(x, Cell.dT);
+    GtoL(xref, Cell.dS, Cell.dT, 0.0, 0.0, 0.0);
 
-  /* Local -> Global */
-  LtoG_M(x, Cell.dT); LtoG(xref, Cell.dS, Cell.dT, 0.0, 0.0, 0.0);
+    switch (W->Pmethod) {
+    case Meth_Linear: /* Nothing */
+        /* Tracy integrator */
+        MulLMat(5, W->W55, x);
+        LinTrans(5L, W->W55, xref);
+        break;
+    }
+
+    /* Local -> Global */
+    LtoG_M(x, Cell.dT);
+    LtoG(xref, Cell.dS, Cell.dT, 0.0, 0.0, 0.0);
 }
 
+void Insertion_SetMatrix(int Fnum1, int Knum1) {
+    /* void Insertion_SetMatrix(int Fnum1, int Knum1)
 
-void Insertion_SetMatrix(int Fnum1, int Knum1)
-{
-/* void Insertion_SetMatrix(int Fnum1, int Knum1)
-
-   Purpose: called by Insertion_Init
-       Constructs the linear matrices
-          K55 kick matrix for one slice
-          D55 drift matrix for one slice
-          KD55 full linear transport matrix
-       
-   Input:
-       Fnum1 Family number
-       Knum1 Kid number
-
-   Output:
-       none
-
-   Return:
-       none
-
-   Global variables:
-       globval
-
-   Specific functions:
-       LinearInterpDeriv2
-
-   Comments:
-       04/07/03 derivative interpolation around closed orbit
-       10/01/05 First order kick added
-
-       Need to be checked energy dependence and so on.                       */
-
-  int            i = 0;
-  double         L = 0.0;
-  CellType       *cellp;
-  elemtype       *elemp;
-  InsertionType  *ID;
-  double         alpha0 = 0.0, alpha02 = 0.0;
-  double         DTHXDX = 0.0, DTHXDZ = 0.0, DTHZDX = 0.0, DTHZDZ = 0.0;
-  int            Nslice = 0;
-
-  if (ElemFam[Fnum1-1].nKid <= 0)
-    return;
-      
-  cellp   = &Cell[ElemFam[Fnum1-1].KidList[Knum1-1]];
-  elemp  = &cellp->Elem;
-  ID  = elemp->ID;
-  Nslice = ID->PN;
-  alpha0 = c0/globval.Energy*1E-9*ID->scaling;
-  alpha02 = alpha0*alpha0/(1.0+globval.dPparticle);
-
-  UnitMat(6L,ID->D55);
-  UnitMat(6L,ID->K55);
-  UnitMat(6L,ID->KD55);
-
-//  if (globval.radiation == false && globval.Cavity_on == false)
-//  {
+     Purpose: called by Insertion_Init
+     Constructs the linear matrices
+     K55 kick matrix for one slice
+     D55 drift matrix for one slice
+     KD55 full linear transport matrix
+
+     Input:
+     Fnum1 Family number
+     Knum1 Kid number
+
+     Output:
+     none
+
+     Return:
+     none
+
+     Global variables:
+     globval
+
+     Specific functions:
+     LinearInterpDeriv2
+
+     Comments:
+     04/07/03 derivative interpolation around closed orbit
+     10/01/05 First order kick added
+
+     Need to be checked energy dependence and so on.                       */
+
+    int i = 0;
+    double L = 0.0;
+    CellType *cellp;
+    elemtype *elemp;
+    InsertionType *ID;
+    double alpha0 = 0.0, alpha02 = 0.0;
+    double DTHXDX = 0.0, DTHXDZ = 0.0, DTHZDX = 0.0, DTHZDZ = 0.0;
+    int Nslice = 0;
+
+    if (ElemFam[Fnum1 - 1].nKid <= 0)
+        return;
+
+    cellp = &Cell[ElemFam[Fnum1 - 1].KidList[Knum1 - 1]];
+    elemp = &cellp->Elem;
+    ID = elemp->ID;
+    Nslice = ID->PN;
+    alpha0 = c0 / globval.Energy * 1E-9 * ID->scaling1;
+    alpha02 = (c0 / globval.Energy * 1E-9) * c0 / globval.Energy * 1E-9 / (1.0
+            + globval.dPparticle) * ID->scaling2;
+
+    UnitMat(6L, ID->D55);
+    UnitMat(6L, ID->K55);
+    UnitMat(6L, ID->KD55);
+
+    //  if (globval.radiation == false && globval.Cavity_on == false)
+    //  {
     /* (Nslice + 1) Drifts for Nslice Kicks */
 
     /* Drift Matrix */
-    L = elemp->PL/(Nslice+1)/(1.0+globval.dPparticle);
-    make4by5(ID->D55,
-	     1.0, L, 0.0, 0.0, 1.0, 0.0, 1.0, L, 0.0, 0.0, 1.0, 0.0);
+    L = elemp->PL / (Nslice + 1) / (1.0 + globval.dPparticle);
+    make4by5(ID->D55, 1.0, L, 0.0, 0.0, 1.0, 0.0, 1.0, L, 0.0, 0.0, 1.0, 0.0);
 
     /* First order Kick */
     if (ID->firstorder) {
-      /* quadrupole Kick matrix linearized around closed orbit */
-      if (!ID->linear) {
-//        SplineInterpDeriv3(cellp->BeamPos[0], cellp->BeamPos[2],
-//			   &DTHXDX, &DTHXDZ, &DTHZDX, &DTHZDZ, cellp);
-      } else {
-//        LinearInterpDeriv2(cellp->BeamPos[0], cellp->BeamPos[2],
-//			   &DTHXDX, &DTHXDZ, &DTHZDX, &DTHZDZ, cellp, 1);
-      }      
-      ID->K55[1][0] = ID->K55[1][0] + alpha0*DTHXDX/Nslice;
-      ID->K55[1][2] = ID->K55[1][2] + alpha0*DTHXDZ/Nslice;
-      ID->K55[3][0] = ID->K55[3][0] + alpha0*DTHZDX/Nslice;
-      ID->K55[3][2] = ID->K55[3][2] + alpha0*DTHZDZ/Nslice;
+        /* quadrupole Kick matrix linearized around closed orbit */
+        if (!ID->linear) {
+            //        SplineInterpDeriv3(cellp->BeamPos[0], cellp->BeamPos[2],
+            //			   &DTHXDX, &DTHXDZ, &DTHZDX, &DTHZDZ, cellp);
+        } else {
+            //        LinearInterpDeriv2(cellp->BeamPos[0], cellp->BeamPos[2],
+            //			   &DTHXDX, &DTHXDZ, &DTHZDX, &DTHZDZ, cellp, 1);
+        }
+        ID->K55[1][0] = ID->K55[1][0] + alpha0 * DTHXDX / Nslice;
+        ID->K55[1][2] = ID->K55[1][2] + alpha0 * DTHXDZ / Nslice;
+        ID->K55[3][0] = ID->K55[3][0] + alpha0 * DTHZDX / Nslice;
+        ID->K55[3][2] = ID->K55[3][2] + alpha0 * DTHZDZ / Nslice;
     }
 
     /* Second order Kick */
-    if (ID->secondorder){
-      /* quadrupole Kick matrix linearized around closed orbit */
-      if (!ID->linear){
-//        SplineInterpDeriv3(cellp->BeamPos[0], cellp->BeamPos[2],
-//			   &DTHXDX, &DTHXDZ, &DTHZDX, &DTHZDZ, cellp);
-      } else{
-//        LinearInterpDeriv2(cellp->BeamPos[0], cellp->BeamPos[2],
-//			   &DTHXDX, &DTHXDZ, &DTHZDX, &DTHZDZ, cellp, 2);
-      }      
-      ID->K55[1][0] = ID->K55[1][0] + alpha02*DTHXDX/Nslice;
-      ID->K55[1][2] = ID->K55[1][2] + alpha02*DTHXDZ/Nslice;
-      ID->K55[3][0] = ID->K55[3][0] + alpha02*DTHZDX/Nslice;
-      ID->K55[3][2] = ID->K55[3][2] + alpha02*DTHZDZ/Nslice;
-    }
-
-    MulLMat(6L,ID->D55, ID->KD55);
+    if (ID->secondorder) {
+        /* quadrupole Kick matrix linearized around closed orbit */
+        if (!ID->linear) {
+            //        SplineInterpDeriv3(cellp->BeamPos[0], cellp->BeamPos[2],
+            //			   &DTHXDX, &DTHXDZ, &DTHZDX, &DTHZDZ, cellp);
+        } else {
+            //        LinearInterpDeriv2(cellp->BeamPos[0], cellp->BeamPos[2],
+            //			   &DTHXDX, &DTHXDZ, &DTHZDX, &DTHZDZ, cellp, 2);
+        }
+        ID->K55[1][0] = ID->K55[1][0] + alpha02 * DTHXDX / Nslice;
+        ID->K55[1][2] = ID->K55[1][2] + alpha02 * DTHXDZ / Nslice;
+        ID->K55[3][0] = ID->K55[3][0] + alpha02 * DTHZDX / Nslice;
+        ID->K55[3][2] = ID->K55[3][2] + alpha02 * DTHZDZ / Nslice;
+    }
+
+    MulLMat(6L, ID->D55, ID->KD55);
 
     for (i = 1; i <= Nslice; i++) {
-      MulLMat(6L,ID->K55, ID->KD55);
-      MulLMat(6L,ID->D55, ID->KD55);
+        MulLMat(6L, ID->K55, ID->KD55);
+        MulLMat(6L, ID->D55, ID->KD55);
     }
-    
-//  }
-//  else
-//  {
-//    L = elemp->PL/(1.0 + globval.dPparticle);  /* L = L/(1 + dP) */
-//    make4by5(ID->KD55,
-//	     1.0, L, 0.0, 0.0, 1.0, 0.0,
-//	     1.0, L, 0.0, 0.0, 1.0, 0.0);
-//  }
+
+    //  }
+    //  else
+    //  {
+    //    L = elemp->PL/(1.0 + globval.dPparticle);  /* L = L/(1 + dP) */
+    //    make4by5(ID->KD55,
+    //	     1.0, L, 0.0, 0.0, 1.0, 0.0,
+    //	     1.0, L, 0.0, 0.0, 1.0, 0.0);
+    //  }
 }
 
+void Insertion_Pass_M(CellType &Cell, Vector &xref, Matrix &M) {
+    /* Purpose: called by Elem_Pass_M
+     matrix propagation through a insertion kick-driftlike matrix
+     x   = KD55*x
+     xref= insertion(xref)
 
-void Insertion_Pass_M(CellType &Cell, Vector &xref, Matrix &M)
-{
-  /* Purpose: called by Elem_Pass_M
-       matrix propagation through a insertion kick-driftlike matrix
-       x   = KD55*x
-       xref= insertion(xref)
+     Input:
+     xref vector
+     x    matrix
 
-   Input:
-       xref vector
-       x    matrix
+     Output:
+     xref
+     x
 
-   Output:
-       xref
-       x
+     Return:
+     none
 
-   Return:
-       none
+     Global variables:
+     none
 
-   Global variables:
-       none
+     Specific functions:
+     MulLMat, Drft
 
-   Specific functions:
-       MulLMat, Drft
+     Comments:
+     01/07/03 6D tracking activated                                        */
 
-   Comments:
-       01/07/03 6D tracking activated                                        */
+    elemtype *elemp;
 
-  elemtype *elemp;
-  
-  elemp = &Cell.Elem;
+    elemp = &Cell.Elem;
 
-  /* Global -> Local */
-//  GtoL_M(x, Cell->dT);
-//  GtoL(xref, Cell->dS, Cell->dT, 0.0, 0.0, 0.0);
-//  if (globval.radiation == false && globval.Cavity_on == false)
-//  {
+    /* Global -> Local */
+    //  GtoL_M(x, Cell->dT);
+    //  GtoL(xref, Cell->dS, Cell->dT, 0.0, 0.0, 0.0);
+    //  if (globval.radiation == false && globval.Cavity_on == false)
+    //  {
     MulLMat(5, elemp->ID->KD55, M); /* M<-KD55*M */
-    LinTrans(5, elemp->ID->KD55, xref); 
-//  }
-//  else
-//  {
-//    MulLMat(5L, elemp->ID->D55, M); /* X<-D55*X */
-//    Drft(elemp->PL, elemp->PL/(1.0+xref[4]), xref);
-//  }
-
-  /* Local -> Global */
-//  LtoG_M(x, Cell->dT);
-//  LtoG(xref, Cell->dS, Cell->dT, 0.0, 0.0, 0.0);
+    LinTrans(5, elemp->ID->KD55, xref);
+    //  }
+    //  else
+    //  {
+    //    MulLMat(5L, elemp->ID->D55, M); /* X<-D55*X */
+    //    Drft(elemp->PL, elemp->PL/(1.0+xref[4]), xref);
+    //  }
+
+    /* Local -> Global */
+    //  LtoG_M(x, Cell->dT);
+    //  LtoG(xref, Cell->dS, Cell->dT, 0.0, 0.0, 0.0);
 }
 
 /****************************************************************************/
 /* void getelem(long i, CellType *cellrec) 
 
-   Purpose:
-      assign all the information of i-th element from array Cell[i] to pointer cellrec
+ Purpose:
+ assign all the information of i-th element from array Cell[i] to pointer cellrec
 
-   Input:
-       
-   Output:
-       none
+ Input:
 
-   Return:
-       none
+ Output:
+ none
 
-   Global variables:
-       none
+ Return:
+ none
 
-   Specific functions:
-       none
+ Global variables:
+ none
 
-   Comments:
+ Specific functions:
+ none
 
-****************************************************************************/
-void getelem(long i, CellType *cellrec) 
-{ 
-  *cellrec = Cell[i]; 
+ Comments:
+
+ ****************************************************************************/
+void getelem(long i, CellType *cellrec) {
+    *cellrec = Cell[i];
 }
 /****************************************************************************/
 /* void putelem(long i, CellType *cellrec) 
 
-   Purpose:
-      assign all the information of pointer cellrec to i-th element to array Cell[i]
+ Purpose:
+ assign all the information of pointer cellrec to i-th element to array Cell[i]
+
+ Input:
 
-   Input:
-       
-   Output:
-       none
+ Output:
+ none
 
-   Return:
-       none
+ Return:
+ none
 
-   Global variables:
-       none
+ Global variables:
+ none
 
-   Specific functions:
-       none
+ Specific functions:
+ none
 
-   Comments:
+ Comments:
 
-****************************************************************************/
-void putelem(long i, CellType *cellrec) 
-{ 
-  Cell[i] = *cellrec; 
+ ****************************************************************************/
+void putelem(long i, CellType *cellrec) {
+    Cell[i] = *cellrec;
 }
 
 /****************************************************************************/
 /* int GetnKid(const int Fnum1)
 
-   Purpose:
-      return the number of kid in the family
+ Purpose:
+ return the number of kid in the family
 
-   Input:
-       Fnum1 :  family number 
-            
-       
-   Output:
-       none
+ Input:
+ Fnum1 :  family number
 
-   Return:
-       none
 
-   Global variables:
-       none
+ Output:
+ none
 
-   Specific functions:
-       none
+ Return:
+ none
 
-   Comments:
+ Global variables:
+ none
 
-****************************************************************************/
-int GetnKid(const int Fnum1) 
-{ 
-  return (ElemFam[Fnum1-1].nKid); 
-}
+ Specific functions:
+ none
 
+ Comments:
+
+ ****************************************************************************/
+int GetnKid(const int Fnum1) {
+    return (ElemFam[Fnum1 - 1].nKid);
+}
 
 /****************************************************************************/
 /* long Elem_GetPos(const int Fnum1, const int Knum1)
 
-   Purpose:
-      get the element index in the lattice 
-      
+ Purpose:
+ get the element index in the lattice
 
-   Input:
-       Fnum1 :  family number of the element
-       Knum1 :  kid number of the element in Fnum1       
-       
-   Output:
-       none
 
-   Return:
-       loc : element index in the lattice
+ Input:
+ Fnum1 :  family number of the element
+ Knum1 :  kid number of the element in Fnum1
 
-   Global variables:
-       none
+ Output:
+ none
 
-   Specific functions:
-       none
+ Return:
+ loc : element index in the lattice
 
-   Comments:
+ Global variables:
+ none
 
-****************************************************************************/
-long Elem_GetPos(const int Fnum1, const int Knum1)
-{
-  long int  loc;
+ Specific functions:
+ none
+
+ Comments:
+
+ ****************************************************************************/
+long Elem_GetPos(const int Fnum1, const int Knum1) {
+    long int loc;
+
+    if (ElemFam[Fnum1 - 1].nKid != 0)
+        loc = ElemFam[Fnum1 - 1].KidList[Knum1 - 1];
+    else {
+        loc = -1;
+        printf("Elem_GetPos: there are no kids in family %d (%s)\n", Fnum1,
+                ElemFam[Fnum1 - 1].ElemF.PName);
+        exit_(0);
+    }
 
-  if (ElemFam[Fnum1-1].nKid != 0)
-    loc = ElemFam[Fnum1-1].KidList[Knum1-1];
-  else 
-  {
-    loc = -1;
-    printf("Elem_GetPos: there are no kids in family %d (%s)\n",
-	   Fnum1, ElemFam[Fnum1-1].ElemF.PName);
-    exit_(0);
-  }
+    return loc;
+}
 
-  return loc;
+static double thirdroot(double a) {
+    /* By substitution method */
+    int i;
+    double x;
+
+    x = 1.0;
+    i = 0;
+    do {
+        i++;
+        x = (x + a) / (x * x + 1e0);
+    } while (i != 250);
+    return x;
 }
 
+void SI_init(void) {
+    /*  c_1 = 1/(2*(2-2^(1/3))),    c_2 = (1-2^(1/3))/(2*(2-2^(1/3)))
+     d_1 = 1/(2-2^(1/3)),        d_2 = -2^(1/3)/(2-2^(1/3))                 */
+
+    double C_gamma, C_u;
+
+    c_1 = 1e0 / (2e0 * (2e0 - thirdroot(2e0)));
+    c_2 = 0.5e0 - c_1;
+    d_1 = 2e0 * c_1;
+    d_2 = 1e0 - 2e0 * d_1;
+
+    // classical radiation
+    //  C_gamma = 8.846056192e-05;
+    // C_gamma = 4 * pi * r_e [m] / ( 3 * (m_e [GeV/c^2] * c^2)^3 )
+    C_gamma = 4.0 * M_PI * r_e / (3.0 * cube(1e-9 * m_e));
+    // P_gamma = e^2 c^3 / 2 / pi * C_gamma (E [GeV])^2 (B [T])^2
+    // p_s = P_s/P, E = P*c, B/(Brho) = p/e
+    cl_rad = C_gamma * cube(globval.Energy) / (2.0 * M_PI);
+
+    // eletron rest mass [GeV]: slightly off???
+    //  m_e_ = 0.5110034e-03;
+    // h_bar times c [GeV m]
+    //  hbar_t_c = 1.9732858e-16;
+    // quantum fluctuations
+    C_u = 55.0 / (24.0 * sqrt(3.0));
+    q_fluct = 3.0 * C_u * C_gamma * 1e-9 * h_bar * c0 / (4.0 * M_PI * cube(1e-9
+            * m_e)) * pow(globval.Energy, 5.0);
+}
 
-static double thirdroot(double a)
-{
-  /* By substitution method */
-  int i;
-  double x;
+static void Mpole_Print(FILE *f, int Fnum1) {
+    elemtype *elemp;
+    MpoleType *M;
 
-  x = 1.0; i = 0;
-  do {
-    i++; x = (x+a)/(x*x+1e0);
-  } while (i != 250);
-  return x;
+    elemp = &ElemFam[Fnum1 - 1].ElemF;
+    M = elemp->M;
+    fprintf(f, "Element[%3d ] \n", Fnum1);
+    fprintf(f, "   Name: %.*s,  Kind:   mpole,  L=% .8E\n", SymbolLength,
+            elemp->PName, elemp->PL);
+    fprintf(f, "   Method: %d, N=%4d\n", M->Pmethod, M->PN);
 }
 
+/****************************************************************************
+ * void Drift_Print(FILE **f, long Fnum1)
+
+ Purpose: called by Elem_Print
+ Print out drift characteristics in a file
+ Name, kind, length, method, slice number
 
-void SI_init(void)
-{
-  /*  c_1 = 1/(2*(2-2^(1/3))),    c_2 = (1-2^(1/3))/(2*(2-2^(1/3)))
-      d_1 = 1/(2-2^(1/3)),        d_2 = -2^(1/3)/(2-2^(1/3))                 */
+ Input:
+ Fnum1 Family number
+ f     pointer on file id
 
-  double C_gamma, C_u;
+ Output:
+ none
 
-  c_1 = 1e0/(2e0*(2e0-thirdroot(2e0))); 
-  c_2 = 0.5e0 - c_1;
-  d_1 = 2e0*c_1; 
-  d_2 = 1e0 - 2e0*d_1;
+ Return:
+ none
 
-  // classical radiation
-//  C_gamma = 8.846056192e-05;
-  // C_gamma = 4 * pi * r_e [m] / ( 3 * (m_e [GeV/c^2] * c^2)^3 )
-  C_gamma = 4.0*M_PI*r_e/(3.0*cube(1e-9*m_e));
-  // P_gamma = e^2 c^3 / 2 / pi * C_gamma (E [GeV])^2 (B [T])^2
-  // p_s = P_s/P, E = P*c, B/(Brho) = p/e
-  cl_rad = C_gamma*cube(globval.Energy)/(2.0*M_PI);
+ Global variables:
+ none
 
-  // eletron rest mass [GeV]: slightly off???
-//  m_e_ = 0.5110034e-03;
-  // h_bar times c [GeV m]
-//  hbar_t_c = 1.9732858e-16;
-  // quantum fluctuations
-  C_u = 55.0/(24.0*sqrt(3.0));
-  q_fluct =
-    3.0*C_u*C_gamma*1e-9*h_bar*c0/(4.0*M_PI*cube(1e-9*m_e))
-    *pow(globval.Energy, 5.0);
-}
+ Specific functions:
+ none
 
+ Comments:
+ none
 
-static void Mpole_Print(FILE *f, int Fnum1)
-{
-  elemtype  *elemp;
-  MpoleType *M;
+ ****************************************************************************/
+static void Drift_Print(FILE *f, int Fnum1) {
+    ElemFamType *elemfamp;
+    elemtype *elemp;
 
-  elemp  = &ElemFam[Fnum1-1].ElemF; M = elemp->M;
-  fprintf(f, "Element[%3d ] \n", Fnum1);
-  fprintf(f, "   Name: %.*s,  Kind:   mpole,  L=% .8E\n",
-          SymbolLength, elemp->PName, elemp->PL);
-  fprintf(f, "   Method: %d, N=%4d\n", M->Pmethod, M->PN);
+    elemfamp = &ElemFam[Fnum1 - 1];
+    elemp = &elemfamp->ElemF;
+    fprintf(f, "Element[%3d ] \n", Fnum1);
+    fprintf(f, "   Name: %.*s,  Kind:   drift,  L=% .8E\n", SymbolLength,
+            elemp->PName, elemp->PL);
+    fprintf(f, "   nKid:%3d\n\n", elemfamp->nKid);
 }
 
+/****************************************************************************
+ * void Wiggler_Print(FILE **f, long Fnum1)
 
-static void Drift_Print(FILE *f, int Fnum1)
-{
-  ElemFamType *elemfamp;
-  elemtype    *elemp;
+ Purpose: called by Elem_Print
+ Print out drift characteristics in a file
+ Name, kind, length
 
-  elemfamp = &ElemFam[Fnum1-1]; elemp = &elemfamp->ElemF;
-  fprintf(f, "Element[%3d ] \n", Fnum1);
-  fprintf(f, "   Name: %.*s,  Kind:   drift,  L=% .8E\n",
-          SymbolLength, elemp->PName, elemp->PL);
-  fprintf(f, "   nKid:%3d\n\n", elemfamp->nKid);
-}
+ Input:
+ Fnum1 Family number
+ f     pointer on file id
 
+ Output:
+ none
 
-static void Wiggler_Print(FILE *f, int Fnum1)
-{
-  elemtype *elemp;
+ Return:
+ none
 
-  elemp = &ElemFam[Fnum1-1].ElemF;
-  fprintf(f, "Element[%3d ] \n", Fnum1);
-  fprintf(f, "   Name: %.*s,  Kind:   wiggler,  L=% .8E\n\n",
-          NameLength, elemp->PName, elemp->PL);
-}
+ Global variables:
+ none
+
+ Specific functions:
+ none
+
+ Comments:
+ none
+
+ ****************************************************************************/
+static void Wiggler_Print(FILE *f, int Fnum1) {
+    elemtype *elemp;
 
+    elemp = &ElemFam[Fnum1 - 1].ElemF;
+    fprintf(f, "Element[%3d ] \n", Fnum1);
+    fprintf(f, "   Name: %.*s,  Kind:   wiggler,  L=% .8E\n\n", NameLength,
+            elemp->PName, elemp->PL);
+}
 
 /****************************************************************************
  * void Insertion_Print(FILE **f, long Fnum1)
 
-   Purpose: called by Elem_Print
-       Print out drift characteristics in a file
-           Name, kind, length
+ Purpose: called by Elem_Print
+ Print out drift characteristics in a file
+ Name, kind, length
 
-   Input:
-       Fnum1 Family number
-       f     pointer on file id
+ Input:
+ Fnum1 Family number
+ f     pointer on file id
 
-   Output:
-       none
+ Output:
+ none
 
-   Return:
-       none
+ Return:
+ none
 
-   Global variables:
-       none
+ Global variables:
+ none
 
-   Specific functions:
-       none
+ Specific functions:
+ none
 
-   Comments:
-       none
+ Comments:
+ none
 
-****************************************************************************/
-static void Insertion_Print(FILE *f, int Fnum1)
-{
-  elemtype *elemp;
+ ****************************************************************************/
+static void Insertion_Print(FILE *f, int Fnum1) {
+    elemtype *elemp;
 
-  elemp = &ElemFam[Fnum1-1].ElemF;
-  fprintf(f, "Element[%3d ] \n", Fnum1);
-  fprintf(f, "   Name: %.*s,  Kind:   wiggler,  L=% .8E\n\n",
-          SymbolLength, elemp->PName, elemp->PL);
+    elemp = &ElemFam[Fnum1 - 1].ElemF;
+    fprintf(f, "Element[%3d ] \n", Fnum1);
+    fprintf(f, "   Name: %.*s,  Kind:   wiggler,  L=% .8E\n\n", SymbolLength,
+            elemp->PName, elemp->PL);
 }
 
+/****************************************************************************
+ * void Insertion_SetMatrix(long Fnum1, long Knum1)
 
-void Elem_Print(FILE *f, int Fnum1)
-{
-  int i;
-
-  if (Fnum1 == 0) {
-    // print all elements
-    for (i = 1; i <= globval.Elem_nFam; i++)
-      Elem_Print(f, i);
-    return;
-  }
-
-  switch (ElemFam[Fnum1-1].ElemF.Pkind) {
-  case drift:
-    Drift_Print(f, Fnum1);
-    break;
-
-  case Mpole:
-    Mpole_Print(f, Fnum1);
-    break;
-  case Wigl:
-    Wiggler_Print(f, Fnum1);
-    break;
-  case FieldMap:
-    break;
-  case Insertion:
-    Insertion_Print(f, Fnum1);
-    break;
-  case Cavity:
-    break;
-  case marker:
-    break;
-  case Spreader:
-    break;
-  case Recombiner:
-    break;
-  case Solenoid:
-    break;
-  case undef:
-    break;
-  }
-}
-
+ Purpose: called by Insertion_Init
+ Constructs the linear matrices
+ K55 kick matrix for one slice
+ D55 drift matrix for one slice
+ KD55 full linear transport matrix
 
-double Mpole_GetPB(int Fnum1, int Knum1, int Order);
+ Input:
+ Fnum1 Family number
+ Knum1 Kid number
 
-/****************************************************************************
- * double Elem_GetKval(int Fnum1, int Knum1, int Order)
+ Output:
+ none
 
-   Purpose: 
-       Get the n-th order integrated field strength of the element with
-       family index "Fnum1" and kid number "Knum1".
+ Return:
+ none
 
-   Input:
-       Fnum1:   Family number
-       Knum1:   kid number
-       Order:   field order
-        
-   Output:
-       none
+ Global variables:
+ globval
 
-   Return:
-       Integrated n-th field strength
+ Specific functions:
+ LinearInterpDeriv2
 
-   Global variables:
-       none
+ Comments:
+ 04/07/03 derivative interpolation around closed orbit
+ 10/01/05 First order kick added
 
-   Specific functions:
-       none
+ Need to be checked energy dependence and so on.
+ ****************************************************************************/
 
-   Comments:
-       comments by Jianfeng Zhang  11/2010
+void Elem_Print(FILE *f, int Fnum1) {
+    int i;
 
-****************************************************************************/
-double Elem_GetKval(int Fnum1, int Knum1, int Order)
-{
-  double    Result = 0.0;
-  elemtype  *elemp;
+    if (Fnum1 == 0) {
+        // print all elements
+        for (i = 1; i <= globval.Elem_nFam; i++)
+            Elem_Print(f, i);
+        return;
+    }
 
-  if (Fnum1 > 0) {
-    elemp = &Cell[ElemFam[Fnum1-1].KidList[Knum1-1]].Elem;
-    switch (elemp->Pkind) {
+    switch (ElemFam[Fnum1 - 1].ElemF.Pkind) {
     case drift:
-      Result = 0.0;
-      break;
-    case marker:
-      Result = 0.0;
-      break;
-    case Cavity:
-      Result = 0.0;
-      break;
-    case Mpole: /* KL*/
-      if (elemp->M->Pthick == thick)
-	Result = elemp->PL*Mpole_GetPB(Fnum1, Knum1, Order);
-      else
-	Result = Mpole_GetPB(Fnum1, Knum1, Order);
-      break;
+        Drift_Print(f, Fnum1);
+        break;
+
+    case Mpole:
+        Mpole_Print(f, Fnum1);
+        break;
     case Wigl:
-      Result =
-	elemp->PL*sqrt(2.0
-	*Cell[ElemFam[Fnum1-1].KidList[Knum1-1]].Elem.W->PBW[Order+HOMmax]);
-      break;
+        Wiggler_Print(f, Fnum1);
+        break;
     case FieldMap:
-      Result = 0.0;
-      break;
+        break;
     case Insertion:
-      Result = 0.0;
-      break;
+        Insertion_Print(f, Fnum1);
+        break;
+    case Cavity:
+        break;
+    case marker:
+        break;
     case Spreader:
-      Result = 0.0;
-      break;
+        break;
     case Recombiner:
-      Result = 0.0;
-      break;
+        break;
     case Solenoid:
-      Result = 0.0;
-      break;
+        break;
     case undef:
-      break;
+        break;
     }
-  } else
-    Result = 0.0;
-
-  return Result;
 }
 
+double Mpole_GetPB(int Fnum1, int Knum1, int Order);
 
-#define n               4
-void LinsTrans(Matrix &A, Vector &b)
-{
-  int     j;
-  Vector  c;
+/****************************************************************************
+ * double Elem_GetKval(long Fnum1, long Knum1, long Order)
+
+ Purpose:
+ Get K values
+
+ Input:
+ Fnum1 Famility number
+ Knum1 Kids number
+ Order mutipole component (K=2 for quadrupole)
+
+ Output:
+ none
+
+ Return:
+ 0.0 if drift
+ integrated field if multipole
+
+
+ Global variables:
+ ElemFam
+
+ Specific functions:
+ Mpole_GetPB
+
+ Comments:
+ 01/02/03 add return = 0 for marker and cavity
+ 22/04/03 Insertion added
+
+ ****************************************************************************/
+double Elem_GetKval(int Fnum1, int Knum1, int Order) {
+    double Result = 0.0;
+    elemtype *elemp;
+
+    if (Fnum1 > 0) {
+        elemp = &Cell[ElemFam[Fnum1 - 1].KidList[Knum1 - 1]].Elem;
+        switch (elemp->Pkind) {
+        case drift:
+            Result = 0.0;
+            break;
+        case marker:
+            Result = 0.0;
+            break;
+        case Cavity:
+            Result = 0.0;
+            break;
+        case Mpole: /* KL*/
+            if (elemp->M->Pthick == thick)
+                Result = elemp->PL * Mpole_GetPB(Fnum1, Knum1, Order);
+            else
+                Result = Mpole_GetPB(Fnum1, Knum1, Order);
+            break;
+        case Wigl:
+            Result
+                    = elemp->PL
+                            * sqrt(2.0 * Cell[ElemFam[Fnum1 - 1].KidList[Knum1
+                                    - 1]].Elem.W->PBW[Order + HOMmax]);
+            break;
+        case FieldMap:
+            Result = 0.0;
+            break;
+        case Insertion:
+            Result = 0.0;
+            break;
+        case Spreader:
+            Result = 0.0;
+            break;
+        case Recombiner:
+            Result = 0.0;
+            break;
+        case Solenoid:
+            Result = 0.0;
+            break;
+        case undef:
+            break;
+        }
+    } else
+        Result = 0.0;
 
-  CopyVec(n, b, c); /* c=b */
-  LinTrans(n, A, c); /* c<-A*c */
-  for (j = 0; j < n; j++)
-    c[j] += A[j][n]*b[n] + A[n][j];
-  CopyVec(n, c, b); /* b=c */
+    return Result;
 }
-#undef n
-
 
 #define n               4
-void MulLsMat(Matrix &A, Matrix &B)
-{
-  int     i, k;
-  Matrix  C;  
+void LinsTrans(Matrix &A, Vector &b) {
+    int j;
+    Vector c;
+
+    CopyVec(n, b, c); /* c=b */
+    LinTrans(n, A, c); /* c<-A*c */
+    for (j = 0; j < n; j++)
+        c[j] += A[j][n] * b[n] + A[n][j];
+    CopyVec(n, c, b); /* b=c */
+}
+#undef n
 
-  CopyMat(n, B, C); /* C<-B */
-  MulLMat(n, A, C); /* C<-A*C */
-  for (i = 0; i < n; i++) {
-    C[i][n] = A[i][n]; C[n][i] = 0.0;
-    for (k = 0; k < n; k++) {
-      C[i][n] += A[i][k]*B[k][n];
-      C[n][i] += A[i][k]*B[n][k];
+#define n               4
+void MulLsMat(Matrix &A, Matrix &B) {
+    int i, k;
+    Matrix C;
+
+    CopyMat(n, B, C); /* C<-B */
+    MulLMat(n, A, C); /* C<-A*C */
+    for (i = 0; i < n; i++) {
+        C[i][n] = A[i][n];
+        C[n][i] = 0.0;
+        for (k = 0; k < n; k++) {
+            C[i][n] += A[i][k] * B[k][n];
+            C[n][i] += A[i][k] * B[n][k];
+        }
     }
-  }
-  C[n][n] = 1.0;
-  CopyMat(n+1, C, B); /* B<-C */
+    C[n][n] = 1.0;
+    CopyMat(n + 1, C, B); /* B<-C */
 }
 #undef n
 
-
 /****************************************************************************
  * void Drift_Alloc(elemtype *Elem)
 
-   Purpose:
-       Dynamic memory allocation for drift element
+ Purpose:
+ Dynamic memory allocation for drift element
 
-   Input:
-       Pointer on element
+ Input:
+ Pointer on element
 
-   Output:
-       memory  space for drift in Elem->UU.D
+ Output:
+ memory  space for drift in Elem->UU.D
 
-   Return:
-       none
+ Return:
+ none
 
-   Global variables:
-       none
+ Global variables:
+ none
 
-   Specific functions:
-       none
+ Specific functions:
+ none
 
-   Comments:
-       none
+ Comments:
+ none
 
-****************************************************************************/
-void Drift_Alloc(elemtype *Elem)
-{
-  Elem->D = (DriftType *)malloc(sizeof(DriftType));
+ ****************************************************************************/
+void Drift_Alloc(elemtype *Elem) {
+    Elem->D = (DriftType *) malloc(sizeof(DriftType));
 }
 
-
-void Mpole_Alloc(elemtype *Elem)
-{
-  int        j;
-  MpoleType  *M;
-
-  /* Memory allocation */
-  Elem->M = (MpoleType *)malloc(sizeof(MpoleType));
-  M = Elem->M; M->Pmethod = Meth_Fourth; M->PN = 0;
-  /* Displacement errors */
-  for (j = 0; j <= 1; j++) {
-    M->PdSsys[j] = 0.0; M->PdSrms[j] = 0.0; M->PdSrnd[j] = 0.0;
-  }
-  M->PdTpar = 0.0; /* Roll angle */
-  M->PdTsys = 0.0; /* systematic Roll errors */
-  M->PdTrms = 0.0; /* random Roll errors */
-  M->PdTrnd = 0.0; /* random seed */
-  for (j = -HOMmax; j <= HOMmax; j++) {
-    /* Initializes multipoles strengths to zero */
-    M->PB[j+HOMmax]    = 0.0; M->PBpar[j+HOMmax] = 0.0;
-    M->PBsys[j+HOMmax] = 0.0; M->PBrms[j+HOMmax] = 0.0;
-    M->PBrnd[j+HOMmax] = 0.0;
-  }
-  M->Porder = 0; M->n_design = 0;
-  M->Pirho  = 0.0; /* inverse of curvature radius */
-  M->PTx1   = 0.0; /* Entrance angle */
-  M->PTx2   = 0.0; /* Exit angle */
-  M->Pgap   = 0.0; /* Gap for fringe field ??? */
-
-  M->Pc0 = 0.0; M->Pc1 = 0.0; M->Ps1 = 0.0;
-  M->quadFF1 = 0L;
-  M->quadFF2 = 0L;
-  M->sextFF1 = 0L;
-  M->sextFF2 = 0L;
-  M->quadFFscaling = 0.0;
+void Mpole_Alloc(elemtype *Elem) {
+    int j;
+    MpoleType *M;
+
+    /* Memory allocation */
+    Elem->M = (MpoleType *) malloc(sizeof(MpoleType));
+    M = Elem->M;
+    M->Pmethod = Meth_Fourth;
+    M->PN = 0;
+    /* Displacement errors */
+    for (j = 0; j <= 1; j++) {
+        M->PdSsys[j] = 0.0;
+        M->PdSrms[j] = 0.0;
+        M->PdSrnd[j] = 0.0;
+    }
+    M->PdTpar = 0.0; /* Roll angle */
+    M->PdTsys = 0.0; /* systematic Roll errors */
+    M->PdTrms = 0.0; /* random Roll errors */
+    M->PdTrnd = 0.0; /* random seed */
+    for (j = -HOMmax; j <= HOMmax; j++) {
+        /* Initializes multipoles strengths to zero */
+        M->PB[j + HOMmax] = 0.0;
+        M->PBpar[j + HOMmax] = 0.0;
+        M->PBsys[j + HOMmax] = 0.0;
+        M->PBrms[j + HOMmax] = 0.0;
+        M->PBrnd[j + HOMmax] = 0.0;
+    }
+    M->Porder = 0;
+    M->n_design = 0;
+    M->Pirho = 0.0; /* inverse of curvature radius */
+    M->PTx1 = 0.0; /* Entrance angle */
+    M->PTx2 = 0.0; /* Exit angle */
+    M->Pgap = 0.0; /* Gap for fringe field ??? */
+
+    M->Pc0 = 0.0;
+    M->Pc1 = 0.0;
+    M->Ps1 = 0.0;
+    M->quadFF1 = 0L;
+    M->quadFF2 = 0L;
+    M->sextFF1 = 0L;
+    M->sextFF2 = 0L;
+    M->quadFFscaling = 0.0;
 
 }
 
-
 /****************************************************************************
  * void Cav_Alloc(elemtype *Elem)
 
-   Purpose:
-       Constructor for a cavity element
+ Purpose:
+ Constructor for a cavity element
 
-   Input:
-       none
+ Input:
+ none
 
-   Output:
-       none
+ Output:
+ none
 
-   Return:
-       none
+ Return:
+ none
 
-   Global variables:
-       none
+ Global variables:
+ none
 
-   Specific functions:
-       none
+ Specific functions:
+ none
 
-   Comments:
-       none
+ Comments:
+ none
 
-****************************************************************************/
-void Cav_Alloc(elemtype *Elem)
-{
-  CavityType *C;
+ ****************************************************************************/
+void Cav_Alloc(elemtype *Elem) {
+    CavityType *C;
 
-  Elem->C = (CavityType *)malloc(sizeof(CavityType));
-  C = Elem->C;
-  C->Pvolt = 0.0; C->Pfreq = 0.0; C->phi = 0.0; C->Ph = 0;
+    Elem->C = (CavityType *) malloc(sizeof(CavityType));
+    C = Elem->C;
+    C->Pvolt = 0.0;
+    C->Pfreq = 0.0;
+    C->phi = 0.0;
+    C->Ph = 0;
 }
 
+void Wiggler_Alloc(elemtype *Elem) {
+    int j;
+    WigglerType *W;
+
+    Elem->W = (WigglerType *) malloc(sizeof(WigglerType));
+    W = Elem->W;
+    W->Pmethod = Meth_Linear;
+    W->PN = 0;
+    for (j = 0; j <= 1; j++) {
+        W->PdSsys[j] = 0.0;
+        W->PdSrnd[j] = 0.0;
+    }
+    W->PdTpar = 0.0;
+    W->PdTsys = 0.0;
+    W->PdTrnd = 0.0;
+    W->n_harm = 0;
+    for (j = 0; j < n_harm_max; j++) {
+        W->BoBrhoV[j] = 0.0;
+        W->BoBrhoH[j] = 0.0;
+        W->kxV[j] = 0.0;
+        W->kxH[j] = 0.0;
+        W->lambda = 0.0;
+        W->phi[j] = 0.0;
+    }
+    for (j = 0; j <= HOMmax; j++)
+        W->PBW[j + HOMmax] = 0.0;
+    W->Porder = 0;
+}
 
-void Wiggler_Alloc(elemtype *Elem)
-{
-  int          j;
-  WigglerType  *W;
-
-  Elem->W = (WigglerType *)malloc(sizeof(WigglerType)); W = Elem->W;
-  W->Pmethod = Meth_Linear; W->PN = 0;
-  for (j = 0; j <= 1; j++) {
-    W->PdSsys[j] = 0.0; W->PdSrnd[j] = 0.0;
-  }
-  W->PdTpar = 0.0; W->PdTsys = 0.0; W->PdTrnd = 0.0;
-  W->n_harm = 0;
-  for (j = 0; j < n_harm_max; j++) {
-    W->BoBrhoV[j] = 0.0; W->BoBrhoH[j] = 0.0; W->kxV[j] = 0.0; W->kxH[j] = 0.0;
-    W->lambda = 0.0; W->phi[j] = 0.0;
-  }
-  for (j = 0; j <= HOMmax; j++)
-    W->PBW[j+HOMmax] = 0.0;
-  W->Porder = 0;
-}
-
-
-void FieldMap_Alloc(elemtype *Elem, const bool alloc_fm)
-{
-  FieldMapType  *FM;
+void FieldMap_Alloc(elemtype *Elem, const bool alloc_fm) {
+    FieldMapType *FM;
+
+    Elem->FM = (FieldMapType *) malloc(sizeof(FieldMapType));
+    FM = Elem->FM;
+    FM->n_step = 0;
+    FM->n[X_] = 0;
+    FM->n[Y_] = 0;
+    FM->n[Z_] = 0;
+    FM->scl = 1.0;
+
+    /*  if (alloc_fm) {
+     FM->AxoBrho = matrix(1, m_max_FM, 1, n_max_FM);
+     FM->AxoBrho2 = matrix(1, m_max_FM, 1, n_max_FM);
+     FM->AyoBrho = matrix(1, m_max_FM, 1, n_max_FM);
+     FM->AyoBrho2 = matrix(1, m_max_FM, 1, n_max_FM);
+
+     FM->Bx = matrix(1, m_max_FM, 1, n_max_FM);
+     FM->By = matrix(1, m_max_FM, 1, n_max_FM);
+     FM->Bz = matrix(1, m_max_FM, 1, n_max_FM);
+
+     FM->x_pos[1] = 1e30; FM->x_pos[FM->m_x] = -1e30;
+     FM->y_pos[1] = 1e30; FM->y_pos[FM->m_y] = -1e30;
+     FM->s_pos[1] = 1e30; FM->s_pos[FM->n_s] = -1e30;
+     }*/
+
+    //  free_vector(FM->x_pos, 1, m_max_FM); free_vector(FM->y_pos, 1, m_max_FM);
+    //  free_vector(FM->s_pos, 1, n_max_FM);
+    //  free_matrix(FM->AxoBrho, 1, m_max_FM, 1, n_max_FM);
+    //  free_matrix(FM->AxoBrho2, 1, m_max_FM, 1, n_max_FM);
+
+    //  free_matrix(Bx, 1, m_max_FM, 1, n_max_FM);
+    //  free_matrix(By, 1, m_max_FM, 1, n_max_FM);
+    //  free_matrix(Bz, 1, m_max_FM, 1, n_max_FM);
+}
 
-  Elem->FM = (FieldMapType *)malloc(sizeof(FieldMapType)); FM = Elem->FM;
-  FM->n_step = 0; FM->n[X_] = 0; FM->n[Y_] = 0; FM->n[Z_] = 0; FM->scl = 1.0;
+/****************************************************************************
+ * void Insertion_Alloc(elemtype *Elem, boolean firstflag, boolean secondflag)
 
-/*  if (alloc_fm) {
-    FM->AxoBrho = matrix(1, m_max_FM, 1, n_max_FM);
-    FM->AxoBrho2 = matrix(1, m_max_FM, 1, n_max_FM);
-    FM->AyoBrho = matrix(1, m_max_FM, 1, n_max_FM);
-    FM->AyoBrho2 = matrix(1, m_max_FM, 1, n_max_FM);
+ Purpose: called by Insertion_Init and Lat_DealElement
+ Dynamic memory allocation for a Insertion element and various
+ initializations
 
-    FM->Bx = matrix(1, m_max_FM, 1, n_max_FM);
-    FM->By = matrix(1, m_max_FM, 1, n_max_FM);
-    FM->Bz = matrix(1, m_max_FM, 1, n_max_FM);
+ Input:
+ Elem Element for memory allocation
+ firstflag true if first order kick map to be loaded
+ secondflag true if second order kick map to be loaded
 
-    FM->x_pos[1] = 1e30; FM->x_pos[FM->m_x] = -1e30;
-    FM->y_pos[1] = 1e30; FM->y_pos[FM->m_y] = -1e30;
-    FM->s_pos[1] = 1e30; FM->s_pos[FM->n_s] = -1e30;
-  }*/
+ Output:
+ none
 
-//  free_vector(FM->x_pos, 1, m_max_FM); free_vector(FM->y_pos, 1, m_max_FM);
-//  free_vector(FM->s_pos, 1, n_max_FM);
-//  free_matrix(FM->AxoBrho, 1, m_max_FM, 1, n_max_FM);
-//  free_matrix(FM->AxoBrho2, 1, m_max_FM, 1, n_max_FM);
+ Return:
+ none
 
-//  free_matrix(Bx, 1, m_max_FM, 1, n_max_FM);
-//  free_matrix(By, 1, m_max_FM, 1, n_max_FM);
-//  free_matrix(Bz, 1, m_max_FM, 1, n_max_FM);
-}
+ Global variables:
+ none
 
-/****************************************************************************
- * void Insertion_Alloc(elemtype *Elem, boolean firstflag, boolean secondflag)
+ Specific functions:
+ none
 
-   Purpose: called by Insertion_Init and Lat_DealElement
-       Dynamic memory allocation for a Insertion element and various
-       initializations
+ Comments:
+ 10/01/05 First order kick part added
+ 4 November 2010 Splitting 1st and 2nd order X and Z axes
 
-   Input:
-       Elem Element for memory allocation
-       firstflag true if first order kick map to be loaded
-       secondflag true if second order kick map to be loaded
+ ****************************************************************************/
 
-   Output:
-       none
+void Insertion_Alloc(elemtype *Elem) {
+    int i = 0, j = 0;
+    InsertionType *ID;
 
-   Return:
-       none
+    Elem->ID = (InsertionType *) malloc(sizeof(InsertionType));
+    ID = Elem->ID;
 
-   Global variables:
-       none
+    ID->Pmethod = Meth_Linear;
+    ID->PN = 0;
+    ID->nx1 = 0;
+    ID->nz1 = 0;
+    ID->nx2 = 0;
+    ID->nz2 = 0;
 
-   Specific functions:
-       none
+    /* Initialization thetax and thetaz to 0*/
 
-   Comments:
-       10/01/05 First order kick part added
+    // first order kick map
+    if (ID->firstorder) {
+        for (i = 0; i < IDZMAX; i++) {
+            for (j = 0; j < IDXMAX; j++) {
+                ID->thetax1[i][j] = 0.0;
+                ID->thetaz1[i][j] = 0.0;
+            }
+        }
+    }
 
-****************************************************************************/
+    // second order kick map
+    if (ID->secondorder) {
+        for (i = 0; i < IDZMAX; i++) {
+            for (j = 0; j < IDXMAX; j++) {
+                ID->thetax2[i][j] = 0.0;
+                ID->thetaz2[i][j] = 0.0;
+            }
+        }
+    }
 
-void Insertion_Alloc(elemtype *Elem)
-{
-  int            i = 0, j = 0;
-  InsertionType  *ID;
-
-  Elem->ID = (InsertionType *)malloc(sizeof(InsertionType));
-  ID = Elem->ID;
-
-  ID->Pmethod = Meth_Linear; ID->PN = 0;
-  ID->nx = 0; ID->nz = 0;
-
-  /* Initialization thetax and thetaz to 0*/
-  
-  // first order kick map
-  if (ID->firstorder){
-    for (i = 0; i < IDZMAX; i++){
-      for (j = 0; j < IDXMAX; j++) {
-	ID->thetax1[i][j] = 0.0; ID->thetaz1[i][j] = 0.0;
-      }
-    }
-  }
-  
-  // second order kick map
-  if (ID->secondorder) {
-    for (i = 0; i < IDZMAX; i++) {
-      for (j = 0; j < IDXMAX; j++) {
-          ID->thetax[i][j] = 0.0; ID->thetaz[i][j] = 0.0;
-      }
-    }
-  }
-
-  // stuffs for interpolation
-  for (j = 0; j < IDXMAX; j++)
-    ID->tabx[j] = 0.0;
-
-  for (j = 0; j < IDZMAX; j++)
-    ID->tabz[j] = 0.0;
-
-  // filenames
-  strcpy(ID->fname1,""); strcpy(ID->fname2,"");
-  
-  for (j = 0; j <= 1; j++) {
-    ID->PdSsys[j] = 0.0; ID->PdSrnd[j] = 0.0;
-  }
-  ID->PdTpar = 0.0; ID->PdTsys = 0.0; ID->PdTrnd = 0.0;
-  ID->Porder = 0;
-}
-
-
-void Spreader_Alloc(elemtype *Elem)
-{
-  int  k;
+    // stuffs for interpolation
+    for (j = 0; j < IDXMAX; j++) {
+        ID->tabx1[j] = 0.0;
+        ID->tabx2[j] = 0.0;
+    }
+
+    for (j = 0; j < IDZMAX; j++) {
+        ID->tabz1[j] = 0.0;
+        ID->tabz2[j] = 0.0;
+    }
 
-  Elem->Spr = (SpreaderType *)malloc(sizeof(SpreaderType));
+    // filenames
+    strcpy(ID->fname1, "");
+    strcpy(ID->fname2, "");
 
-  for (k = 0; k < Spreader_max; k++)
-    Elem->Spr->Cell_ptrs[k] = NULL;
+    for (j = 0; j <= 1; j++) {
+        ID->PdSsys[j] = 0.0;
+        ID->PdSrnd[j] = 0.0;
+    }
+    ID->PdTpar = 0.0;
+    ID->PdTsys = 0.0;
+    ID->PdTrnd = 0.0;
+    ID->Porder = 0;
 }
 
+void Spreader_Alloc(elemtype *Elem) {
+    int k;
 
-void Recombiner_Alloc(elemtype *Elem)
-{
-  Elem->Rec = (RecombinerType *)malloc(sizeof(RecombinerType));
+    Elem->Spr = (SpreaderType *) malloc(sizeof(SpreaderType));
+
+    for (k = 0; k < Spreader_max; k++)
+        Elem->Spr->Cell_ptrs[k] = NULL;
 }
 
+void Recombiner_Alloc(elemtype *Elem) {
+    Elem->Rec = (RecombinerType *) malloc(sizeof(RecombinerType));
+}
 
-void Solenoid_Alloc(elemtype *Elem)
-{
-  int           j;
-  SolenoidType  *Sol;
+void Solenoid_Alloc(elemtype *Elem) {
+    int j;
+    SolenoidType *Sol;
+
+    Elem->Sol = (SolenoidType *) malloc(sizeof(SolenoidType));
+    Sol = Elem->Sol;
+    Sol->N = 0;
+    for (j = 0; j <= 1; j++) {
+        Sol->PdSsys[j] = 0.0;
+        Sol->PdSrms[j] = 0.0;
+        Sol->PdSrnd[j] = 0.0;
+    }
+    Sol->dTpar = 0.0;
+    Sol->dTsys = 0.0;
+    Sol->dTrnd = 0.0;
+}
 
-  Elem->Sol = (SolenoidType *)malloc(sizeof(SolenoidType));
-  Sol = Elem->Sol; Sol->N = 0;
-  for (j = 0; j <= 1; j++) {
-    Sol->PdSsys[j] = 0.0; Sol->PdSrms[j] = 0.0; Sol->PdSrnd[j] = 0.0;
-  }
-  Sol->dTpar = 0.0; Sol->dTsys = 0.0; Sol->dTrnd = 0.0;
+/****************************************************************************/
+/* void Drift_Init(long Fnum1)
+
+ Purpose:
+ Constructor of a drift element
+ see comments in  Drift_SetMatrix
+
+ Input:
+ Fnum1 Family number
+
+ Output:
+ none
+
+ Return:
+ none
+
+ Global variables:
+ ElemFam
+ Cell
+
+ Specific functions:
+ Drift_Alloc
+ Drift_SetMatrix
+
+ Comments:
+ none
+
+ ****************************************************************************/
+void Drift_Init(int Fnum1) {
+    int i;
+    ElemFamType *elemfamp;
+    CellType *cellp;
+
+    elemfamp = &ElemFam[Fnum1 - 1];
+    for (i = 1; i <= elemfamp->nKid; i++) {
+        /* Get in Cell kid # i from Family Fnum1 */
+        cellp = &Cell[elemfamp->KidList[i - 1]];
+        /* Dynamic memory allocation for element */
+        Drift_Alloc(&cellp->Elem);
+        /* copy low level routine */
+        memcpy(cellp->Elem.PName, elemfamp->ElemF.PName, sizeof(partsName));
+        /* Set the drift length */
+        cellp->Elem.PL = elemfamp->ElemF.PL;
+        /* set the kind of element */
+        cellp->Elem.Pkind = elemfamp->ElemF.Pkind;
+        /* set pointer for the D dynamic space */
+        *cellp->Elem.D = *elemfamp->ElemF.D;
+        cellp->dT[0] = 1e0; /* cos = 1 */
+        cellp->dT[1] = 0.0; /* sin = 0 */
+        cellp->dS[0] = 0.0; /* no H displacement */
+        cellp->dS[1] = 0.0; /* no V displacement */
+        /* set Drift matrix */
+        Drift_SetMatrix(Fnum1, i);
+    }
 }
 
+static int UpdatePorder(elemtype &Elem) {
+    int i, order;
+    MpoleType *M;
 
-void Drift_Init(int Fnum1)
-{
-  int          i;
-  ElemFamType  *elemfamp;
-  CellType     *cellp;
-
-  elemfamp   = &ElemFam[Fnum1-1];
-  for (i = 1; i <= elemfamp->nKid; i++) {
-    /* Get in Cell kid # i from Family Fnum1 */
-    cellp = &Cell[elemfamp->KidList[i-1]];
-    /* Dynamic memory allocation for element */
-    Drift_Alloc(&cellp->Elem);
-    /* copy low level routine */
-    memcpy(cellp->Elem.PName, elemfamp->ElemF.PName, sizeof(partsName));
-    /* Set the drift length */
-    cellp->Elem.PL = elemfamp->ElemF.PL;
-    /* set the kind of element */
-    cellp->Elem.Pkind = elemfamp->ElemF.Pkind;
-    /* set pointer for the D dynamic space */
-    *cellp->Elem.D = *elemfamp->ElemF.D;
-    cellp->dT[0] = 1e0; /* cos = 1 */
-    cellp->dT[1] = 0.0; /* sin = 0 */
-    cellp->dS[0] = 0.0; /* no H displacement */
-    cellp->dS[1] = 0.0; /* no V displacement */
-    /* set Drift matrix */
-    Drift_SetMatrix(Fnum1, i);
-  }
-}
-
-
-static int UpdatePorder(elemtype &Elem)
-{
-  int        i, order;
-  MpoleType  *M;
+    M = Elem.M;
+    if (M->Pirho != 0.0) /* non zero curvature => bend */
+        order = 1;
+    else
+        /* mutipole */
+        order = 0;
+    for (i = -HOMmax; i <= HOMmax; i++)
+        if (M->PB[i + HOMmax] != 0.0 && abs(i) > order)
+            order = abs(i);
 
-  M = Elem.M;
-  if (M->Pirho != 0.0) /* non zero curvature => bend */
-    order = 1;
-  else /* mutipole */
-    order = 0;
-  for (i = -HOMmax; i <= HOMmax; i++)
-    if (M->PB[i+HOMmax] != 0.0 && abs(i) > order) order = abs(i);
+    return order;
+}
 
-  return order;
+void Mpole_Init(int Fnum1) {
+    double x;
+    int i;
+    ElemFamType *elemfamp;
+    CellType *cellp;
+    elemtype *elemp;
+
+    /* Pointer on element */
+    elemfamp = &ElemFam[Fnum1 - 1];
+    memcpy(elemfamp->ElemF.M->PB, elemfamp->ElemF.M->PBpar, sizeof(mpolArray));
+    /* Update the right multipole order */
+    elemfamp->ElemF.M->Porder = UpdatePorder(elemfamp->ElemF);
+    /* Quadrupole strength */
+    x = elemfamp->ElemF.M->PBpar[Quad + HOMmax];
+    for (i = 1; i <= elemfamp->nKid; i++) {
+        cellp = &Cell[elemfamp->KidList[i - 1]];
+        /* Memory allocation and set everything to zero */
+        Mpole_Alloc(&cellp->Elem);
+        memcpy(cellp->Elem.PName, elemfamp->ElemF.PName, sizeof(partsName));
+        /* set length */
+        cellp->Elem.PL = elemfamp->ElemF.PL;
+        /* set element kind (Mpole) */
+        cellp->Elem.Pkind = elemfamp->ElemF.Pkind;
+        *cellp->Elem.M = *elemfamp->ElemF.M;
+
+        elemp = &cellp->Elem;
+        /* set entrance and exit angles */
+        cellp->dT[0] = cos(dtor(elemp->M->PdTpar));
+        cellp->dT[1] = sin(dtor(elemp->M->PdTpar));
+
+        /* set displacement to zero */
+        cellp->dS[0] = 0.0;
+        cellp->dS[1] = 0.0;
+
+        if (elemp->PL != 0.0 || elemp->M->Pirho != 0.0) {
+            /* Thick element or radius non zero element */
+            elemp->M->Pthick = pthicktype(thick);
+            /* sin(L*irho/2) =sin(theta/2) half the angle */
+            elemp->M->Pc0 = sin(elemp->PL * elemp->M->Pirho / 2e0);
+            /* cos roll: sin(theta/2)*cos(dT) */
+            elemp->M->Pc1 = cellp->dT[0] * elemp->M->Pc0;
+            /* sin roll: sin(theta/2)*cos(dT) */
+            elemp->M->Ps1 = cellp->dT[1] * elemp->M->Pc0;
+            Mpole_Setmatrix(Fnum1, i, x);
+        } else
+            /* element as thin lens */
+            elemp->M->Pthick = pthicktype(thin);
+    }
 }
 
+#define order           2
+void Wiggler_Init(int Fnum1) {
+    int i;
+    double x;
+    ElemFamType *elemfamp;
+    CellType *cellp;
+    elemtype *elemp;
+
+    elemfamp = &ElemFam[Fnum1 - 1];
+    /* ElemF.M^.PB := ElemF.M^.PBpar; */
+    elemfamp->ElemF.W->Porder = order;
+    x = elemfamp->ElemF.W->PBW[Quad + HOMmax];
+    for (i = 1; i <= elemfamp->nKid; i++) {
+        cellp = &Cell[elemfamp->KidList[i - 1]];
+        Wiggler_Alloc(&cellp->Elem);
+        memcpy(cellp->Elem.PName, elemfamp->ElemF.PName, sizeof(partsName));
+        cellp->Elem.PL = elemfamp->ElemF.PL;
+        cellp->Elem.Pkind = elemfamp->ElemF.Pkind;
+        *cellp->Elem.W = *elemfamp->ElemF.W;
+
+        elemp = &cellp->Elem;
+        cellp->dT[0] = cos(dtor(elemp->M->PdTpar));
+        cellp->dT[1] = sin(dtor(elemp->M->PdTpar));
+
+        cellp->dS[0] = 0.0;
+        cellp->dS[1] = 0.0;
+        Wiggler_Setmatrix(Fnum1, i, cellp->Elem.PL, cellp->Elem.W->kxV[0], 2.0
+                * M_PI / cellp->Elem.W->lambda, x);
+    }
+}
+#undef order
 
-void Mpole_Init(int Fnum1)
-{
-  double       x;
-  int          i;
-  ElemFamType  *elemfamp;
-  CellType     *cellp;
-  elemtype     *elemp;
-
-  /* Pointer on element */
-  elemfamp = &ElemFam[Fnum1-1];
-  memcpy(elemfamp->ElemF.M->PB, elemfamp->ElemF.M->PBpar, sizeof(mpolArray));
-  /* Update the right multipole order */
-  elemfamp->ElemF.M->Porder = UpdatePorder(elemfamp->ElemF);
-  /* Quadrupole strength */
-  x = elemfamp->ElemF.M->PBpar[Quad+HOMmax];
-  for (i = 1; i <= elemfamp->nKid; i++) {
-    cellp = &Cell[elemfamp->KidList[i-1]];
-    /* Memory allocation and set everything to zero */
-    Mpole_Alloc(&cellp->Elem);
-    memcpy(cellp->Elem.PName, elemfamp->ElemF.PName, sizeof(partsName));
-    /* set length */
-    cellp->Elem.PL = elemfamp->ElemF.PL;
-    /* set element kind (Mpole) */
-    cellp->Elem.Pkind = elemfamp->ElemF.Pkind;
-    *cellp->Elem.M = *elemfamp->ElemF.M;
+/*
+ void get_Ax(const int m, const int n, float **By, FieldMapType *FM)
+ {
+ int  j, k;
 
-    elemp = &cellp->Elem;
-    /* set entrance and exit angles */
-    cellp->dT[0] = cos(dtor(elemp->M->PdTpar));
-    cellp->dT[1] = sin(dtor(elemp->M->PdTpar));
+ const double  Brho = 1e9*globval.Energy/c0;
 
-    /* set displacement to zero */
-    cellp->dS[0] = 0.0; cellp->dS[1] = 0.0;
+ FM->m_y = m; FM->n_s = n;
 
-    if (elemp->PL != 0.0 || elemp->M->Pirho != 0.0) {
-      /* Thick element or radius non zero element */
-      elemp->M->Pthick = pthicktype(thick);
-      /* sin(L*irho/2) =sin(theta/2) half the angle */
-      elemp->M->Pc0 = sin(elemp->PL*elemp->M->Pirho/2e0);
-      /* cos roll: sin(theta/2)*cos(dT) */
-      elemp->M->Pc1 = cellp->dT[0]*elemp->M->Pc0;
-      /* sin roll: sin(theta/2)*cos(dT) */
-      elemp->M->Ps1 = cellp->dT[1]*elemp->M->Pc0;
-      Mpole_Setmatrix(Fnum1, i, x);
-    } else /* element as thin lens */
-      elemp->M->Pthick = pthicktype(thin);
-  }
-}
+ for (j = 1; j <= m; j++) {
+ FM->AxoBrho[j][1] = 0.0;
+ for (k = 2; k <= n; k++)
+ FM->AxoBrho[j][k] =
+ FM->AxoBrho[j][k-1] + By[j][k]*(FM->s_pos[k]-FM->s_pos[k-1])/Brho;
+ }
 
+ splie2(FM->y_pos, FM->s_pos, FM->AxoBrho, FM->m_y, FM->n_s, FM->AxoBrho2);
+ }
 
-#define order           2
-void Wiggler_Init(int Fnum1)
-{
-  int          i;
-  double       x;
-  ElemFamType  *elemfamp;
-  CellType     *cellp;
-  elemtype     *elemp;
-
-  elemfamp = &ElemFam[Fnum1-1];
-  /* ElemF.M^.PB := ElemF.M^.PBpar; */
-  elemfamp->ElemF.W->Porder = order;
-  x = elemfamp->ElemF.W->PBW[Quad+HOMmax];
-  for (i = 1; i <= elemfamp->nKid; i++) {
-    cellp = &Cell[elemfamp->KidList[i-1]];
-    Wiggler_Alloc(&cellp->Elem);
-    memcpy(cellp->Elem.PName, elemfamp->ElemF.PName, sizeof(partsName));
-    cellp->Elem.PL = elemfamp->ElemF.PL;
-    cellp->Elem.Pkind = elemfamp->ElemF.Pkind;
-    *cellp->Elem.W = *elemfamp->ElemF.W;
 
-    elemp = &cellp->Elem;
-    cellp->dT[0] = cos(dtor(elemp->M->PdTpar));
-    cellp->dT[1] = sin(dtor(elemp->M->PdTpar));
+ void get_Ay(const int m, const int n, float **Bx, FieldMapType *FM)
+ {
+ int  j, k;
+
+ const double  Brho = 1e9*globval.Energy/c0;
+
+ FM->m_x = m; FM->n_s = n;
+
+ for (j = 1; j <= m; j++) {
+ FM->AyoBrho[j][1] = 0.0;
+ for (k = 2; k <= n; k++)
+ FM->AyoBrho[j][k] =
+ FM->AyoBrho[j][k-1] - Bx[j][k]*(FM->s_pos[k]-FM->s_pos[k-1])/Brho;
+ }
+
+ splie2(FM->x_pos, FM->s_pos, FM->AyoBrho, FM->m_x, FM->n_s, FM->AyoBrho2);
+ }
+ */
+
+void get_B(const char *file_name, FieldMapType *FM) {
+    char line[max_str];
+    int i, j, k, l;
+    ifstream inf;
+
+    printf("\n");
+    printf("reading field map %s\n", file_name);
+
+    file_rd(inf, file_name);
+
+    inf.getline(line, max_str);
+    // read number of steps
+    sscanf(line, "%d,%d,%d", &FM->n[X_], &FM->n[Y_], &FM->n[Z_]);
+    // skip comment
+    inf.getline(line, max_str);
+
+    i = 1;
+    j = 0;
+    k = 1;
+    while (inf.getline(line, max_str) != NULL) {
+        j++;
+        if (j > FM->n[Y_]) {
+            k++;
+            j = 1;
+        }
+        if (k > FM->n[Z_]) {
+            i++;
+            k = 1;
+        }
+
+        if ((i > i_max_FM) || (j > j_max_FM) || (k > k_max_FM)) {
+            printf("get_B: max index exceeded %d %d %d (%d %d %d)\n", i, j, k,
+                    i_max_FM, j_max_FM, k_max_FM);
+            exit_(1);
+        }
+
+        sscanf(line, "%lf,%lf,%lf,%lf,%lf,%lf", &FM->xyz[X_][i - 1][j - 1][k
+                - 1], &FM->xyz[Y_][i - 1][j - 1][k - 1], &FM->xyz[Z_][i - 1][j
+                - 1][k - 1], &FM->B[X_][i - 1][j - 1][k - 1],
+                &FM->B[Y_][i - 1][j - 1][k - 1],
+                &FM->B[Z_][i - 1][j - 1][k - 1]);
+        for (l = 0; l < 3; l++)
+            FM->xyz[l][i - 1][j - 1][k - 1] *= 1e-3;
+
+    }
+
+    printf("no of steps: n_x = %d, n_y = %d, n_z = %d\n", FM->n[X_], FM->n[Y_],
+            FM->n[Z_]);
 
-    cellp->dS[0] = 0.0; cellp->dS[1] = 0.0;
-    Wiggler_Setmatrix(Fnum1, i, cellp->Elem.PL,
-		      cellp->Elem.W->kxV[0], 2.0*M_PI/cellp->Elem.W->lambda,
-		      x);
-  }
+    //  get_Ay(m, n, FM->Bx, FM); prt_Bx(FM);
 }
-#undef order
 
-/*
-void get_Ax(const int m, const int n, float **By, FieldMapType *FM)
-{
-  int  j, k;
+void FieldMap_Init(int Fnum1) {
+    int i;
+    ElemFamType *elemfamp;
+    CellType *cellp;
+    elemtype *elemp;
+
+    elemfamp = &ElemFam[Fnum1 - 1];
+    for (i = 1; i <= elemfamp->nKid; i++) {
+        cellp = &Cell[elemfamp->KidList[i - 1]];
+        FieldMap_Alloc(&cellp->Elem, false);
+        memcpy(cellp->Elem.PName, elemfamp->ElemF.PName, sizeof(partsName));
+        cellp->Elem.PL = elemfamp->ElemF.PL;
+        cellp->Elem.Pkind = elemfamp->ElemF.Pkind;
+        *cellp->Elem.FM = *elemfamp->ElemF.FM;
+
+        elemp = &cellp->Elem;
+        cellp->dT[0] = 1.0;
+        cellp->dT[1] = 0.0;
+        cellp->dS[X_] = 0.0;
+        cellp->dS[Y_] = 0.0;
+    }
+}
 
-  const double  Brho = 1e9*globval.Energy/c0;
+/****************************************************************************
+ * void Cav_Init(long Fnum1)
 
-  FM->m_y = m; FM->n_s = n;
+ Purpose: called by Cell_Init()
+ Constructor for a cavity
+ set the RF voltage, frequency read from the lattice file
 
-  for (j = 1; j <= m; j++) {
-    FM->AxoBrho[j][1] = 0.0;
-    for (k = 2; k <= n; k++)
-      FM->AxoBrho[j][k] =
-	FM->AxoBrho[j][k-1] + By[j][k]*(FM->s_pos[k]-FM->s_pos[k-1])/Brho;
-  }
+ Input:
+ Fnum1 Family number
 
-  splie2(FM->y_pos, FM->s_pos, FM->AxoBrho, FM->m_y, FM->n_s, FM->AxoBrho2);
-}
+ Output:
+ none
 
+ Return:
+ none
 
-void get_Ay(const int m, const int n, float **Bx, FieldMapType *FM)
-{
-  int  j, k;
+ Global variables:
+ ElemFam, Cell
 
-  const double  Brho = 1e9*globval.Energy/c0;
+ Specific functions:
+ none
 
-  FM->m_x = m; FM->n_s = n;
+ Comments:
+ none
 
-  for (j = 1; j <= m; j++) {
-    FM->AyoBrho[j][1] = 0.0;
-    for (k = 2; k <= n; k++)
-      FM->AyoBrho[j][k] =
-	FM->AyoBrho[j][k-1] - Bx[j][k]*(FM->s_pos[k]-FM->s_pos[k-1])/Brho;
-  }
+ ****************************************************************************/
+void Cav_Init(int Fnum1) {
+    int i;
+    ElemFamType *elemfamp;
+    elemtype *elemp;
+    CellType *cellp;
 
-  splie2(FM->x_pos, FM->s_pos, FM->AyoBrho, FM->m_x, FM->n_s, FM->AyoBrho2);
+    elemfamp = &ElemFam[Fnum1 - 1];
+    elemp = &elemfamp->ElemF;
+    for (i = 0; i < elemfamp->nKid; i++) {
+        cellp = &Cell[elemfamp->KidList[i]];
+        cellp->Elem = elemfamp->ElemF;
+    }
 }
-*/
 
-void get_B(const char *file_name, FieldMapType *FM)
-{
-  char      line[max_str];
-  int       i, j, k, l;
-  ifstream  inf;
+void Marker_Init(int Fnum1) {
+    int i;
+    ElemFamType *elemfamp;
+    elemtype *elemp;
+    CellType *cellp;
+
+    elemfamp = &ElemFam[Fnum1 - 1];
+    elemp = &elemfamp->ElemF;
+    for (i = 0; i < elemfamp->nKid; i++) {
+        cellp = &Cell[elemfamp->KidList[i]];
+        cellp->Elem = elemfamp->ElemF;
+        cellp->dT[0] = 1.0;
+        cellp->dT[1] = 0.0;
+        cellp->dS[0] = 0.0;
+        cellp->dS[1] = 0.0;
+    }
+}
+
+/****************************************************************************
+ *                              INSERTION                                   *
+ ****************************************************************************/
+
+/****************************************************************************
+ * void Insertion_Init(long Fnum1)
+
+ Purpose: called by Cell_Init
+ Initializes the insertion
+ Fills in all the parameters read in the RADIA file
+ Constructs the linear matrix
+
+ Input:
+ Fnum1: family number
+
+ Output:
+ none
+
+ Return:
+ none
+
+ Global variables:
+ none
+
+ Specific functions:
+ none
+
+ Comments:
+ none
+
+ ****************************************************************************/
 
-  printf("\n");
-  printf("reading field map %s\n", file_name);
+void Insertion_Init(int Fnum1) {
+    int i;
+    ElemFamType *elemfamp;
+    CellType *cellp;
+    elemtype *elemp;
 
-  file_rd(inf, file_name);
+    elemfamp = &ElemFam[Fnum1 - 1];
+    //  elemfamp->ElemF.ID->Porder = order;
+    //  x = elemfamp->ElemF.ID->PBW[Quad + HOMmax];
+    for (i = 1; i <= elemfamp->nKid; i++) {
+        cellp = &Cell[elemfamp->KidList[i - 1]];
+        Insertion_Alloc(&cellp->Elem);
+        memcpy(cellp->Elem.PName, elemfamp->ElemF.PName, sizeof(partsName));
+        cellp->Elem.PL = elemfamp->ElemF.PL;
+        cellp->Elem.Pkind = elemfamp->ElemF.Pkind;
+        *cellp->Elem.ID = *elemfamp->ElemF.ID;
 
-  inf.getline(line, max_str);
-  // read number of steps
-  sscanf(line, "%d,%d,%d", &FM->n[X_], &FM->n[Y_], &FM->n[Z_]);
-  // skip comment
-  inf.getline(line, max_str);
+        elemp = &cellp->Elem;
 
-  i = 1; j = 0; k = 1;
-  while (inf.getline(line, max_str) != NULL) {
-    j++;
-    if (j > FM->n[Y_]) {
-      k++; j = 1;
+        cellp->dT[0] = cos(dtor(elemp->ID->PdTpar));
+        cellp->dT[1] = sin(dtor(elemp->ID->PdTpar));
+        cellp->dS[0] = 0.0;
+        cellp->dS[1] = 0.0;
+
+        Insertion_SetMatrix(Fnum1, i);
+    }
+}
+
+void Spreader_Init(int Fnum1) {
+    int i;
+    ElemFamType *elemfamp;
+    CellType *cellp;
+
+    elemfamp = &ElemFam[Fnum1 - 1];
+    for (i = 1; i <= elemfamp->nKid; i++) {
+        /* Get in Cell kid # i from Family Fnum1 */
+        cellp = &Cell[elemfamp->KidList[i - 1]];
+        /* Dynamic memory allocation for element */
+        Spreader_Alloc(&cellp->Elem);
+        /* copy low level routine */
+        memcpy(cellp->Elem.PName, elemfamp->ElemF.PName, sizeof(partsName));
+        /* set the kind of element */
+        cellp->Elem.Pkind = elemfamp->ElemF.Pkind;
+        /* set pointer for the dynamic space */
+        *cellp->Elem.Spr = *elemfamp->ElemF.Spr;
+        cellp->dT[0] = 1e0; /* cos = 1 */
+        cellp->dT[1] = 0.0; /* sin = 0 */
+        cellp->dS[0] = 0.0; /* no H displacement */
+        cellp->dS[1] = 0.0; /* no V displacement */
     }
-    if (k > FM->n[Z_]) {
-      i++; k = 1;
+}
+
+void Recombiner_Init(int Fnum1) {
+    int i;
+    ElemFamType *elemfamp;
+    CellType *cellp;
+
+    elemfamp = &ElemFam[Fnum1 - 1];
+    for (i = 1; i <= elemfamp->nKid; i++) {
+        /* Get in Cell kid # i from Family Fnum1 */
+        cellp = &Cell[elemfamp->KidList[i - 1]];
+        /* Dynamic memory allocation for element */
+        Spreader_Alloc(&cellp->Elem);
+        /* copy low level routine */
+        memcpy(cellp->Elem.PName, elemfamp->ElemF.PName, sizeof(partsName));
+        /* set the kind of element */
+        cellp->Elem.Pkind = elemfamp->ElemF.Pkind;
+        /* set pointer for the dynamic space */
+        *cellp->Elem.Rec = *elemfamp->ElemF.Rec;
+        cellp->dT[0] = 1e0; /* cos = 1 */
+        cellp->dT[1] = 0.0; /* sin = 0 */
+        cellp->dS[0] = 0.0; /* no H displacement */
+        cellp->dS[1] = 0.0; /* no V displacement */
     }
+}
 
-    if ((i > i_max_FM) || (j > j_max_FM) || (k > k_max_FM)) {
-      printf("get_B: max index exceeded %d %d %d (%d %d %d)\n",
-	     i, j, k, i_max_FM, j_max_FM, k_max_FM);
-      exit_(1);
+void Solenoid_Init(int Fnum1) {
+    int i;
+    ElemFamType *elemfamp;
+    CellType *cellp;
+    elemtype *elemp;
+
+    /* Pointer on element */
+    elemfamp = &ElemFam[Fnum1 - 1];
+    for (i = 1; i <= elemfamp->nKid; i++) {
+        cellp = &Cell[elemfamp->KidList[i - 1]];
+        /* Memory allocation and set everything to zero */
+        Solenoid_Alloc(&cellp->Elem);
+        memcpy(cellp->Elem.PName, elemfamp->ElemF.PName, sizeof(partsName));
+        /* set length */
+        cellp->Elem.PL = elemfamp->ElemF.PL;
+        /* set element kind */
+        cellp->Elem.Pkind = elemfamp->ElemF.Pkind;
+        *cellp->Elem.Sol = *elemfamp->ElemF.Sol;
+
+        elemp = &cellp->Elem;
+        /* set entrance and exit angles */
+        cellp->dT[0] = 1.0;
+        cellp->dT[1] = 0.0;
+
+        /* set displacement to zero */
+        cellp->dS[0] = 0.0;
+        cellp->dS[1] = 0.0;
     }
+}
 
-    sscanf(line, "%lf,%lf,%lf,%lf,%lf,%lf",
-	   &FM->xyz[X_][i-1][j-1][k-1], &FM->xyz[Y_][i-1][j-1][k-1],
-	   &FM->xyz[Z_][i-1][j-1][k-1],
-	   &FM->B[X_][i-1][j-1][k-1], &FM->B[Y_][i-1][j-1][k-1],
-	   &FM->B[Z_][i-1][j-1][k-1]);
-    for (l = 0; l < 3; l++)
-      FM->xyz[l][i-1][j-1][k-1] *= 1e-3;
+/**************************************************************************************
+ void Mpole_SetPB(int Fnum1, int Knum1, int Order)
 
-  }
+ Purpose:
+ called by Cell_SetdP
+ Compute full multipole composent as sum of design, systematic
+ and random part
+ Compute transport matrix if quadrupole (Order=2)
+ Set multipole order to Order if multipole (Order >2)
 
-  printf("no of steps: n_x = %d, n_y = %d, n_z = %d\n",
-	 FM->n[X_], FM->n[Y_], FM->n[Z_]);
+ Input:
+ Fnum1        family name
+ Knum1        kid number
+ Order        maximum order of the multipole
 
-//  get_Ay(m, n, FM->Bx, FM); prt_Bx(FM);
-}
+ Output:
+ None
 
+ Return:
+ None
 
-void FieldMap_Init(int Fnum1)
-{
-  int          i;
-  ElemFamType  *elemfamp;
-  CellType     *cellp;
-  elemtype     *elemp;
-
-  elemfamp = &ElemFam[Fnum1-1];
-  for (i = 1; i <= elemfamp->nKid; i++) {
-    cellp = &Cell[elemfamp->KidList[i-1]];
-    FieldMap_Alloc(&cellp->Elem, false);
-    memcpy(cellp->Elem.PName, elemfamp->ElemF.PName, sizeof(partsName));
-    cellp->Elem.PL = elemfamp->ElemF.PL;
-    cellp->Elem.Pkind = elemfamp->ElemF.Pkind;
-    *cellp->Elem.FM = *elemfamp->ElemF.FM;
+ Gloval variables:
+ None
+
+ Specific functions:
 
+ Comments:
+ None
+
+ **************************************************************************************/
+void Mpole_SetPB(int Fnum1, int Knum1, int Order) {
+    /*               */
+
+    CellType *cellp; /* pointer on the Cell */
+    elemtype *elemp; /* pointer on the Elemetype */
+    MpoleType *M;/* Pointer on the Multipole */
+
+    cellp = &Cell[ElemFam[Fnum1 - 1].KidList[Knum1 - 1]];
     elemp = &cellp->Elem;
-    cellp->dT[0] = 1.0; cellp->dT[1] = 0.0;
-    cellp->dS[X_] = 0.0; cellp->dS[Y_] = 0.0;
-  }
+    M = elemp->M;
+    M->PB[Order + HOMmax] = M->PBpar[Order + HOMmax] + M->PBsys[Order + HOMmax]
+            + M->PBrms[Order + HOMmax] * M->PBrnd[Order + HOMmax];
+    if (abs(Order) > M->Porder && M->PB[Order + HOMmax] != 0.0)
+        M->Porder = abs(Order);
+    if (M->Pmethod == Meth_Linear && Order == 2L)
+        Mpole_Setmatrix(Fnum1, Knum1, M->PB[Order + HOMmax]);
+    cellconcat = false;
 }
 
+/**************************************************************************************
+ double Mpole_GetPB(int Fnum1, int Knum1, int Order)
 
-/****************************************************************************
- * void Cav_Init(long Fnum1)
+ Purpose:
+ Return multipole strength (of order Order) for Knum1 element of
+ family Fnum1
+ Order =  2 for normal quadrupole, bn components
+ = -2 for skew quadrupole    an components
 
-   Purpose: called by Cell_Init()
-       Constructor for a cavity
-       set the RF voltage, frequency read from the lattice file
+ Input:
+ Fnum1        family name
+ Knum1        kid number
+ Order        order of the multipole
 
-   Input:
-       Fnum1 Family number
+ Output:
+ None
 
-   Output:
-       none
+ Return:
+ None
 
-   Return:
-       none
+ Gloval variables:
+ None
 
-   Global variables:
-       ElemFam, Cell
+ Specific functions:
 
-   Specific functions:
-       none
+ Comments:
+ None
 
-   Comments:
-       none
+ **************************************************************************************/
+double Mpole_GetPB(int Fnum1, int Knum1, int Order) {
 
-****************************************************************************/
-void Cav_Init(int Fnum1)
-{
-  int          i;
-  ElemFamType  *elemfamp;
-  elemtype     *elemp;
-  CellType     *cellp;
+    MpoleType *M; /* Pointer on the multipole */
 
-  elemfamp = &ElemFam[Fnum1-1]; elemp = &elemfamp->ElemF;
-  for (i = 0; i < elemfamp->nKid; i++) {
-    cellp = &Cell[elemfamp->KidList[i]]; cellp->Elem = elemfamp->ElemF;
-  }
+    M = Cell[ElemFam[Fnum1 - 1].KidList[Knum1 - 1]].Elem.M;
+    return (M->PB[Order + HOMmax]);
 }
 
+void Mpole_DefPBpar(int Fnum1, int Knum1, int Order, double PBpar) {
+    elemtype *elemp;
+    MpoleType *M;
 
-void Marker_Init(int Fnum1)
-{
-  int          i;
-  ElemFamType  *elemfamp;
-  elemtype     *elemp;
-  CellType     *cellp;
+    elemp = &Cell[ElemFam[Fnum1 - 1].KidList[Knum1 - 1]].Elem;
+    M = elemp->M;
 
-  elemfamp = &ElemFam[Fnum1-1]; elemp  = &elemfamp->ElemF;
-  for (i = 0; i < elemfamp->nKid; i++) {
-    cellp = &Cell[elemfamp->KidList[i]]; cellp->Elem  = elemfamp->ElemF;
-    cellp->dT[0] = 1.0; cellp->dT[1] = 0.0;
-    cellp->dS[0] = 0.0; cellp->dS[1] = 0.0;
-  }
+    M->PBpar[Order + HOMmax] = PBpar;
 }
 
+void Mpole_DefPBsys(int Fnum1, int Knum1, int Order, double PBsys) {
+    /*Fnum1, Knum1, Order : integer*/
+    elemtype *elemp;
+    MpoleType *M;
 
-void Insertion_Init(int Fnum1)
-{
-  int          i;
-  ElemFamType  *elemfamp;
-  CellType     *cellp;
-  elemtype     *elemp;
-
-  elemfamp = &ElemFam[Fnum1-1];
-//  elemfamp->ElemF.ID->Porder = order;
-//  x = elemfamp->ElemF.ID->PBW[Quad + HOMmax];
-  for (i = 1; i <= elemfamp->nKid; i++) {
-    cellp = &Cell[elemfamp->KidList[i-1]];
-    Insertion_Alloc(&cellp->Elem);
-    memcpy(cellp->Elem.PName, elemfamp->ElemF.PName, sizeof(partsName));
-    cellp->Elem.PL = elemfamp->ElemF.PL;
-    cellp->Elem.Pkind = elemfamp->ElemF.Pkind;
-    *cellp->Elem.ID = *elemfamp->ElemF.ID;
+    elemp = &Cell[ElemFam[Fnum1 - 1].KidList[Knum1 - 1]].Elem;
+    M = elemp->M;
 
-    elemp = &cellp->Elem;
+    M->PBsys[Order + HOMmax] = PBsys;
+}
 
-    cellp->dT[0] = cos(dtor(elemp->ID->PdTpar));
-    cellp->dT[1] = sin(dtor(elemp->ID->PdTpar));
-    cellp->dS[0] = 0.0; cellp->dS[1] = 0.0;
+void Mpole_SetdS(int Fnum1, int Knum1) {
+    int j;
+    CellType *cellp;
+    elemtype *elemp;
+    MpoleType *M;
 
-    Insertion_SetMatrix(Fnum1, i);
-  }
+    cellp = &Cell[ElemFam[Fnum1 - 1].KidList[Knum1 - 1]];
+    elemp = &cellp->Elem;
+    M = elemp->M;
+    for (j = 0; j <= 1; j++)
+        cellp->dS[j] = M->PdSsys[j] + M->PdSrms[j] * M->PdSrnd[j];
+    cellconcat = false;
 }
 
+void Mpole_SetdT(int Fnum1, int Knum1) {
+    CellType *cellp;
+    elemtype *elemp;
+    MpoleType *M;
 
-void Spreader_Init(int Fnum1)
-{
-  int          i;
-  ElemFamType  *elemfamp;
-  CellType     *cellp;
-
-  elemfamp = &ElemFam[Fnum1-1];
-  for (i = 1; i <= elemfamp->nKid; i++) {
-    /* Get in Cell kid # i from Family Fnum1 */
-    cellp = &Cell[elemfamp->KidList[i-1]];
-    /* Dynamic memory allocation for element */
-    Spreader_Alloc(&cellp->Elem);
-    /* copy low level routine */
-    memcpy(cellp->Elem.PName, elemfamp->ElemF.PName, sizeof(partsName));
-    /* set the kind of element */
-    cellp->Elem.Pkind = elemfamp->ElemF.Pkind;
-    /* set pointer for the dynamic space */
-    *cellp->Elem.Spr = *elemfamp->ElemF.Spr;
-    cellp->dT[0] = 1e0; /* cos = 1 */
-    cellp->dT[1] = 0.0; /* sin = 0 */
-    cellp->dS[0] = 0.0; /* no H displacement */
-    cellp->dS[1] = 0.0; /* no V displacement */
-  }
-}
-
-
-void Recombiner_Init(int Fnum1)
-{
-  int          i;
-  ElemFamType  *elemfamp;
-  CellType     *cellp;
-
-  elemfamp = &ElemFam[Fnum1-1];
-  for (i = 1; i <= elemfamp->nKid; i++) {
-    /* Get in Cell kid # i from Family Fnum1 */
-    cellp = &Cell[elemfamp->KidList[i-1]];
-    /* Dynamic memory allocation for element */
-    Spreader_Alloc(&cellp->Elem);
-    /* copy low level routine */
-    memcpy(cellp->Elem.PName, elemfamp->ElemF.PName, sizeof(partsName));
-    /* set the kind of element */
-    cellp->Elem.Pkind = elemfamp->ElemF.Pkind;
-    /* set pointer for the dynamic space */
-    *cellp->Elem.Rec = *elemfamp->ElemF.Rec;
-    cellp->dT[0] = 1e0; /* cos = 1 */
-    cellp->dT[1] = 0.0; /* sin = 0 */
-    cellp->dS[0] = 0.0; /* no H displacement */
-    cellp->dS[1] = 0.0; /* no V displacement */
-  }
-}
-
-
-void Solenoid_Init(int Fnum1)
-{
-  int          i;
-  ElemFamType  *elemfamp;
-  CellType     *cellp;
-  elemtype     *elemp;
-
-  /* Pointer on element */
-  elemfamp = &ElemFam[Fnum1-1];
-  for (i = 1; i <= elemfamp->nKid; i++) {
-    cellp = &Cell[elemfamp->KidList[i-1]];
-    /* Memory allocation and set everything to zero */
-    Solenoid_Alloc(&cellp->Elem);
-    memcpy(cellp->Elem.PName, elemfamp->ElemF.PName, sizeof(partsName));
-    /* set length */
-    cellp->Elem.PL = elemfamp->ElemF.PL;
-    /* set element kind */
-    cellp->Elem.Pkind = elemfamp->ElemF.Pkind;
-    *cellp->Elem.Sol = *elemfamp->ElemF.Sol;
-
+    cellp = &Cell[ElemFam[Fnum1 - 1].KidList[Knum1 - 1]];
     elemp = &cellp->Elem;
-    /* set entrance and exit angles */
-    cellp->dT[0] = 1.0; cellp->dT[1] = 0.0;
-
-    /* set displacement to zero */
-    cellp->dS[0] = 0.0; cellp->dS[1] = 0.0;
-  }
+    M = elemp->M;
+    cellp->dT[0] = cos(dtor(M->PdTpar + M->PdTsys + M->PdTrms * M->PdTrnd));
+    cellp->dT[1] = sin(dtor(M->PdTpar + M->PdTsys + M->PdTrms * M->PdTrnd));
+    /* Calculate simplified p_rots */
+    M->Pc0 = sin(elemp->PL * M->Pirho / 2e0);
+    M->Pc1 = cos(dtor(M->PdTpar)) * M->Pc0;
+    M->Ps1 = sin(dtor(M->PdTpar)) * M->Pc0;
+    cellconcat = false;
 }
 
-/**************************************************************************************
-void Mpole_SetPB(int Fnum1, int Knum1, int Order)
-
-  Purpose:
-      called by Cell_SetdP
-       Compute full multipole composent as sum of design, systematic
-       and random part
-       Compute transport matrix if quadrupole (Order=2)
-       Set multipole order to Order if multipole (Order >2)     
-       
-  Input:
-      Fnum1        family name
-      Knum1        kid number
-      Order        maximum order of the multipole
-      
-  Output: 
-      None
-  
-  Return:
-      None
-     
-  Gloval variables:
-      None
-      
-  Specific functions:
-  
-  Comments:
-     None
-  
-**************************************************************************************/
-void Mpole_SetPB(int Fnum1, int Knum1, int Order)
-{
-  /*               */
-
-  CellType *cellp;  /* pointer on the Cell */
-  elemtype *elemp; /* pointer on the Elemetype */
-  MpoleType *M;/* Pointer on the Multipole */
+/****************************************************************************/
+/* double Mpole_GetdT(long Fnum1, long Knum1)
 
-  cellp  = &Cell[ElemFam[Fnum1-1].KidList[Knum1-1]];
-  elemp = &cellp->Elem; M = elemp->M;
-  M->PB[Order+HOMmax] =
-    M->PBpar[Order+HOMmax] + M->PBsys[Order+HOMmax] +
-    M->PBrms[Order+HOMmax]*M->PBrnd[Order+HOMmax];
-  if (abs(Order) > M->Porder && M->PB[Order+HOMmax] != 0.0)
-    M->Porder = abs(Order);
-  if (M->Pmethod == Meth_Linear && Order == 2L)
-    Mpole_Setmatrix(Fnum1, Knum1, M->PB[Order+HOMmax]);
-  cellconcat = false;
-}
+ Purpose:
+ Return total roll angle of the element
+ Cell[ElemFam[Fnum1 - 1].KidList[Knum1 - 1]].Elem, which is
+ a sum of a design ,a systematic error and a random error part.
 
-/**************************************************************************************
-double Mpole_GetPB(int Fnum1, int Knum1, int Order)
-
-  Purpose:
-         Return multipole strength (of order Order) for Knum1 element of
-      family Fnum1
-       Order =  2 for normal quadrupole, bn components
-             = -2 for skew quadrupole    an components
-       
-  Input:
-      Fnum1        family name
-      Knum1        kid number
-      Order        order of the multipole
-      
-  Output: 
-      None
-  
-  Return:
-      None
-     
-  Gloval variables:
-      None
-      
-  Specific functions:
-  
-  Comments:
-     None
-  
-**************************************************************************************/
-double Mpole_GetPB(int Fnum1, int Knum1, int Order)
-{
-       
-  MpoleType *M; /* Pointer on the multipole */
 
-  M = Cell[ElemFam[Fnum1-1].KidList[Knum1-1]].Elem.M;
-  return (M->PB[Order+HOMmax]);
-}
+ Input:
+ none
 
+ Output:
+ none
 
-void Mpole_DefPBpar(int Fnum1, int Knum1, int Order, double PBpar)
-{
-  elemtype   *elemp;
-  MpoleType  *M;
+ Return:
+ none
 
-  elemp = &Cell[ElemFam[Fnum1-1].KidList[Knum1-1]].Elem;
-  M = elemp->M;
+ Global variables:
+ none
 
-  M->PBpar[Order+HOMmax]=PBpar;
-}
+ Specific functions:
+ none
 
+ Comments:
+ none
 
-void Mpole_DefPBsys(int Fnum1, int Knum1, int Order, double PBsys)
-{
-  /*Fnum1, Knum1, Order : integer*/
-  elemtype *elemp;
-  MpoleType *M;
+ ****************************************************************************/
+double Mpole_GetdT(int Fnum1, int Knum1) {
+    elemtype *elemp;
+    MpoleType *M;
 
-  elemp = &Cell[ElemFam[Fnum1-1].KidList[Knum1-1]].Elem;
-  M = elemp->M;
+    elemp = &Cell[ElemFam[Fnum1 - 1].KidList[Knum1 - 1]].Elem;
+    M = elemp->M;
 
-  M->PBsys[Order+HOMmax]=PBsys;
+    return (M->PdTpar + M->PdTsys + M->PdTrms * M->PdTrnd);
 }
 
+/****************************************************************************
+ * void Mpole_DefdTpar(long Fnum1, long Knum1, double PdTpar)
 
-void Mpole_SetdS(int Fnum1, int Knum1)
-{
-  int       j;
-  CellType  *cellp;
-  elemtype  *elemp;
-  MpoleType *M;
+ Purpose:
+ Set design roll angle to {\ttfamily PdTpar} degrees.
 
-  cellp = &Cell[ElemFam[Fnum1-1].KidList[Knum1-1]];
-  elemp = &cellp->Elem; M = elemp->M;
-  for (j = 0; j <= 1; j++)
-    cellp->dS[j] = M->PdSsys[j] + M->PdSrms[j]*M->PdSrnd[j];
-  cellconcat = false;
-}
+ Input:
+ none
 
-void Mpole_SetdT(int Fnum1, int Knum1)
-{
-  CellType  *cellp;
-  elemtype  *elemp;
-  MpoleType *M;
+ Output:
+ none
 
-  cellp = &Cell[ElemFam[Fnum1-1].KidList[Knum1-1]];
-  elemp = &cellp->Elem; M = elemp->M;
-  cellp->dT[0] =
-    cos(dtor(M->PdTpar + M->PdTsys + M->PdTrms*M->PdTrnd));
-  cellp->dT[1] = sin(
-      dtor(M->PdTpar + M->PdTsys + M->PdTrms*M->PdTrnd));
-  /* Calculate simplified p_rots */
-  M->Pc0 = sin(elemp->PL*M->Pirho/2e0);
-  M->Pc1 = cos(dtor(M->PdTpar))*M->Pc0;
-  M->Ps1 = sin(dtor(M->PdTpar))*M->Pc0;
-  cellconcat = false;
-}
+ Return:
+ none
 
+ Global variables:
+ none
 
-double Mpole_GetdT(int Fnum1, int Knum1)
-{
-  elemtype  *elemp;
-  MpoleType *M;
+ Specific functions:
+ none
+
+ Comments:
+ none
+
+ ****************************************************************************/
+void Mpole_DefdTpar(int Fnum1, int Knum1, double PdTpar) {
+    elemtype *elemp;
+    MpoleType *M;
 
-  elemp = &Cell[ElemFam[Fnum1-1].KidList[Knum1-1]].Elem;
-  M = elemp->M;
+    elemp = &Cell[ElemFam[Fnum1 - 1].KidList[Knum1 - 1]].Elem;
+    M = elemp->M;
 
-  return(M->PdTpar + M->PdTsys + M->PdTrms*M->PdTrnd);
+    M->PdTpar = PdTpar;
 }
 
+/****************************************************************************
+ * void Mpole_DefdTsys(long Fnum1, long Knum1, double PdTsys)
 
-void Mpole_DefdTpar(int Fnum1, int Knum1, double PdTpar)
-{
-  elemtype  *elemp;
-  MpoleType *M;
+ Purpose:
+ Set systematic roll angle error to {\ttfamily PdTsys} degrees.
 
-  elemp = &Cell[ElemFam[Fnum1-1].KidList[Knum1-1]].Elem; M = elemp->M;
+ Input:
+ none
 
-  M->PdTpar = PdTpar;
-}
+ Output:
+ none
 
+ Return:
+ none
 
-void Mpole_DefdTsys(int Fnum1, int Knum1, double PdTsys)
-{
-  elemtype  *elemp;
-  MpoleType *M;
+ Global variables:
+ none
 
-  elemp = &Cell[ElemFam[Fnum1-1].KidList[Knum1-1]].Elem; M = elemp->M;
+ Specific functions:
+ none
 
-  M->PdTsys=PdTsys;
+ Comments:
+ none
+
+ ****************************************************************************/
+void Mpole_DefdTsys(int Fnum1, int Knum1, double PdTsys) {
+    elemtype *elemp;
+    MpoleType *M;
+
+    elemp = &Cell[ElemFam[Fnum1 - 1].KidList[Knum1 - 1]].Elem;
+    M = elemp->M;
+
+    M->PdTsys = PdTsys;
 }
 
+void Wiggler_SetPB(int Fnum1, int Knum1, int Order) {
+    CellType *cellp;
+    elemtype *elemp;
+    WigglerType *W;
 
-void Wiggler_SetPB(int Fnum1, int Knum1, int Order)
-{
-  CellType     *cellp;
-  elemtype     *elemp;
-  WigglerType  *W;
+    cellp = &Cell[ElemFam[Fnum1 - 1].KidList[Knum1 - 1]];
+    elemp = &cellp->Elem;
+    W = elemp->W;
+    if (abs(Order) > W->Porder)
+        W->Porder = abs(Order);
+    if (W->Pmethod == Meth_Linear && Order == 2)
+        Wiggler_Setmatrix(Fnum1, Knum1, elemp->PL, W->kxV[0], 2.0 * M_PI
+                / cellp->Elem.W->lambda, W->PBW[Order + HOMmax]);
+    cellconcat = false;
+}
 
-  cellp = &Cell[ElemFam[Fnum1-1].KidList[Knum1-1]]; elemp = &cellp->Elem;
-  W = elemp->W;
-  if (abs(Order) > W->Porder)
-    W->Porder = abs(Order);
-  if (W->Pmethod == Meth_Linear && Order == 2)
-    Wiggler_Setmatrix(Fnum1, Knum1, elemp->PL,
-		      W->kxV[0], 2.0*M_PI/cellp->Elem.W->lambda,
-                      W->PBW[Order+HOMmax]);
-  cellconcat = false;
+void Wiggler_SetdS(int Fnum1, int Knum1) {
+    int j;
+    CellType *cellp;
+    elemtype *elemp;
+    WigglerType *W;
+
+    cellp = &Cell[ElemFam[Fnum1 - 1].KidList[Knum1 - 1]];
+    elemp = &cellp->Elem;
+    W = elemp->W;
+    for (j = 0; j <= 1; j++)
+        cellp->dS[j] = W->PdSsys[j] + W->PdSrms[j] * W->PdSrnd[j];
+    cellconcat = false;
+    if (W->Pmethod == Meth_Linear)
+        Wiggler_Setmatrix(Fnum1, Knum1, elemp->PL, W->kxV[0], 2.0 * M_PI
+                / cellp->Elem.W->lambda, W->PBW[Quad + HOMmax]);
+    cellconcat = false;
 }
 
+void Wiggler_SetdT(int Fnum1, int Knum1) {
+    CellType *cellp;
+    elemtype *elemp;
+    WigglerType *W;
 
-void Wiggler_SetdS(int Fnum1, int Knum1)
-{
-  int         j;
-  CellType    *cellp;
-  elemtype    *elemp;
-  WigglerType *W;
-
-  cellp = &Cell[ElemFam[Fnum1-1].KidList[Knum1-1]];
-  elemp = &cellp->Elem; W = elemp->W;
-  for (j = 0; j <= 1; j++)
-    cellp->dS[j] = W->PdSsys[j]
-                   + W->PdSrms[j]*W->PdSrnd[j];
-  cellconcat = false;
-  if (W->Pmethod == Meth_Linear)
-    Wiggler_Setmatrix(Fnum1, Knum1, elemp->PL,
-		      W->kxV[0], 2.0*M_PI/cellp->Elem.W->lambda,
-                      W->PBW[Quad+HOMmax]);
-  cellconcat = false;
-}
-
-void Wiggler_SetdT(int Fnum1, int Knum1)
-{
-  CellType    *cellp;
-  elemtype    *elemp;
-  WigglerType *W;
-
-  cellp = &Cell[ElemFam[Fnum1-1].KidList[Knum1-1]];
-  elemp = &cellp->Elem; W = elemp->W;
-  cellp->dT[0] = cos(dtor(W->PdTpar+W->PdTsys+W->PdTrms*W->PdTrnd));
-  cellp->dT[1] = sin(dtor(W->PdTpar+W->PdTsys+W->PdTrms*W->PdTrnd));
-  if (W->Pmethod == Meth_Linear)
-    Wiggler_Setmatrix(Fnum1, Knum1, elemp->PL, W->kxV[0],
-		      2.0*M_PI/cellp->Elem.W->lambda,
-		      W->PBW[Quad+HOMmax]);
-  cellconcat = false;
+    cellp = &Cell[ElemFam[Fnum1 - 1].KidList[Knum1 - 1]];
+    elemp = &cellp->Elem;
+    W = elemp->W;
+    cellp->dT[0] = cos(dtor(W->PdTpar + W->PdTsys + W->PdTrms * W->PdTrnd));
+    cellp->dT[1] = sin(dtor(W->PdTpar + W->PdTsys + W->PdTrms * W->PdTrnd));
+    if (W->Pmethod == Meth_Linear)
+        Wiggler_Setmatrix(Fnum1, Knum1, elemp->PL, W->kxV[0], 2.0 * M_PI
+                / cellp->Elem.W->lambda, W->PBW[Quad + HOMmax]);
+    cellconcat = false;
 }
diff --git a/tracy/tracy/src/t2lat.cc b/tracy/tracy/src/t2lat.cc
index f446c2193ea6f2b7551beba02a7e0ce1f401561d..6f4a027991e8d8356227ff854e8ab880ae9d4e74 100644
--- a/tracy/tracy/src/t2lat.cc
+++ b/tracy/tracy/src/t2lat.cc
@@ -46,7 +46,7 @@ typedef enum
   cctsym, usesym, andsym, dspsym, kicksym, wglsym, nsym, mrksym,
   nbdsym, frgsym, latsym, mpsym, dbnsym, kssym, homsym, lmdsym, dtsym, xytsym,
   vrfsym, harnumsym, frqsym, gstsym, typsym, rollsym, idsym,
-  fnamesym1, fnamesym2, scalingsym, fmsym, harmsym, sprsym, recsym, solsym,
+  fnamesym1, fnamesym2, scalingsym1, scalingsym2, fmsym, harmsym, sprsym, recsym, solsym,
   ff1sym, ff2sym, ffscalingsym, tiltsym
 } Lat_symbol;   /*\*/
 // idsym fnamesym1 fnamesym2 scalingsym added for insertion
@@ -2034,8 +2034,7 @@ static bool Lat_DealElement(FILE **fi_, FILE **fo_, long *cc_, long *ll_,
   bool firstflag  = false; // flag for first kick input
   bool secondflag = false; // flag for second kick input
   long           i;
-  int            kx, kz;
-  double         scaling;
+  double         scaling1, scaling2;
 
   V.LINK = LINK;
   V.fi = fi_; V.fo = fo_; V.cc = cc_; V.ll = ll_; V.errpos = errpos_;
@@ -3190,7 +3189,7 @@ static bool Lat_DealElement(FILE **fi_, FILE **fo_, long *cc_, long *ll_,
          
     <name> : insertion,              
              N = <number of thin lenses>,
-             scaling = scaling factor: should be 1. Default value
+             scaling1 or 2 = scaling factor: should be 1. Default value
              file1 = <filename>, in lowercases (first order defaults)
              file2 = <filename>, in lowercases (second order defauts)
              method = <method>, ( 2 or 4. The method to divide Q into slices.)
@@ -3198,9 +3197,9 @@ static bool Lat_DealElement(FILE **fi_, FILE **fo_, long *cc_, long *ll_,
     
     Example
          
-      ID1 : insertion, scaling = 1, N=10, file2=hu80_lh;
-      ID2 : insertion, scaling = 1, N=10, file1=hu80_lh_bdl;
-      ID3 : insertion, scaling = 1, N=10, file1=hu80_lh_dbl; file2=hu80_lh;
+      ID1 : insertion, scaling2 = 1, N=10, file2="hu80_lh";
+      ID2 : insertion, scaling1 = 1, N=10, file1="hu80_lh_bdl";
+      ID3 : insertion, N=10, file1="hu80_lh_dbl"; file2="hu80_lh";
          
     Notes
       file1 and file2 must have the same structures and meshing
@@ -3208,153 +3207,169 @@ static bool Lat_DealElement(FILE **fi_, FILE **fo_, long *cc_, long *ll_,
     **************************************************************************/
 
   case idsym:
-    getest__(P_expset(SET, 1L << ((long)comma)), "<, > expected", &V);
-    GetSym__(&V);
-    QK  = 0e0; QKxV = 0e0; QKS = 0e0;
-    k1  = 1;
-    k2  = 1;       // 1 linear interpolation, 2 spline interpolation
-    dt  = 0e0;
-    scaling = 1.0; // scaling factor
-    P_addset(P_expset(mysys, 0), (long)nsym);
-    P_addset(mysys, (long)fnamesym1);
-    P_addset(mysys, (long)fnamesym2);
-    P_addset(mysys, (long)scalingsym);
-    P_addset(mysys, (long)mthsym);
-    do {
-      test__(mysys, "illegal parameter", &V);
-      sym1 = *V.sym;
-      getest__(P_expset(SET, 1L << ((long)eql)), "<=> expected", &V);
-      switch (sym1) {   
-
-      case nsym: /* Read number of sclices */
-	k1 = abs((long)floor(EVAL_(&V)));
-	GetSym__(&V); 
-	break;
-
-      case scalingsym: /* read scaling factor for debugging purpose*/
-	scaling = abs((long)floor(EVAL_(&V)));
-	break;
-
-      case fnamesym1: /* Read filename for insertion device first order kicks*/
-	firstflag = true;
-	GetSym__(&V);
-	for (i = 1; i < (signed)strlen(id_); i++) {
-	  if (id_[i] == '"')
-	    break;
-	  strncat(str1,&id_[i],1);
-	}
-	GetSym__(&V);
-	break;
-
-      case fnamesym2: /* Read filename for insertion
-			 device second order kicks */
-	secondflag = true;
-	GetSym__(&V);
-	for (i = 1; i < (signed)strlen(id_); i++) {
-	  if (id_[i] == '"')
-	    break;
-	  strncat(str2,&id_[i],1);
-	}
-	GetSym__(&V);
-	break;
-
-      case mthsym: // method for interpolation: 1 means linear 2 spline
-	k2 = (long)floor(EVAL_(&V) + 0.5);
-	if (k2 != Meth_Linear) globval.MatMeth = false;
-	break;
-      default:
-	break;
-      }
-      if (*V.sym == comma)
-	GetSym__(&V);
-    } while (P_inset(*V.sym, mysys));   /*5*/
-    GetSym__(&V);
-    globval.Elem_nFam++;
-
-    /* Fills up the ID */
-    if (globval.Elem_nFam <= Elem_nFamMax) {
-      WITH  = &ElemFam[globval.Elem_nFam-1];
-      WITH1 = &WITH->ElemF;
-      memcpy(WITH1->PName, ElementName, sizeof(partsName));
-      WITH1->Pkind = Insertion;
-      Insertion_Alloc(&WITH->ElemF);
-      WITH5 = WITH1->ID;
-      WITH5->Pmethod = k2;
-      WITH5->PN = k1;
-      WITH5->scaling = scaling;
-
-      // Check if filename given for first order kicks
-      if (firstflag) {
-	if (strcmp(str1,"") == 0)
-	  strcpy(WITH5->fname1,"/*No_Filename1_Given*/");
-	strcpy(WITH5->fname1,str1);
-	// Read Id file for first order kicks
-	WITH5->firstorder = true;
-	Read_IDfile(WITH5->fname1, &WITH1->PL, &WITH5->nx, &WITH5->nz,
-		    WITH5->tabx, WITH5->tabz, WITH5->thetax1, WITH5->thetaz1);
-	// scale factor from Radia: Tmm to get Tm.
-	for (kx = 0; kx < WITH5->nx; kx++) {
-	  for (kz = 0; kz < WITH5->nz; kz++) {
-	    WITH5->thetax1[kz][kx] = 1e-3*WITH5->thetax1[kz][kx];
-	    WITH5->thetaz1[kz][kx] = 1e-3*WITH5->thetaz1[kz][kx];
-	  }
-	}
-      } else {
-	strcpy(WITH5->fname1,"/*No_Filename1_Given*/");
-      }
-
-      // Check if filename given for Second order kicks
-      if (secondflag) {
-	if (strcmp(str2,"") != 0)
-	  strcpy(WITH5->fname2,"/*No_Filename2_Given*/");
-	strcpy(WITH5->fname2,str2);
-	WITH5->secondorder = secondflag;
-	// Read Id file for second order kicks
-	Read_IDfile(WITH5->fname2, &WITH1->PL, &WITH5->nx, &WITH5->nz,
-		    WITH5->tabx, WITH5->tabz, WITH5->thetax, WITH5->thetaz);
-      } else {
-	strcpy(WITH5->fname2,"/*No_Filename2_Given*/");
-      }
-
-      // check whether no Radia filename read: something is wrong
-      if (!firstflag && !secondflag) {
-	printf("Erreur no Insertion filename found as"
-	       " an input in lattice file\n");
-	exit_(-1);
-      }
-
-      if (k2 != 1) { // linear interpolation
-	WITH5->linear = false;
-      } else { // cubic interpolation
-	WITH5->linear = true;
-      }
-
-      // stuff for spline interpolation
-      if (!WITH5->linear) {
-	WITH5->tx = dmatrix(1,WITH5->nz,1,WITH5->nx);
-	WITH5->tz = dmatrix(1,WITH5->nz,1,WITH5->nx);
-	WITH5->tab1 = (double *)malloc((WITH5->nx)*sizeof(double));
-	WITH5->tab2 = (double *)malloc((WITH5->nz)*sizeof(double));
-	WITH5->f2x = dmatrix(1,WITH5->nz,1,WITH5->nx);
-	WITH5->f2z = dmatrix(1,WITH5->nz,1,WITH5->nx);
-	Matrices4Spline(WITH5);
-      }
-      // to put somewhere
-      //      /** Free memory **/
-      //      free(tab1);
-      //      free(tab2);
-      //
-      //      free_matrix(tx,1,nz,1,nx);
-      //      free_matrix(tz,1,nz,1,nx);
-      //      free_matrix(f2x,1,nz,1,nx);
-      //      free_matrix(f2z,1,nz,1,nx);
-
-    } else {
-      printf("Elem_nFamMax exceeded: %ld(%ld)\n",
-	     globval.Elem_nFam, (long)Elem_nFamMax);
-      exit_(1);
-    }
-    break;
+    getest__(P_expset(SET, 1L << ((long) comma)), "<, > expected", &V);
+        GetSym__(&V);
+        QK   = 0e0;
+        QKxV = 0e0;
+        QKS  = 0e0;
+        k1 = 1;
+        k2 = 3; // 1 linear interpolation, 3 spline interpolation
+        dt = 0e0;
+        scaling1 = 1.0; // scaling factor
+        scaling2 = 1.0; // scaling factor
+        P_addset(P_expset(mysys, 0), (long) nsym);
+        P_addset(mysys, (long) fnamesym1);
+        P_addset(mysys, (long) fnamesym2);
+        P_addset(mysys, (long) scalingsym1);
+        P_addset(mysys, (long) scalingsym2);
+        P_addset(mysys, (long) mthsym);
+        do {
+            test__(mysys, "illegal parameter", &V);
+            sym1 = *V.sym;
+            getest__(P_expset(SET, 1L << ((long) eql)), "<=> expected", &V);
+            switch (sym1) {
+
+            case nsym: /* Read number of slices */
+                k1 = abs((long) floor(EVAL_(&V)));
+                GetSym__(&V);
+                break;
+
+            case scalingsym1: /* read scaling factor for debugging purpose*/
+                scaling1 = abs((long) floor(EVAL_(&V)));
+                break;
+
+            case scalingsym2: /* read scaling factor for debugging purpose*/
+                scaling2 = abs((long) floor(EVAL_(&V)));
+                break;
+
+            case fnamesym1: /* Read filename for insertion device first order kicks*/
+                firstflag = true;
+                GetSym__(&V);
+                for (i = 1; i < (signed) strlen(id_); i++) {
+                    if (id_[i] == '"')
+                        break;
+                    strncat(str1, &id_[i], 1);
+                }
+                GetSym__(&V);
+                break;
+
+            case fnamesym2: /* Read filename for insertion
+             device second order kicks */
+                secondflag = true;
+                GetSym__(&V);
+                for (i = 1; i < (signed) strlen(id_); i++) {
+                    if (id_[i] == '"')
+                        break;
+                    strncat(str2, &id_[i], 1);
+                }
+                GetSym__(&V);
+                break;
+
+            case mthsym: // method for interpolation: 1 means linear 3 spline
+                k2 = (long) floor(EVAL_(&V));
+                if (k2 != Meth_Linear)
+                    globval.MatMeth = false;
+                break;
+            default:
+                break;
+            }
+            if (*V.sym == comma)
+                GetSym__(&V);
+        } while (P_inset(*V.sym, mysys)); /*5*/
+        GetSym__(&V);
+        globval.Elem_nFam++;
+
+        /* Fills up the ID */
+        if (globval.Elem_nFam <= Elem_nFamMax) {
+            WITH = &ElemFam[globval.Elem_nFam - 1];
+            WITH1 = &WITH->ElemF;
+            memcpy(WITH1->PName, ElementName, sizeof(partsName));
+            WITH1->Pkind = Insertion;
+            Insertion_Alloc(&WITH->ElemF);
+            WITH5 = WITH1->ID;
+            WITH5->Pmethod = k2;
+            WITH5->PN = k1;
+            WITH5->scaling1 = scaling1;
+            WITH5->scaling2 = scaling2;
+
+            // Check if filename given for first order kicks
+            if (firstflag) {
+                if (strcmp(str1, "") == 0)
+                    strcpy(WITH5->fname1, "/*No_Filename1_Given*/");
+                strcpy(WITH5->fname1, str1);
+                // Read Id file for first order kicks
+                WITH5->firstorder = true;
+                Read_IDfile(WITH5->fname1, &WITH1->PL, &WITH5->nx1,
+                        &WITH5->nz1, WITH5->tabx1, WITH5->tabz1, WITH5->thetax1,
+                        WITH5->thetaz1);
+            } else {
+                strcpy(WITH5->fname1, "/*No_Filename1_Given*/");
+            }
+
+            // Check if filename given for Second order kicks
+            if (secondflag) {
+                if (strcmp(str2, "") != 0)
+                    strcpy(WITH5->fname2, "/*No_Filename2_Given*/");
+                strcpy(WITH5->fname2, str2);
+                WITH5->secondorder = secondflag;
+                // Read Id file for second order kicks
+                Read_IDfile(WITH5->fname2, &WITH1->PL, &WITH5->nx2,
+                        &WITH5->nz2, WITH5->tabx2, WITH5->tabz2,
+                        WITH5->thetax2, WITH5->thetaz2);
+            } else {
+                strcpy(WITH5->fname2, "/*No_Filename2_Given*/");
+            }
+
+            // check whether no Radia filename read: something is wrong
+            if (!firstflag && !secondflag) {
+                printf("Erreur no Insertion filename found as"
+                    " an input in lattice file\n");
+                exit_(-1);
+            }
+
+            if (k2 == 3) { // cubic interpolation
+                WITH5->linear = false;
+            } else { // linear interpolation
+                WITH5->linear = true;
+            }
+
+            // stuff for spline interpolation
+            if (!WITH5->linear) {
+              if (firstflag){
+                WITH5->tx1 = dmatrix(1, WITH5->nz1, 1, WITH5->nx1);
+                WITH5->tz1 = dmatrix(1, WITH5->nz1, 1, WITH5->nx1);
+                WITH5->TabxOrd1 = (double *) malloc((WITH5->nx1) * sizeof(double));
+                WITH5->TabzOrd1 = (double *) malloc((WITH5->nz1) * sizeof(double));
+                WITH5->f2x1 = dmatrix(1, WITH5->nz1, 1, WITH5->nx1);
+                WITH5->f2z1 = dmatrix(1, WITH5->nz1, 1, WITH5->nx1);
+                Matrices4Spline(WITH5,1);}
+
+              if (secondflag){
+                WITH5->tx2 = dmatrix(1, WITH5->nz2, 1, WITH5->nx2);
+                WITH5->tz2 = dmatrix(1, WITH5->nz2, 1, WITH5->nx2);
+                WITH5->TabxOrd2 = (double *) malloc((WITH5->nx2) * sizeof(double));
+                WITH5->TabzOrd2 = (double *) malloc((WITH5->nz2) * sizeof(double));
+                WITH5->f2x2 = dmatrix(1, WITH5->nz2, 1, WITH5->nx2);
+                WITH5->f2z2 = dmatrix(1, WITH5->nz2, 1, WITH5->nx2);
+                Matrices4Spline(WITH5,2);}
+
+            }
+            // to put somewhere
+            //      /** Free memory **/
+            //      free(tab1);
+            //      free(tab2);
+            //
+            //      free_matrix(tx,1,nz,1,nx);
+            //      free_matrix(tz,1,nz,1,nx);
+            //      free_matrix(f2x,1,nz,1,nx);
+            //      free_matrix(f2z,1,nz,1,nx);
+
+        } else {
+            printf("Elem_nFamMax exceeded: %ld(%ld)\n", globval.Elem_nFam,
+                    (long) Elem_nFamMax);
+            exit_(1);
+        }
+        break;
 
     /**************************************************************************
        Spreader
@@ -3648,7 +3663,8 @@ static void init_reserved_words(struct LOC_Lattice_Read *LINK)
   Reg("quadrupole     ", qdsym, &V);
   Reg("recombiner     ", recsym, &V);
   Reg("roll           ", rollsym, &V);
-  Reg("scaling        ", scalingsym, &V); /* ID Laurent */
+  Reg("scaling1       ", scalingsym1, &V); /* ID Laurent */
+  Reg("scaling2       ", scalingsym2, &V); /* ID Laurent */
   Reg("sextupole      ", sexsym, &V);
   Reg("solenoid       ", solsym, &V);
   Reg("spreader       ", sprsym, &V);
@@ -3713,8 +3729,8 @@ static void init_reserved_words(struct LOC_Lattice_Read *LINK)
   P_addset(LINK->elmbegsys, (long)sprsym);
   P_addset(LINK->elmbegsys, (long)recsym);
   P_addset(LINK->elmbegsys, (long)solsym);
-//  P_addset(LINK->elmbegsys, (long)fnamesym1);  /* ID file name Laurent */
-//  P_addset(LINK->elmbegsys, (long)fnamesym2);  /* ID file name Laurent */
+  P_addset(LINK->elmbegsys, (long)fnamesym1);  /* ID file name Laurent */
+  P_addset(LINK->elmbegsys, (long)fnamesym2);  /* ID file name Laurent */
 //  P_addset(LINK->elmbegsys, (long)scalingsym); /* ID scale factor Laurent */
 }
 
@@ -4417,7 +4433,7 @@ bool Lattice_Read(FILE **fi_, FILE **fo_)
   if (*V.fo != NULL)
     fclose(*V.fo);  /* Close lax file */
   *V.fo = NULL;
-  RegisterKids(&V); /* Check wether too many elements */
+  RegisterKids(&V); /* Check whether too many elements */
   PrintResult(&V);  /* Print lattice statistics */
  _L9999:
   return (!ErrFlag);
diff --git a/tracy/tracy/src/t2ring.cc b/tracy/tracy/src/t2ring.cc
index 9d038efb4dcf45c278e5b83e1de6f27700357f8a..274ccf4b13b68a8a5e24afb6924da6f9ab602ea2 100644
--- a/tracy/tracy/src/t2ring.cc
+++ b/tracy/tracy/src/t2ring.cc
@@ -987,6 +987,7 @@ void Ring_Fittune(Vector2 &nu, double eps, iVector2 &nq, long qf[], long qd[],
   Vector2  nu0, nu1;
   Vector  dkL1, dnu;
   Matrix A;
+  bool prt = false;
 
   if (setjmp(V._JL999)) return;
 
@@ -1008,8 +1009,6 @@ void Ring_Fittune(Vector2 &nu, double eps, iVector2 &nq, long qf[], long qd[],
       }
       Ring_GetTwiss(false, dP);
       nu1[0] = globval.TotalTune[0]; nu1[1] = globval.TotalTune[1];
-//      GetCOD(globval.CODimax, globval.CODeps, dP, lastpos);
-//      Cell_GetABGN(globval.OneTurnMat, alpha, beta, gamma, nu1);
       checkifstable(&V);
       for (k = 0; k <= 1; k++) {
         dnu[k] = nu1[k] - (long)nu1[k] - nu0[k] + (long)nu0[k];
@@ -1045,12 +1044,19 @@ void Ring_Fittune(Vector2 &nu, double eps, iVector2 &nq, long qf[], long qd[],
     Ring_GetTwiss(false, dP); checkifstable(&V);
     memcpy(nu0, globval.TotalTune, sizeof(Vector2));
     if (trace)
-      printf("  Nux = %10.6f%10.6f, Nuy = %10.6f%10.6f,"
-	     " QF*L = % .5E, QD*L = % .5E @%3d\n",
+      printf("  Nux = %10.6f(%10.6f), Nuy = %10.6f(%10.6f),"
+	     " QFam1*L = % .5E, QFam2*L = % .5E @%3d\n",
 	     nu0[0], nu1[0], nu0[1], nu1[1],
 	     Elem_GetKval(Cell[qf[0]].Fnum, 1, (long)Quad),
 	     Elem_GetKval(Cell[qd[0]].Fnum, 1, (long)Quad), i);
   } while (sqrt(sqr(nu[0]-nu0[0])+sqr(nu[1]-nu0[1])) >= eps && i != imax);
+  if (prt)
+	  // print new K-value for 1s element of the family
+    printf("Reached  Nux = %10.6f, Nuy = %10.6f,"
+	     " QFam1*L = % .5E, QFam2*L = % .5E @iteration %3d\n",
+	     nu[0], nu[1],
+	     Elem_GetKval(Cell[qf[0]].Fnum, 1, (long)Quad),
+	     Elem_GetKval(Cell[qd[0]].Fnum, 1, (long)Quad), i);
 }
 #undef dP
 
diff --git a/tracy/tracy/src/tracy.cc b/tracy/tracy/src/tracy.cc
index 8fd397023a7f590b239ab2a7a71e42fa09be93a8..1e5ae152579e0a49f1de2c7fa21b9b9a5d555db9 100644
--- a/tracy/tracy/src/tracy.cc
+++ b/tracy/tracy/src/tracy.cc
@@ -179,10 +179,10 @@ template void LinearInterpolation2(tps &, tps &, tps &, tps &,
 				   CellType &, bool &, int);
 
 template void SplineInterpolation2(double &, double &, double &, double &,
-				   CellType &, bool &);
+				   CellType &, bool &, int);
 
 template void SplineInterpolation2(tps &, tps &, tps &, tps &,
-				   CellType &, bool &);
+				   CellType &, bool &, int);
 
 template void spline(const double [], const double [], int const,
 		     double const, const double, double []);