      function dihed(coori,coorj,coork,coorl)

c  this subroutine written by alain st-amant of the department of
c  pharmaceutical chemistry, university of california, san francisco.
c  all rights reserved.  this is part of the DeFT project.

      implicit real*8(a-h,o-z)

      dimension rij(3),rjk(3),rkj(3),rlk(3),vec1(3),vec2(3),vec3(3)

      dimension coori(*),coorj(*),coork(*),coorl(*)

      data one,two,pi,one80/1.0d0,2.0d0,3.1415926535898d0,180.0d0/

      rad2deg=one80/pi

      deg90=pi/two

      do 1001 i=1,3
 1001 rij(i)=coori(i)-coorj(i)

      do 1002 i=1,3
 1002 rjk(i)=coorj(i)-coork(i)

      do 1003 i=1,3
 1003 rkj(i)=coork(i)-coorj(i)

      do 1004 i=1,3
 1004 rlk(i)=coorl(i)-coork(i)

      call crossprod(vec1,rkj,rij)
      call crossprod(vec2,rlk,rjk)

      call crossprod(vec3,vec1,vec2)

      dihed=dmagvec(3,vec3)/dmagvec(3,vec2)/dmagvec(3,vec1)

      if(dihed.ge.+one) dihed=+one
      if(dihed.le.-one) dihed=-one

      dihed=asin(dihed)

      fac1=dot(3,vec1,vec2)/dmagvec(3,vec1)/dmagvec(3,vec2)

      if(fac1.ge.+one) fac1=+one
      if(fac1.le.-one) fac1=-one

      fac1=acos(fac1)

      fac2=dot(3,vec1,rlk)/dmagvec(3,vec1)/dmagvec(3,rlk)

      if(fac2.ge.+one) fac2=+one
      if(fac2.le.-one) fac2=-one

      fac2=acos(fac2)

      if((fac1.le.deg90).and.(fac2.le.deg90)) dihed=rad2deg*(+dihed)
      if((fac1.le.deg90).and.(fac2.gt.deg90)) dihed=rad2deg*(-dihed)
      if((fac1.gt.deg90).and.(fac2.le.deg90)) dihed=rad2deg*(pi-dihed)
      if((fac1.gt.deg90).and.(fac2.gt.deg90)) dihed=rad2deg*(dihed-pi)

      return
      end
