	PROGRAM SSRL
!Program to take SSRL data files and convert them to GSAS raw powder files
	REAL*4		START		!Start 2-theta
	REAL*4		FINISH		!End 2-theta (no point here)
	REAL*4		STEP		!2-theta steps
	REAL*4		YI(4000),YO(4000),TTH(4000)	!Input data
	INTEGER*4	ITTH(4),IYO(4),IYS(4)		!Output data
	REAL*4		SUMYO		!Sum(yo)
	INTEGER*4	IUIN,IUOUT	!Input and output unit nos.
	CHARACTER*80	INNAME,OUTNAME	!Input & output file names
	CHARACTER*1	IX		!Dummy character
	CHARACTER*80	TITLE

	DATA	IUIN,IUOUT/10,11/

!Open files

	TYPE *,' Enter SSRL data file name'
	ACCEPT '(A)',INNAME
	OPEN(IUIN,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

	READ(IUIN,'(A)') TITLE
	READ(IUIN,'(/////,6X,F10.0,8X,F10.0,6X,F6.0,/)') START,FINISH,STEP
	TYPE 1,START,FINISH,STEP
1	FORMAT(' Starting 2-theta = ',F10.2,' ending 2-theta = ',F10.2,
	1	' step = ',F6.4)
!Process data

	SUMYO = 0.0
	NSTEPS = 1
	IERR = 0
	DO WHILE ( IERR.EQ.0 )
	  READ(IUIN,3,IOSTAT=IERR) TTH(NSTEPS),YI(NSTEPS),YO(NSTEPS)
3	  FORMAT(F11.0,F15.0,F12.0)
	  IF ( IERR.EQ.0 .AND. TTH(NSTEPS).GT.0.0 ) THEN
	    TTH(NSTEPS) = TTH(NSTEPS)*3200.
	    SUMYO = SUMYO+YO(NSTEPS)/YI(NSTEPS)
	    NSTEPS = NSTEPS+1
	  ELSE
	    IERR = 1
	    NSTEPS = NSTEPS-1
	  END IF
	END DO
	NREC = (NSTEPS-1)/4+1
	TYPE *,' Number of data = ',NSTEPS,
	1	' number of output records = ',NREC
	WRITE(IUOUT,'(A)') TITLE
	WRITE(IUOUT,8) 'BANK  1 ',NSTEPS,NREC,' CONST ',
	1	START*100.,STEP*100.
8	FORMAT(A,2I8,A,2F10.0,' 0 0 ALT',21X)
	SCALE = SUMYO/FLOAT(NSTEPS)
	SCALE = FLOAT(10**(-NINT(LOG10(SCALE))+1))
	TYPE *,' Data and esd''s scaled by ',SCALE
	IBEG = 1
	DO IREC = 1,NREC
	  DO I=1,4
	    ITTH(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))
	    ITTH(I) = TTH(IDAT)
	  END DO
	  WRITE(IUOUT,'(4(I8,I7,I5))') (ITTH(I),IYO(I),IYS(I),I=1,4)
	  IBEG = IBEG+4
	END DO

!Finished

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