program minimize
  use gildas_def
  use gkernel_interfaces
  use image_def
  use gbl_format
  !---------------------------------------------------------------------
  ! GDF	Main program for finding best linear combination
  !		X(i,j) = A*Y(i,j) + B
  ! Subroutines
  !	GDF100
  !---------------------------------------------------------------------
  ! Global
  ! Local
  character(len=filename_length) :: namey,namex
  logical :: error
  real :: a,b
  type(gildas) :: x,y
  !
  call gildas_open
  call gildas_char('Y_NAME$',namey)
  call gildas_char('X_NAME$',namex)
  call gildas_close
  !
  call gildas_null(y)
  call gdf_read_gildas(y,namey,'.gdf',error,rank=0)
  if (error) goto 100
  !
  call gildas_null(x)
  call gdf_read_gildas(x,namex,'.gdf',error,rank=0)
  if (error) goto 100
  !
  call gdf100(x%loca%size,   &
     &    y%r1d,y%gil%bval,y%gil%eval,   &
     &    x%r1d,x%gil%bval,x%gil%eval,   &
     &    a,b)
  write(6,*) ' X = ',a,' * Y + ',b
  call gagout('I-MINI,  Successful completion')
  call sysexi (1)
  !
100 call sysexi (fatale)
end program minimize
!
subroutine gdf100(n, y,ybv,yev, x,xbv,xev, a,b)
  use gildas_def
  !---------------------------------------------------------------------
  ! GDF	Internal routine
  !	Find Linear combination of input arrays
  !	X = A*Y + B
  ! Arguments
  !	Y	R*4(*)	Input array
  !	X	R*4(*)	Output array
  !	N	I	Dimensions of arrays
  !	BVAL	R*4	Blanking values
  !	EVAL	R*4	Tolerance on blanking
  !	A	R*4	Multiplicative factor of array Y
  !	B	R*4	Additive constant
  !---------------------------------------------------------------------
  integer(kind=size_length) :: n                   !
  real :: y(n)                      !
  real :: ybv                       !
  real :: yev                       !
  real :: x(n)                      !
  real :: xbv                       !
  real :: xev                       !
  real :: a                         !
  real :: b                         !
  ! Local
  integer :: i,np
  real :: xm,ym,xym,y2m,r
  !
  np = 0
  xm = 0.
  ym = 0.
  xym = 0.
  y2m = 0.
  do i=1,n
    if (abs(x(i)-xbv).gt.xev .and.   &
     &      abs(y(i)-ybv).gt.yev) then
      np = np+1
      xm = xm + x(i)
      ym = ym + y(i)
      y2m = y2m + y(i)**2
      xym = xym + x(i)*y(i)
    endif
  enddo
  r = np*y2m - ym**2
  a = (np*xym - xm*ym) / r
  b = (xm*y2m - ym*xym) / r
  write(6,*) 'Number of pixels         ',n
  write(6,*) 'Number of blanked pixels ',n-np,   &
     &    float(n-np)/float(n)*100.,' %'
end subroutine gdf100
