      subroutine xopen(iunit,file,status,mode,itype,ierr)
c
c  opens a binary xyz or post file
c
c  iunit:       fortran unit number
c  file:        file name
c  status:      'new','old','unknown', or 'scratch'
c  mode:        'read','write',or 'readwrite'
c  itype:       0 for xyz
c               n for n-channel post (x = channel 1, y=channel 2)
c               -1 for ascii
c  ierr:        returns 0 on no error
c
      character file*(*),status*(*),mode*(*)
      character share*6,ans*1
      data maxpst/104/
c
      if(status.eq.'old'.or.status.eq.'OLD') then
        share='denywr'
      else
        share='compat'
      endif
      open(iunit,file=file,status=status,form='unformatted',
     & mode=mode,share=share,iostat=ierr)
      if(ierr.eq.6415) then
c          print*,ierr
        print'(a\)',' File exists -- OK to overwrite? [n] '
        read(5,20) ans
20      format(a)
        if(ans.eq.'y'.or.ans.eq.'Y') then
      open(iunit,file=file,status='unknown',form='unformatted',
     & mode=mode,share=share,iostat=ierr)
        endif
      endif
      if(ierr.ne.0) return
      if(mode.eq.'read'.or.mode.eq.'READ') then
        read(iunit,err=10,iostat=ios) itest
10      rewind(iunit)
        if (ios.ne.0) then
          close(iunit)
	  go to 100
	endif

c  file is binary
c  lenrec returns zero if buffer is too short
      nword = lenrec(iunit,maxpst)
        if (nword.eq.1.or.nword.eq.2) go to 200

c  simple xyz file.
        if (nword.eq.3) then
        print *, 'binary xyz data'
          itype=0
	  go to 999
	endif

c  simple post file.
        if (nword.ge.4.and.nword.le.maxpst) then
          nchan  = nword - 2
          nnchan=nchan-2
          write(6,220) nnchan
220       format(' post data, with ',i3,' data channels')
c        print *, ' post data,  found', nnchan, ' data channels'
          itype=nword-2
	  go to 999
	endif

c  open for ascii input
100     open(iunit,file=file,status=status,form='formatted',
     1       mode=mode,share=share,iostat=ierr)
        itype=-1
        print*,'ascii data'
	go to 999

c  record length undefined.
200   print *, 'input record length =', nword
      print *, 'input is neither xyz or post'
      ierr=1
      endif
999     return
      end
c******************************************************************************
c        function lenrec( iswt, irec, nwork )
        function lenrec( iswt, nwork )
c  brute force recovery of record length
        integer*4 irec(52)

	istep = 10
	if ( nwork .gt. 100 ) istep = 20
	if ( nwork .gt. 500 ) istep = 50
	rewind iswt

	do max = istep, nwork, istep
	  read( iswt, err=10 ) ( irec(i), i=1, max )
	  rewind iswt
	enddo
	lenrec = -1
	go to 99

10	rewind iswt
	do lenrec = max, max - istep, -1
	  read( iswt, err=20 ) ( irec(i), i=1, lenrec )
	  go to 99
20	  rewind iswt
	enddo

99	rewind iswt
	return
        end

