      program squishhkl
      character filename*80
      character string*80
      integer   lf
      integer   nd
      integer   nin,nout
      integer   h,k,l
      integer   m,oldm
      integer   code
      integer   oldh,oldk,oldl
      real      intensity,sigma
c      integer   i,sigi
      real      sumi,sums
      integer   n,nr,oldnr
      integer   error
      integer   in,out
      character message*256
 
      call finish(-6)
      error = 1
      call get_commandline
      call get_inp(filename,nd,'Sorted reflection filename',
     1 *900)
      call build_file(filename,' ','.SCR',filename,lf)
      call open_file(filename(1:lf),in,message,error)
      call str_write(6,message)
      if(error.ne.0) goto 900
 
      call create_file(filename(1:lf),out,message,error)
      call str_write(6,message)
      if(error.ne.0) goto 900
 
      n = 1
      sumi = 0.0
      sums = 0.0
      nin  = 0
      nout = 0
      read(in,*,iostat=error) oldm,oldh,oldk,oldl,sumi,sums,code,oldnr
      if(error.ne.0) then
        call str_write(6,'Error: empty input file')
        goto 900
      endif
      nin = 1
      read (in,*,iostat=error) m,h,k,l,intensity,sigma,code,nr
      do while(error.eq.0)
        nin = nin + 1
        if(m.eq.oldm) then
          n = n + 1
          sumi = sumi + intensity
          sums = sums + sigma
        else
          write (out,200) oldm,oldh,oldk,oldl,sumi/n,sums/n,code,oldnr
200       format(i10,3i5,2f10.2,i6,i6)
          nout = nout + 1
          n = 1
          sumi = intensity
          sums = sigma
        endif
        oldh = h
        oldk = k
        oldl = l
        oldm = m
        oldnr = nr
        read(in,*,iostat=error) m,h,k,l,intensity,sigma,code,nr
      enddo ! while error
      close(in)
      write (out,200) oldm,oldh,oldk,oldl,sumi/n,sums/n,code,nr
      nout = nout + 1
      close(out)
      call str_num(nin,'# reflection^ input',string)
      call str_write(6,string)
      call log_add(string)
      call str_num(nout,'# reflection^ output',string)
      call str_write(6,string)
      call log_add(string)
      error = 0
900   continue
      call log_close
      call finish(6)
      if(error.ne.0) then
        call exit(2)
      else
        call exit(1)
      endif
      end
