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

	character	infile*19, outfile*12, dum*20
	integer*4	star(200,200), avgstar(200,200), imagecnt(200,200)
	integer*4       i, j, starloop, dateloop, orbitloop, date,  orbitnum, minr, maxr
	real*4		radius, 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
	
	do i=1,200
	 do j=1,200
	   star(i,j)=0
	 enddo
	enddo

	if(starloop.eq.1)then
	  write (infile,'(A8,I4.4,A1,I2.2,A4)') 'Aldebar_',date,'_',orbitnum,'.grd'
	elseif(starloop.eq.2)then
	  write (infile,'(A8,I4.4,A1,I2.2,A4)') 'Betel___',date,'_',orbitnum,'.grd'
	elseif(starloop.eq.3)then
	  write (infile,'(A8,I4.4,A1,I2.2,A4)') 'Sirius__',date,'_',orbitnum,'.grd'
	elseif(starloop.eq.4)then
	  write (infile,'(A8,I4.4,A1,I2.2,A4)') 'Vega____',date,'_',orbitnum,'.grd'
	elseif(starloop.eq.5)then
	  write (infile,'(A8,I4.4,A1,I2.2,A4)') 'Alcaid__',date,'_',orbitnum,'.grd'
	elseif(starloop.eq.6)then
	  write (infile,'(A8,I4.4,A1,I2.2,A4)') 'EtaDrac_',date,'_',orbitnum,'.grd'
	elseif(starloop.eq.7)then
	  write (infile,'(A8,I4.4,A1,I2.2,A4)') 'Almach__',date,'_',orbitnum,'.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-100)*(j-100)) )
	   if(radius.lt.55)then
	     if(avgstar(i,j).gt.maxr) maxr=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)
	   if(avgstar(i,j).gt.0.and.minr.gt.avgstar(i,j)) minr=avgstar(i,j)
	 enddo
	enddo
	
	do i=1,200
	 do j=1,200
	   avgstar(i,j)=avgstar(i,j)-minr
	 enddo
	enddo

	write (outfile,'(A12)') 'avg_star.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
