c
c----------------------------------------------------------------------------
c
      subroutine get_direction(costheta, sintheta, cosphi, sinphi, 
     1                         pos_tot)
c
c
c       T. Prokscha,    15-Sep-2000     PSI
c
c       Unix Version
c
c------------------------------------------------------------------------------
c
c       generates the initial direction of the decay-e+
c
      implicit none
c
#define CERNLIB_TYPE
#include "geant321/gctrak.inc"
#include        "common.inc"
c
      real*4 pos_tot                  ! total e+ energy including mass
      real*4 p                        ! polarization == bfield(4)
      real*4 costheta,phi             ! decay direction in rotated system
      real*4 sintheta
      real*4 cosphi, sinphi
      real*4 eps                      ! pos_tot/MAX_TOTAL_ENERGY
      real*4 Dw                       ! asymmetry factor
      real*4 random(3)
      real*4 x,y,z,r
c
c-----------------------------------------------------------------------------
c
        x = vect(1)
        y = vect(2)
        z = vect(3)
        r = sqrt(x**2 + y**2)
        if (1.4 .le. z .and. z .le. 1.41 .and. r .le. 3.5) then
           p = bfield(5) / 100.
        else
           p = bfield(4) / 100.
        endif
c
#if defined (OS_UNIX)
        call ranlux(random, 3)	! random generator from Mathlib
#else
        random(1) = ran(ix1)
        random(2) = ran(ix1)
        random(3) = ran(ix1)
#endif
        if (p.eq.0.0) then
c
          costheta = 1. - 2.*random(1)
c 
        else
c
c           see TP Logbook 7, p. 167 for getting the equations
c
          eps = pos_tot / MAX_TOTAL_ENERGY
          Dw = (2. * eps - 1.) / (3. - 2. * eps) * p

          costheta = 1/Dw*(-1. + 
     1               sqrt( 1. - 2*Dw*( 2.*random(2) - 1. ) + Dw**2))
        endif
c
        sintheta = sqrt(1. - costheta**2)
c
        phi=random(3) * TWO_PI
c
        cosphi = cos(phi)
        sinphi = sin(phi)
c
c       now we have the decay direction in the rest system of the muon
c       return.
c
        return
        end
