C @(#)mean.for	19.1 (ES0-DMD) 02/25/03 13:23:05
C===========================================================================
C Copyright (C) 1995 European Southern Observatory (ESO)
C
C This program is free software; you can redistribute it and/or 
C modify it under the terms of the GNU General Public License as 
C published by the Free Software Foundation; either version 2 of 
C the License, or (at your option) any later version.
C
C This program is distributed in the hope that it will be useful,
C but WITHOUT ANY WARRANTY; without even the implied warranty of
C MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
C GNU General Public License for more details.
C
C You should have received a copy of the GNU General Public 
C License along with this program; if not, write to the Free 
C Software Foundation, Inc., 675 Massachusetss Ave, Cambridge, 
C MA 02139, USA.
C
C Corresponding concerning ESO-MIDAS should be addressed as follows:
C	Internet e-mail: midas@eso.org
C	Postal address: European Southern Observatory
C			Data Management Division 
C			Karl-Schwarzschild-Strasse 2
C			D 85748 Garching bei Muenchen 
C			GERMANY
C===========================================================================
C
C @(#)mean.for	19.1 (ESO-SDAG) 02/25/03 13:23:05
      SUBROUTINE MEAN(XTEMP,YTEMP,IX,XMEAN,YMEAN,NKICK,RESA,SIG) 

      IMPLICIT REAL*8 (A-H,O-Z), INTEGER*4 (I-N)
C
C MEAN COMPUTES MEAN VALUES OF (X,Y) MEASUREMENTS OF THE SAME OBJECT.
C IF THERE ARE MORE THAN 2 MEASUREMENTS, THE R.M.S. VALUES OF X, Y
C AND R (=SQRT(X**2+Y**2)) ARE ALSO RETURNED IN RESA(3).
C IF R.M.S. (R) IS LARGER THAN SIG, THEN THE (X,Y) WITH THE
C LARGEST RESIDUAL IS REMOVED. THIS PROCESS IS CONTINUED UNTIL
C R.M.S. (R) < SIG, OR IF THERE ARE ONLY 2 MEASUREMENTS LEFT.
C
C A REASONABLE VALUE IS SIG = 5.0 MICRONS
C
      DIMENSION XTEMP(20),YTEMP(20),RESA(3)

      NKICK = 0 
   10 RESX = 0
      RESY = 0
      RESD = 0
      XMEAN = 0 
      YMEAN = 0 

      DO 20 I = 1,IX
         XMEAN = XMEAN + XTEMP(I)
   20    YMEAN = YMEAN + YTEMP(I)
      XMEAN = XMEAN/IX
      YMEAN = YMEAN/IX

      IF(IX.LE.2) GO TO  60 

      DO 30 I=1,IX
         RESX = RESX+(XMEAN-XTEMP(I))**2 
         RESY = RESY+(YMEAN-YTEMP(I))**2 
   30    RESD = RESD+((XMEAN-XTEMP(I))**2+(YMEAN-YTEMP(I))**2) 
      RESX = SQRT(RESX/(IX**2-IX))
      RESY = SQRT(RESY/(IX**2-IX))
      RESD = SQRT(RESD/(IX**2-IX))

      IF(RESD.LT.SIG) GO TO  60 

      DIFF = 0

C
C NOW FIND THE WORST (X,Y) AND REMOVE IT
C
      DO 40 I=1,IX
         DIF = SQRT((XMEAN-XTEMP(I))**2+(YMEAN-YTEMP(I))**2) 
         IF(DIF.LT.DIFF) GO TO 40
         IKICK = I 
         DIFF = DIF
   40    CONTINUE

C
C CLOSE THE RANKS
C
      DO 50 I=IKICK,IX
         XTEMP(I) = XTEMP(I+1) 
   50    YTEMP(I) = YTEMP(I+1) 
      IX = IX-1 
      NKICK = NKICK + 1 
      GO TO 10


C The End
   60 RESA(1) = RESX
      RESA(2) = RESY
      RESA(3) = RESD
      RETURN
      END 





