C @(#)median.for	19.1 (ES0-DMD) 02/25/03 13:30:46
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+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
C.IDENTIFICATION
C  subroutine MEDIAN         version 2         810727
C  A. Kruszewski             ESO - Garching
C.PURPOSE
C  calculates median "AMED" of input array "A"
C.INPUT/OUTPUT
C  input arguments
C  A           real*4 array        data array
C  N           integer*4           number of values in "A"
C  ALC         real*4              low cut applied to data in "A"
C  AHC         real*4              high cut applied to data in "A"
C  output arguments
C  AMED        real*4              median of data in "A"
C-----------------------------------------------------------------------
      SUBROUTINE MEDIAN(A,N,ALC,AHC,AMED)
C
      IMPLICIT  NONE	
      INTEGER   N
      DIMENSION A(N)
      REAL      AHC
      REAL      AMED
C
      INTEGER   HISTO(100)
      INTEGER   L
      INTEGER   K
      REAL      A, ALC
      REAL      HN
      REAL      SUM
      REAL      CORR
      REAL      X0,X1,DX
C
      X0=ALC
      X1=AHC
C
C *** Calculates histogram.
C
      DX=(X1-X0)/100
      DO 10 L=1,100
         HISTO(L)=0
10    CONTINUE 
      DO 11 K=1,N
         L=INT((A(K)-X0)/DX)+1
         HISTO(L)=HISTO(L)+1
11    CONTINUE 
C
C *** Calculates median with help of histogram.
C
      HN=FLOAT(N)/2
      L=0
      SUM=0.0
12    CONTINUE
         L=L+1
         SUM=SUM+HISTO(L)
      IF (SUM.LT.HN) GOTO 12 
      AMED=X0+L*DX
      CORR=((SUM-HN)*DX)/HISTO(L)
      AMED=AMED-CORR
      RETURN
      END 

