C+
C NAME:
C	avgstar_creator_brx
C MODIFICATION HISTORY:
C	July, 2003 A. Smith (UCSD/CASS)
C-
	program avgstar_creator_brx
	implicit none

	character	infile*50, outfile*16, dum*20
	integer*4	star(200,200), avgstar(200,200), imagecnt(200,200)
	integer*4       i, j, starloop, dateloop, orbitloop, date,  orbitnum, maxr, minr, radius
	real*4		temp

	print*, 'Fortran in...'

	do i=1,200
	 do j=1,200
	   avgstar(i,j)=0
	   imagecnt(i,j)=0
	 enddo
	enddo
	
	do dateloop=1,1
	 if(dateloop.eq.1)  date=0227
	 if(dateloop.eq.2)  date=0228
	 if(dateloop.eq.3)  date=0301
	do orbitloop=1,4
	 orbitnum=orbitloop
	do starloop=1,7
	
	print*, dateloop, orbitloop, starloop
	
	do i=1,200
	 do j=1,200
	   star(i,j)=0
	 enddo
	enddo

	if(starloop.eq.1)then
	  write (infile,'(A35,I4.4,A1,I2.2,A8)') 'Star_Transits/brx_transits/Aldebar_',date,'_',orbitnum,'_brx.grd'
	elseif(starloop.eq.2)then
	  write (infile,'(A35,I4.4,A1,I2.2,A8)') 'Star_Transits/brx_transits/Betel___',date,'_',orbitnum,'_brx.grd'
	elseif(starloop.eq.3)then
	  write (infile,'(A35,I4.4,A1,I2.2,A8)') 'Star_Transits/brx_transits/Sirius__',date,'_',orbitnum,'_brx.grd'
	elseif(starloop.eq.4)then
	  write (infile,'(A35,I4.4,A1,I2.2,A8)') 'Star_Transits/brx_transits/Vega____',date,'_',orbitnum,'_brx.grd'
	elseif(starloop.eq.5)then
	  write (infile,'(A35,I4.4,A1,I2.2,A8)') 'Star_Transits/brx_transits/Alcaid__',date,'_',orbitnum,'_brx.grd'
	elseif(starloop.eq.6)then
	  write (infile,'(A35,I4.4,A1,I2.2,A8)') 'Star_Transits/brx_transits/EtaDrac_',date,'_',orbitnum,'_brx.grd'
	elseif(starloop.eq.7)then
	  write (infile,'(A35,I4.4,A1,I2.2,A8)') 'Star_Transits/brx_transits/Almach__',date,'_',orbitnum,'_brx.grd'
	endif


	!! read in headers, then image array
	open(12,file=infile,form='formatted',readonly)
	read(12,120)dum
	read(12,120)dum
	read(12,120)dum
	read(12,120)dum
	read(12,120)dum
120	format(a20)
	read(12,12)((star(i,j),i=1,200),j=1,200)
12	format(20i6)
	close(12)

	do i=1,200
	 do j=1,200
	   if(star(i,j).gt.0)then
	     avgstar(i,j)=avgstar(i,j)+star(i,j)
	     imagecnt(i,j)=imagecnt(i,j)+1
	   endif
	 enddo
	enddo
	
	enddo !!end starloop
	enddo !!end orbitloop
	enddo !!end dateloop
	
	minr=65000
	maxr=0
	do i=1,200
	 do j=1,200
	   if(imagecnt(i,j).gt.0)  avgstar(i,j)=nint( float(avgstar(i,j))/float(imagecnt(i,j)) )
	   radius = sqrt( float((i-100)*(i-100) + (j-105)*(j-105)) )
	   if(radius.lt.35)then
	     if(avgstar(i,j).gt.maxr) maxr=avgstar(i,j)
	     if(avgstar(i,j).gt.0.and.minr.gt.avgstar(i,j)) minr=avgstar(i,j)
	   endif
	 enddo
	enddo

	do i=1,200
	 do j=1,200
	   temp=float(avgstar(i,j))
	   if(temp.lt.0.0) temp=0.0
	   temp=temp*65000.D0/float(maxr)
	   avgstar(i,j)=nint(temp)
	 enddo
	enddo

	write (outfile,'(A16)') 'avg_star_brx.grd'
	!!Write rotated image to file
	open (10,file = outfile, form = 'formatted')
	write(10,10)
10	format('DSAA'/'200 200'/'0 200'/'0 200'/'0 65000')
	do j=1,200
	  write(10,'(20i6)')(avgstar(i,j),i=1,200)
	enddo
	close(10)

	print*, 'Fortran out!!!'

	end
