C+
C NAME:
C	A_mainf_centroid
C PURPOSE:
C	average over transits of a star to get an average of that star
C CATEGORY:
C	SMEI Data processing
C INPUTS:
C
C OUTPUTS:
C
C CALLS:
C       none
C PROCEDURE:
C
C MODIFICATION HISTORY:
C	April, 2003 A. Smith (UCSD/CASS)
C-
	program A_mainf_centroid
	implicit none

	! Dimensions for node, nodeid, hits above must be at least 2*(4**(level+1))
	! For LEVEL = 12, KMAX = 134217728
	! For LEVEL =  8, KMAX =    524288

	integer*2	  TOP_LEVEL
	parameter	( TOP_LEVEL = 12 )

	integer*8	  TOP_KMAX
	parameter	( TOP_KMAX = 2*(4**(TOP_LEVEL+1)) )

	real*4		node  ( TOP_KMAX )	!/TOP_KMAX*0.0/
	integer*8	nodeid( TOP_KMAX )	!/TOP_KMAX*0  /
	integer*2	hits  ( TOP_KMAX )	!/TOP_KMAX*0  /

	integer*2	level			/TOP_LEVEL/
	integer*8	kmax			/TOP_KMAX/

	real*4		frame      (1272,256)
	real*4		framessff  (1272,256)
	real*4		framelsff  (1272,256)
	real*4		framelsffu (1272,256)
	real*4  	ped			/0./
	real*4		dark			/0./
	real*4		avg        (1272,256)    /0./
	real*4		hroom			/49400./		!'headroom'=new onboard value of 65k ADUs
	real*4		adu2e
	real*8		affine(6)		/6*0.0D0/		! Affine parameters zero for now
	real*8		cra
	real*8		cdec
	real*8		alfa
	real*8		beta
	real*8		gamma
	real*8		euler(3)
	real*8		camlat
	real*8		ra0
	real*8		arg
	real*8		arg1
	real*8		dusk

	integer*4	mode			/1/			!onboard binning mode
	integer*4	ic			/2/			!Camera #
	integer*4	ifm			/0/			!ROI mask (0=no,1=yes)
	integer*4	id			/1272/			!1280 for TMO
	integer*4	jd			/256/			!600 for TMO
	integer*4	icrcnt			/0/
	integer*4	neighbors		/0/
	integer*4	iframe
	integer*4	iframemask (1272,256)	/325632*1/
	integer*4	ihit(1272,256)
	integer*4	ihist(250)
	integer*4	ifmin                   /193/
	integer*4	ifmax                   /469/
	integer*4	i
	integer*4	j
	integer*4	night			/99/			!night=99 for SMEI data
	integer*4	image(200,200)		/40000*0/
	integer*4	image2(200,200)		/40000*0/

	character	outfile*30,outfile2*30,listfile*23,starlist*37,class1*3,class2*9
	character	framename*28,infile*47,name*14,strlist*29,stdlist*29
c
c	AARON'S DECLARATIONS
c
	integer*4 idarkcr, ii, jj, icra, meascnt, fcnt, badangle,spec,lum
	integer*4 orbitnum, date, maxk, skmin, skmax, maxr, minr
	integer*8 k, kk, frametest, framemax, starloop, dateloop, orbitloop
	real*4 mag1, mag2, mag3
	real*8 rq, dr, thetax, thetaxsq, thetay, cx, cy, cz, crsq
	real*8 rccd, x0, y0, r0, tempx, avgthetarot, thetarot
	real*8 response, arg, arg1, phi, rlat, xra(2), ydec(2)
	real*8 x(4), y(4), ra(4), dec(4), avgthetax, thetaxsum
	real*8 f0, f, xf, yf, zf, rfsq, rf, raf, decf, radius
	real*8 qcam(3,4), qc(4), qsc(4), qandy(4), qdum(4), qfinal(4)

	!!quaternion for cameras from SMEIPoint v1.0
	qcam(1,1) = -0.24387742D0
	qcam(1,2) = 0.46807739D0
	qcam(1,3) = 0.84666176D0
	qcam(1,4) = 0.067758569D0
c	qcam(2,1) = -0.27454405D0
c	qcam(2,2) = 0.017651734D0
c	qcam(2,3) = 0.96032546D0
c	qcam(2,4) = 0.045705368D0
	qcam(3,1) = -0.21298450D0
	qcam(3,2) = -0.43870382D0
	qcam(3,3) = 0.86674816D0
	qcam(3,4) = 0.10451884D0
	!! updated test quaternions (e1=-86.10, e2=59.05, e3=-6.75)
	qcam(2,1) = -0.268131D0
	qcam(2,2) = 0.0170381D0
	qcam(2,3) = 0.962053D0
	qcam(2,4) = 0.0476403D0

	!!quaternion to rotate Andy's coordinates to Don's
	qandy(1)=0.5D0
	qandy(2)=0.5D0
	qandy(3)=0.5D0
	qandy(4)=0.5D0
	data ihist /250*0/
	data ihit /81408*0/

	print*, 'Fortran IN ...'
	adu2e=4.5*65536./hroom
c	call set_flatfields(ic,framessff,framelsff,framelsffu)	!note dimensions should be checked before ff is done...
	call set_cr_backgnd(mode,ic,ifm,id,jd,avg)

	do k=1,kmax
	   node(k)=0.0
	   nodeid(k)=0
	   hits(k)=0
	enddo

	do dateloop=1,1
	  date=0227
	  write(listfile,'(A15,I4.4,A4)') 'DATA_SMEI/list_',date,'.txt'
	  if(date.eq.0529) write(listfile,'(A15,I4.4,A4)') 'DATA_SMEI/cam1_',date,'.txt'
	  do orbitloop=1,1
	    orbitnum=orbitloop
	    maxk=850
	    write (starlist,'(A37)') 'Star_Transits/0227_01_starlist_03.txt'
	    write(stdlist,'(A29)') 'Star_Transits/std_list_03.txt'
	    write(strlist,'(A29)') 'Star_Transits/str_list_03.txt'
	    open(14,file=starlist,status='old')
	    open(18,file=stdlist,form='formatted')
	    open(19,file=strlist,form='formatted')
	    do starloop=1,103

	      read(14,14) cra,cdec,skmin,skmax,name,mag1,mag2,mag3,class1,class2
14	      format(F10.6,2x,F10.6,2x,I5.5,2x,I5.5,2x,A14,2x,F5.2,2x,F5.2,2x,F5.2,2x,A3,2x,A9)
	      write (outfile,'(A14,A1,I4.4,A1,I2.2,A8)') name,'_',date,'_',orbitnum,'_str.grd'
	      write (outfile2,'(A14,A1,I4.4,A1,I2.2,A8)') name,'_',date,'_',orbitnum,'_std.grd'

	      open(13,file=listfile,status='old')
	      frametest=14
	      avgthetax=0.D0
	      avgthetarot=0.D0
	      thetarot=0.D0
	      thetaxsum=0.D0
	      fcnt=0
	      do i=1,200
	        do j=1,200
	          image(i,j)=0
		  image2(i,j)=0
	        enddo
	      enddo

	      do k=1,maxk
	        if(k.eq.skmin) print*, starloop, outfile

 	        read(13,13)framename
13	        format(a28)

	        if(k.ge.skmin.and.k.le.skmax)then

	          write(infile,'(A14,I4.4,A1,A28)') 'DATA_SMEI/2003',date,'/',framename

		  call read_framecrx(infile,mode,ic,id,jd,frame,qdum,meascnt)
		  if(meascnt.lt.5000)then
C		    print*, k, infile

		    !! input quaternion is of form ai+bj+ck+d, not d+ai+bj+ck -> swap with new quaternion
		    qsc(1)=qdum(4)
		    qsc(2)=qdum(1)
		    qsc(3)=qdum(2)
		    qsc(4)=qdum(3)

		    !! multiply camera quaternion into spacecraft(frame) quaternion and take the inverse
		    !! of camera quaternion because it goes from sky to ccd
		    qc(1)=qcam(ic,1)
		    qc(2)=-qcam(ic,2)
		    qc(3)=-qcam(ic,3)
		    qc(4)=-qcam(ic,4)

		    call qmultiply(qsc,qc,qdum)
		    call qmultiply(qdum,qandy,qfinal)

		    !!take inverse of final quaternion: going from ccd to sky, not the other way around
C		    qfinal(1)=qfinal(1)
		    qfinal(2)=-qfinal(2)
		    qfinal(3)=-qfinal(3)
		    qfinal(4)=-qfinal(4)

C		    find ra/dec of center of FOV for a frame
c		      !!find ra of center of the first frame; use to calculate ra bounds in final image
c		      !!car/cdec calculated from thetax=thetay=0
c		      cra=0.D0
c		      cdec=90.D0
c	              call rotateq(qfinal,cra,cdec) !!rotate to standard system
C		      print*, k,' RA/DEC: ',cra,cdec

	!! this function not indented because call is so long
	CALL indexframe(mode,ic,id,jd,level,TOP_KMAX,node,nodeid,hits,frame,affine,qfinal,cra,cdec,avgthetarot,thetax,badangle,xra,ydec)
		    if(badangle.eq.0) then
		      fcnt=fcnt+1
		      thetaxsum=thetaxsum+thetax
		    endif
		  endif  !!end if-block discarding cosmic ray saturated frames

	        endif
	      enddo

	    if(fcnt.le.4) goto 98  !!too many frames were saturated with cosmic rays

	    thetarot=avgthetarot/float(fcnt)
	    avgthetax=thetaxsum/float(fcnt)
c	    print*, 'Thetax: ',avgthetax
c	    print*, 'Thetarot: ',thetarot

	    write(19,19) outfile, mag1, mag2, mag3, class1, class2
19	    format(A30,2x,F5.2,2x,F5.2,2x,F5.2,2x,A3,2x,A9)
	    write(18,18) outfile2, avgthetax, mag1, mag2, mag3, class1, class2
18	    format(A30,2x,F10.6,2x,F5.2,2x,F5.2,2x,F5.2,2x,A3,2x,A9)

	    print*, 'Calling average night...'
C	    call averagenight_rotate(node,nodeid,hits,TOP_KMAX,level,cra,cdec,thetarot,avgthetax,image)
	    call averagenight_rotate_2(node,nodeid,hits,TOP_KMAX,level,cra,cdec,thetarot,avgthetax,image,image2)

	    !!Write imagecnt(sky atlas) 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)')(image(i,j),i=1,200)
	    enddo
	    close(10)

	    maxr=0
	    minr=0
	    do i=1,200
	      do j=1,200
	        radius = sqrt( float((i-100)*(i-100))*1.55 + float((j-102)*(j-102)) )
	        if(radius.lt.36.and.image2(i,j).gt.maxr)  maxr=image2(i,j)
	      enddo
	    enddo

	    !!Write imagecnt(sky atlas) to file
	    open (11,file = outfile2, form = 'formatted')
	    write(11,11)
11	    format('DSAA'/'200 200'/'0 200'/'0 200')
	    write(11,111) minr, maxr
111	    format(I1.1,1x,I5.5)
	    do j=1,200
	      write(11,'(20i6)')(image2(i,j),i=1,200)
	    enddo
	    close(11)

98	    close(13)
	    enddo  !!end starloop
	    close(18)
	    close(19)
	  enddo  !!end orbitloop
	enddo  !!end dateloop

99	print*, 'Fortran out!'

	end
