      program xyz2rel
      implicit none
C     Available procedures
C     innerprod, det, invert
      double precision pos(3),rel(3)
      double precision a(3,3),inva(3,3)
      integer          natoms
      integer          i,j

      read(*,*) natoms
      read(*,*) ((a(i,j),j=1,3),i=1,3)
      call invert(a,inva)
      do i=1,natoms
        read(*,*) (pos(j),j=1,3)
        call innerprod(inva,pos,rel)
        write(*,10) (rel(j),j=1,3)
      end do
      stop
10    format(3f13.8)
      end

      subroutine innerprod(a,b,x)
      implicit none
      integer i,j
      double precision a(3,3),b(3),x(3)
      do i=1,3
        x(i)=0.0d0
        do j=1,3
          x(i)=x(i)+a(i,j)*b(j)
        end do
      end do
      return
      end

      double precision function det(a)
      implicit none
      double precision a(3,3),d
      d=0.0d0
      d=d+a(1,1)*(a(2,2)*a(3,3)-a(3,2)*a(2,3))
      d=d-a(1,2)*(a(2,1)*a(3,3)-a(3,1)*a(2,3))
      d=d+a(1,3)*(a(2,1)*a(3,2)-a(3,1)*a(2,2))
      det=d
      return
      end

      subroutine invert(a,x)
      implicit none
      double precision a(3,3),x(3,3)
      double precision d,det,temp(2,2)
      integer          i,j,k,l,m,n
      d=det(a)
      if (dabs(d) .lt. 1.0d-9) then
         write(*,*) 'determinant is zero',d
         write(*,*) 'termination forced.',d
         stop
         return
      end if
      do i=1,3
         do j=1,3
            m=0
            do k=1,3
               if (i .ne. k) then
                  m=m+1
                  n=0
                  do l=1,3
                     if (j .ne. l) then
                        n=n+1
                        temp(m,n)=a(k,l)
                     end if
                  end do
               end if
            end do
            x(j,i)=(temp(1,1)*temp(2,2)-
     >             temp(2,1)*temp(1,2))*(-1.0d0)**(i+j)/d
         end do
      end do
      return
      end

