*------------- Telecommunications & Signal Processing Lab --------------
*                          McGill University
*
*
* Module:
*     SUBROUTINE ENGSCL (FIRSTV, DELTAV, NVAL, NSIG, IEXP)
*
*
* Purpose:
*     Find a scale factor for a range of data
*
*
* Description:
*     The NVAL values are given as FIRSTV, FIRSTV+DELTAV, ... ,
*     FIRSTV+(NVAL-1)*DELTAV.  This subroutine determines the smallest
*     and largest magnitude, non-zero values (Pmin and Pmax).  From
*     these values a scale factor of the form 10**IEXP, where IEXP is
*     a multiple of 3, is determined as follows.
*     1) If all values can be represented by NSIG significant digits
*        without scaling, IEXP is set to zero.  That is IEXP is zero if
*        Pmin is greater than or equal to 0.1 and Pmax is less than
*        10***NSIG.
*     2) Otherwise, the scale factor is chosen such that
*        Pmax=Pm*10**IEXP where IEXP is a multiple of 3 and Pm lies
*        between 1 and 1000.
*
*
* Parameters:
* R ->  FIRSTV - First value
* R ->  DELTAV - Increment in values
* I ->  NVAL   - Number of values
* I ->  NSIG   - Number of significant digits to be used in
*                representing the values.  NSIG must be at least 3.
* I <-  IEXP   - Exponent for the scale factor.  IEXP is a multiple of
*                3.  The scale factor is 10**IEXP.
*
* Author / revision:
*     P. Kabal
*     $Revision: 1.4 $  $Date: 1995/03/08 15:27:53 $
*
*
*-----------------------------------------------------------------------

      SUBROUTINE ENGSCL (FIRSTV, DELTAV, NVAL, NSIG, IEXP)


      REAL EPS
      PARAMETER (EPS=1E-5)

      INTEGER NVAL,NSIG,IEXP
      INTEGER IV

      REAL FIRSTV,DELTAV
      REAL ALASTV,SF,SL,SD,PMAX,PMIN,R


      ALASTV=FIRSTV+(NVAL-1)*DELTAV
      SF=ABS(FIRSTV)
      SL=ABS(ALASTV)
      SD=ABS(DELTAV)

* Find the maximum
      PMAX=MAX(SF,SL)

      IF (FIRSTV*ALASTV.GE.0.0) THEN

* End points have the same sign, minimum occurs at the ends
        PMIN=MIN(SF,SL)

      ELSE

* Minimum occurs at an intermediate point
        PMIN=ABS(SD*ANINT(SF/SD)-SF)

      END IF

* Check for a zero or near zero minimum
      IF (PMIN.LT.EPS*SD) PMIN=SD

* Find the exponent of the scale factor
      IEXP=0
      R=10.**NSIG

* (R-0.5) is the largest number that can be represented with NSIG
* digits
* (0.1-0.5/R) is the smallest number that can be represented with NSIG
* digits
      IF (PMAX.GE.(R-0.5) .OR. PMIN.LT.(0.1-0.5/R)) THEN

* The factor R/(R-0.5) ensures that numbers between R-0.5 and R take on
* the next higher value of IEXP
        IV=ALOG10(PMAX*R/(R-0.5)) + 900.0
        IEXP=(IV/3)*3 - 900

      END IF


      RETURN

      END
