	PROGRAM LANSCE_NORM
!Program to take LANSCE binned data and normalize by vanadium spectrum
! Both the data and the vanadium spectrum must be binned in exactly the same way.
	REAL*4		START		!Start TOF
	REAL*4		FINISH		!End TOF
	REAL*4		YI(20000),YO(20000),TOF(20000)	!Input data
	INTEGER*4	ITOF(4),IYO(4),IYS(4)		!Output data
	REAL*4		SUMYO		!Sum(yo)
	INTEGER*4	IUIN,IUVAN,IUOUT	!Input and output unit nos.
	CHARACTER*80	INNAME,INVAN,OUTNAME	!Input & output file names
	CHARACTER*1	IX		!Dummy character
	CHARACTER*80	TITLE,DUMMY,TEXT
	CHARACTER*18	DATM		!Date/time expt started

	DATA	IUIN,IUVAN,IUOUT/9,10,11/

!Open files

	TYPE *,' Enter GSAS raw data file name'
	ACCEPT '(A)',INNAME
	OPEN(IUIN,FILE=INNAME,STATUS='OLD',ACCESS='SEQUENTIAL')
	TYPE *,' Enter GSAS vanadium spectrum data file name'
	ACCEPT '(A)',INVAN
	OPEN(IUVAN,FILE=INNAME,STATUS='OLD',ACCESS='SEQUENTIAL')
	TYPE *,' Enter GSAS output data file name'
	ACCEPT '(A)',OUTNAME
	OPEN(IUOUT,FILE=OUTNAME,STATUS='UNKNOWN',ACCESS='SEQUENTIAL',
	1	RECL=80,RECORDTYPE='FIXED',FORM='FORMATTED')

!Read header & write headers
!Read title record

	READ(IUIN,'(A)') TITLE
	READ(IUVAN,'(A)') DUMMY
	WRITE(IUOUT,'(A)') TITLE

!Read instrument parameter file record

	READ(IUIN,'(A)') TEXT
	WRITE(IUOUT,'(A)') TEXT			!MAY NOT WANT THIS
	READ(IUVAN,'(A)') DUMMY

!Read bank header record

	DO WHILE ( .TRUE. )
	  READ(IUIN,'(A)',END=999) TEXT
	  READ(IUVAN,'(A)') DUMMY
	  IF ( TEXT(1:8) .EQ.'TIME_MAP' ) THEN

!Deal with time map

	    WRITE (IUOUT,'(A)') TEXT
	    READ(TEXT,'(16X,I5)') NREC
	    DO I=1,NREC
	      READ(IUIN,'(A)') TEXT
	      READ(IUVAN,'(A)') DUMMY
	      WRITE(IUOUT,'(A)') TEXT
	    END DO
	  ELSE

!Real data

	    IBEG = INDEX(TEXT,'STD')
	    TEXT(IBEG:IBEG+2) = 'ALT'
	    WRITE(IUOUT,'(A)') TEXT
	    READ(TEXT,'(7X,I6,I5)') NCHAN,NREC
	    READ(IUIN,'(10(2X,I6))') (YO(I),I=1,NCHAN)
	    READ(IUVAN,'(10(2X,I6))') (YI(I),I=1,NCHAN)

!Process data

	    SUMYO = 0.0
	    IERR = 0
	    DO I=1,NCHAN
	      SUMYO = SUMYO+YO(I)/YI(I)
	    END DO
	    MREC = (NCHAN-1)/4+1
	    TYPE *,' Number of data = ',NCHAN,
	1	' number of output records = ',MREC
	    SCALE = SUMYO/FLOAT(NCHAN)
	    SCALE = FLOAT(10**(-NINT(LOG10(SCALE))))
	    TYPE *,' Data and esd''s scaled by ',SCALE
	    IBEG = 1
	    DO IREC = 1,NREC
	      DO I=1,4
	        ITOF(I) = 0
	        IYO(I) = 0
	        IYS(I) = 0
	      END DO
	      IFIN = MIN(IBEG+3,NSTEPS)
	      DO IDAT=IBEG,IFIN
	        I = IDAT-IBEG+1
	        YOP = YO(IDAT)/MAX(YI(IDAT),1.0)
	        IYO(I) = 10000.*YOP*SCALE
	        IYS(I) = 10000.*SCALE*SQRT(YOP*(1.0+YOP)/MAX(YI(IDAT),1.0))
!	        ITOF(I) = TOF(IDAT)
	      END DO
	      WRITE(IUOUT,'(4(I8,I7,I5))') (ITOF(I),IYO(I),IYS(I),I=1,4)
	      IBEG = IBEG+4
	    END DO
	  END IF
	END DO

!Finished

999	CLOSE(IUVAN)
	CLOSE(IUIN)
	CLOSE(IUOUT)
	STOP 'All done'
	END
