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

	character	infile*16, outfile*16, dum*20
	integer*4	image(100,100), avgstarcnt(100,100)
	integer*4       xnew, ynew, i, j,ss, maxr,minr
	real*4		star(10,100,100), avgstar(100,100), mult
	real*8		cra,cdec
	
	print*, 'Fortran in...'

	maxr=0
	minr=60000

	do i=1,100
	 do j=1,100
	  image(i,j)=0
	  avgstar(i,j)=0.0
	  avgstarcnt(i,j)=0
	 enddo
	enddo
	
	do ss=1,4

	if(ss.eq.1)then
CCC	Coordinates and Files for Aldebaran
	cra=68.9802D0
	cdec=16.5093D0
	write (infile,'(A16)') 'Aldebar__rot.grd'
	elseif(ss.eq.22)then
CCC	Coordinates and Files for HD 20902
	cra=51.0807D0
	cdec=49.8611D0
	write (infile,'(A16)') 'HD20902__rot.grd'
	elseif(ss.eq.2)then
CCC	Coordinates and Files for Sirius (HD 48915)
	cra=101.28717D0
	cdec=-16.71611D0
	write (infile,'(A16)') 'Sirius___rot.grd'
	elseif(ss.eq.3)then
CCC	coordinates and files for Vega (alfa lyra)
	cra=279.23475D0
	cdec=38.78361D0
	write (infile,'(A16)') 'Vega_____rot.grd'
	elseif(ss.eq.4)then
CCC	coordinates and files for Alcaid
	cra=206.8852D0
	cdec=49.3133D0
	write (infile,'(A16)') 'Alcaid___rot.grd'
	elseif(ss.eq.5)then
CCC	coordinates and files for Eta Draconis
	cra=245.99786D0
	cdec=61.51421D0
	write (infile,'(A16)') 'EtaDrac_tran1.grd'
	endif

	print*, infile

	!! 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)((image(i,j),i=1,100),j=1,100)
12	format(20i6)
	close(12)

	!! find brightest pixel to draw box around
	do j=1,100
	 do i=1,100
	   star(ss,i,j)=0.0
	   if(image(i,j).gt.maxr)maxr=image(i,j)
	 enddo
	enddo
	
	mult=65000.D0/maxr
	
	do j=1,100
	 do i=1,100
	   star(ss,i,j)=image(i,j)*mult
	   if(star(ss,i,j).gt.0) then
	    avgstar(i,j)=avgstar(i,j)+star(ss,i,j)
	    avgstarcnt(i,j)=avgstarcnt(i,j)+1
	   endif
	 enddo
	enddo

	enddo !!end ss loop
	
	do j=1,100
	 do i=1,100
	   if(avgstarcnt(i,j).gt.0) avgstarcnt(i,j)=nint( avgstar(i,j)/avgstarcnt(i,j) )
	 enddo
	enddo

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

	print*, 'Fortran out!!!'

	end
