c  DETREND2.FOR
c
c  To detrend profile data by removing a least-squares-fit
c  linear trend.
c
      dimension x(2000),y(2000),f(2000)
      character*50 ifile,ofile
      print*,'Enter ascii profile xyz file name:'
      print 1
1     format(' *',$)
      read(5,2)ifile
2     format(a50)
      open(10,file=ifile,err=90,form='formatted',status='old')
      print*,'Enter output detrended file name:'
      print 1
      read(5,2)ofile
      open(11,file=ofile,form='formatted',status='new')
      i=0
100   i=i+1
      read(10,*,end=101)x(i),y(i),f(i)
      go to 100
101   continue
      n=i-1
      sx=0.
      sf=0.
      sxx=0.
      sfx=0.
      rn=n
      do 102 i=1,n
      sx=sx+x(i)
      sf=sf+f(i)
      sxx=sxx+x(i)*x(i)
      sfx=sfx+f(i)*x(i)
102   continue
      den=rn*sxx-sx*sx
      if(den.eq.0.)then
        print*,'Jacobian = 0, no solution possible'
        go to 99
      endif
      a=(sf*sxx-sx*sfx)/den
      b=(rn*sfx-sf*sx)/den
      print*,'A =',a,', B =',b
      do 103 i=1,n
      f(i)=f(i)-a-b*x(i)
      write(11,*)x(i),y(i),f(i)
103   continue
      go to 99
90    print*,'Problem opening file',ifile
99    stop
      end
