c
c
c     ###################################################
c     ##  COPYRIGHT (C)  1990  by  Jay William Ponder  ##
c     ##              All Rights Reserved              ##
c     ###################################################
c
c     ################################################################
c     ##                                                            ##
c     ##  subroutine writeout  --  update the optimization results  ##
c     ##                                                            ##
c     ################################################################
c
c
c     "writeout" is used by each of the optimization routines
c     to save imtermediate atomic coordinates to a disk file
c
c
      subroutine writeout (xx,ncycle)
      implicit none
      include 'sizes.i'
      include 'atoms.i'
      include 'files.i'
      include 'math.i'
      include 'omega.i'
      include 'output.i'
      include 'scales.i'
      include 'usage.i'
      include 'zcoord.i'
      integer i,iwrt,freeunit
      integer nvar,ncycle,lext
      real*8 xx(maxvar)
      character*3 status
      character*7 ext
      character*60 coordfile
c
c
c     transform optimization parameters back to coordinates
c
      if (coordtype .eq. 'none') then
         return
      else if (coordtype .eq. 'cartesian') then
         nvar = 0
         do i = 1, n
            if (use(i)) then
               nvar = nvar + 1
               x(i) = xx(nvar)
               nvar = nvar + 1
               y(i) = xx(nvar)
               nvar = nvar + 1
               z(i) = xx(nvar)
               if (scale .ne. 1.0d0) then
                  x(i) = x(i) / scale
                  y(i) = y(i) / scale
                  z(i) = z(i) / scale
               end if
            end if
         end do
      else if (coordtype .eq. 'internal') then
         do i = 1, nomega
            dihed(i) = xx(i)
            if (scale .ne. 1.0d0)  dihed(i) = dihed(i) / scale
            bet(zline(i)) = dihed(i) * radian
         end do
      end if
c
c     get the name to be used for the coordinates file
c
      if (savecycle) then
         lext = 3
         call numeral (ncycle,ext,lext)
         coordfile = filename(1:leng)//'.'//ext(1:lext)
         status = 'new'
      else
         coordfile = outfile
         status = 'old'
      end if
c
c     open and then update the coordinates file
c
      iwrt = freeunit ()
      call version (coordfile,status)
      open (unit=iwrt,file=coordfile,status=status)
      if (status .eq. 'old')  rewind (unit=iwrt)
      if (coordtype .eq. 'cartesian') then
         call prtxyz (iwrt)
      else if (coordtype .eq. 'internal') then
         call prtint (iwrt)
      else if (coordtype .eq. 'rigidbody') then
         call prtxyz (iwrt)
      end if
      close (unit=iwrt)
      return
      end
