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

	character	infile1*19, infile2*12, outfile*17, dum*20
	integer*4	star(200,200), substar(200,200), avgstar(200,200)
	integer*4       i, j,ss, date, orbitnum, maxr, minr
	real*4		radius

	print*, 'Fortran in...'

	!!Read in average star to be subtracted from star transits
	write (infile2,'(A12)') 'avg_star.grd'
	open(11,file=infile2,form='formatted',readonly)
	read(11,119)dum
	read(11,119)dum
	read(11,119)dum
	read(11,119)dum
	read(11,119)dum
119	format(a20)
	read(11,11)((avgstar(i,j),i=1,200),j=1,200)
11	format(20i6)
	close(11)

	do ss=1,7

	do i=1,200
	 do j=1,200
	   star(i,j)=0
	   substar(i,j)=0
	 enddo
	enddo

	date=0227
	orbitnum=1
	if(ss.eq.1)then
	  write (infile1,'(A8,I4.4,A1,I2.2,A4)') 'Aldebar_',date,'_',orbitnum,'.grd'
	  write (outfile,'(A17)') 'Aldebar___sub.grd'
	elseif(ss.eq.2)then
	  write (infile1,'(A8,I4.4,A1,I2.2,A4)') 'Betel___',date,'_',orbitnum,'.grd'
	  write (outfile,'(A17)') 'Betel_____sub.grd'
	elseif(ss.eq.3)then
	  write (infile1,'(A8,I4.4,A1,I2.2,A4)') 'Sirius__',date,'_',orbitnum,'.grd'
	  write (outfile,'(A17)') 'Sirius____sub.grd'
	elseif(ss.eq.4)then
	  write (infile1,'(A8,I4.4,A1,I2.2,A4)') 'Vega____',date,'_',orbitnum,'.grd'
	  write (outfile,'(A17)') 'Vega______sub.grd'
	elseif(ss.eq.5)then
	  write (infile1,'(A8,I4.4,A1,I2.2,A4)') 'Alcaid__',date,'_',orbitnum,'.grd'
	  write (outfile,'(A17)') 'Alcaid____sub.grd'
	elseif(ss.eq.6)then
	  write (infile1,'(A8,I4.4,A1,I2.2,A4)') 'EtaDrac_',date,'_',orbitnum,'.grd'
	  write (outfile,'(A17)') 'EtaDrac___sub.grd'
	elseif(ss.eq.7)then
	  write (infile1,'(A8,I4.4,A1,I2.2,A4)') 'Almach__',date,'_',orbitnum,'.grd'
	  write (outfile,'(A17)') 'Almach____sub.grd'
	endif


	!! read in headers, then image array
	open(12,file=infile1,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
	   radius = sqrt( float((i-100)*(i-100) + (j-100)*(j-100)) )
	   if(radius.lt.55)then
	     if(star(i,j).gt.0.and.star(i,j).lt.minr) minr=star(i,j)
	   endif
	 enddo
	enddo
	
	do i=1,200
	 do j=1,200
	   if(star(i,j).gt.0) substar(i,j)=star(i,j)-minr-avgstar(i,j)
	 enddo
	enddo
	
	!!Write subtracted image to file
	open (10,file = outfile, form = 'formatted')
	write(10,10)
10	format('DSAA'/'200 200'/'0 200'/'0 200'/'-5000 5000')
	do j=1,200
	  write(10,'(20i6)')(substar(i,j),i=1,200)
	enddo
	close(10)
	
	enddo !!end ss do loop to include all the stars

	print*, 'Fortran out!!!'

	end
