#!/bin/bash

export LANG=C

# This function should print the TESS spacecraft pointings:
# Output columns are needed to be: orbit_id ra dec roll gps_first gps_last
function tess_pointings()
{
 #    orbit_id  RA	   DEC	       ROLL		GPS_BEG    GPS_END

# Year 1:
 echo   S1      352.6844 -64.8531 -137.8468	2458324.707     2458353.492
 echo   S2       16.5571 -54.0160 -139.5665	2458353.492     2458382.030
 echo   S3       36.3138 -44.2590 -146.9616	2458382.030     2458410.074
 echo   S4       55.0070 -36.6420 -157.1698	2458410.074     2458437.529
 echo   S5       73.5382 -31.9349 -168.9483	2458437.529     2458464.402
 echo   S6       92.0096 -30.5839  178.6367	2458464.402     2458490.818
 echo   S7      110.2560 -32.6344 -193.5524	2458490.818     2458516.909
 echo   S8      128.1156 -37.7370 -204.6909	2458516.909     2458542.839
 echo   S9      145.9071 -45.3044 -214.0837	2458542.839     2458569.078
 echo   S10     165.0475 -54.8165 -220.8276	2458569.078     2458596.314
 echo   S11     189.1247 -65.5369 -221.9239	2458596.314     2458624.730
 echo   S12     229.5885 -75.1255 -206.0227	2458624.730     2458653.714
 echo   S13     298.6671 -76.3281 -161.0622	2458653.714     2458682.531

# Year 2:
 echo	S14	276.7169 62.4756 -327.7671	2458682.531 	2458710.668
 echo 	S15	280.3985 64.0671 -304.5723	2458710.668	2458737.846	
 echo	S16	282.4427 66.1422 -280.5302	2458737.846	2458764.128
 echo	S17	351.2381 57.8456 -318.0314	2458764.128	2458789.827
 echo	S18	 16.1103 67.9575 -319.4547	2458789.827	2458815.461
 echo	S19	 60.2026 76.2343 -340.3537	2458815.461	2458841.826
 echo	S20	129.3867 75.2520 -25.4311	2458841.826	2458869.603
 echo	S21	171.7951 65.1924 -42.0505	2458869.603	2458898.484
 echo 	S22	197.101  53.743  -40.301	2458898.484	2458927.332
 echo	S23	217.288  43.807  -32.575	2458927.332	2458955.503
 echo	S24	261.45   63.12   317.26		2458955.503	2458982.864
 echo	S25	265.61   61.94   339.53		2458982.864	2459009.439
 echo	S26	270.14   61.56     0.60		2459009.439	2459035.451

# Year 3: 
 echo	S27	326.87 -72.43 -145.48		2459035.449	2459061.369
 echo	S28	357.30 -63.00 -137.47		2459061.369	2459087.804
 echo	S29	 18.93 -52.83 -140.20		2459087.804	2459115.261
 echo	S30	 38.36 -43.32 -147.95		2459115.261	2459143.729
 echo	S31	 57.64 -35.78 -158.76		2459143.729	2459172.542
 echo	S32	 77.19 -31.39 -171.37		2459172.542	2459200.925
 echo	S33	 96.60 -30.78  175.54		2459200.925	2459228.396
 echo	S34	115.30 -33.78  163.19		2459228.396	2459254.903
 echo	S35	133.20 -39.69  152.40		2459254.903	2459280.775
 echo	S36	150.95 -47.75  143.73		2459280.775	2459306.600
 echo	S37	170.25 -57.37  138.17		2459306.600	2459333.194
 echo	S38	195.71 -67.83  139.35		2459333.194	2459361.171
 echo	S39	242.20 -76.40  161.60		2459361.171	2459390.206

# Year 4:
 echo	S40	273.08  61.74   14.15   	2459390.206	2459419.162
 echo	S41	277.62  62.76   37.22   	2459419.162	2459447.101
 echo	S42	 13.01   6.33  292.80   	2459447.101	2459473.815
 echo	S43	 49.53  18.97  284.96   	2459473.815	2459499.652
 echo	S44	 89.61  24.13  270.16   	2459499.652	2459525.255
 echo	S45	130.30  19.02  255.09   	2459525.255	2459551.466
 echo	S46	157.70  10.09  248.41    	2459551.466	2459578.973
 echo	S47	143.38  73.11  327.10   	2459578.973	2459607.730
 echo	S48	179.43  62.10  317.42   	2459607.730	2459636.500
 echo	S49	202.64  50.95  321.35   	2459636.500	2459664.500
 echo	S50	221.86  41.76  329.73   	2459664.500	2459691.500
 echo	S51	239.43  35.23  339.87   	2459691.500	2459717.500
 echo	S52	266.36  61.82  343.14   	2459717.500	2459743.500
 echo	S53	270.81  61.58    3.68   	2459743.500	2459769.500
 echo	S54	290.12  32.61   13.46   	2459769.500	2459796.500

# Year 5:
 echo	S55	307.87  37.65  24.54	   	2459796.500	2459823.500
 echo	S56	324.28  46.34  36.25		2459823.500	2459852.500
 echo	S57	344.23  56.41  44.01		2459852.500	2459881.500
 echo	S58  	  9.31  67.65  45.36		2459881.500	2459909.500
 echo	S59	 52.98  77.17  26.51		2459909.500	2459936.500
 echo	S60	125.67  77.31 337.32		2459936.500	2459962.500
 echo	S61	118.04 -36.09 162.22		2459962.500	2459987.500
 echo	S62	135.24 -42.24 151.59		2459987.500	2460013.500
 echo	S63	153.06 -50.70 142.74		2460013.500	2460040.500
 echo	S64	173.27 -60.86 137.28		2460040.500	2460068.500
 echo	S65	201.62 -71.57 140.74		2460068.500	2460097.500
 echo	S66	259.17 -78.80 173.91		2460097.500	2460126.500
 echo	S67	326.77 -74.28 217.47		2460126.500	2460154.500
 echo	S68	359.28 -64.24 226.10		2460154.500	2460181.500
 echo	S69	 20.04 -54.23 222.77		2460181.500 	2460207.500

# Year 6:
 echo	S70	 24.04   9.26 291.30		2460207.500	2460233.500
 echo	S71	 77.34  22.22 275.00		2460233.500	2460259.500
 echo	S72	133.76  16.65 254.03		2460259.500	2460285.500
 echo	S73	 80.67  78.83   8.03		2460285.500	2460312.500
 echo	S74	261.22  72.30 213.92		2460312.500	2460339.500
 echo	S75	254.93  69.94 247.49		2460339.500	2460366.500
 echo	S76	253.53  66.84 276.64		2460366.500	2460395.500
 echo	S77	255.86  63.86 302.34		2460395.500	2460423.500
 echo	S78	260.42  61.57 325.71		2460423.500	2460451.500
 echo	S79	266.06  60.30 347.51		2460451.500	2460479.500
 echo	S80	275.70  32.23   5.49		2460479.500	2460506.500
 echo	S81	292.57  34.69  17.13		2460506.500	2460532.500
 echo	S82	309.13  39.78  27.80		2460532.500	2460558.500
 echo	S83	325.89  47.12  37.05		2460558.500	2460584.500
}

###############################################################################

# Usage: rdr_projection <RA>,<DEC>,<ROLL> <K1>,<K2>,... <COL_RA>,<COL_DEC>
# Equivalent to:
# grtrans --col-radec <COL_RA>,<COL_DEC> --projection ra=<RA>,dec=<DEC>,roll=<ROLL>,tan,k1=<K1>,k2=<K2>,...,degrees
function rdr_projection()
{
 local	RDR="$1"
 local	A=(${RDR//,/ })
 local	KLIST="$2"
 local	B=(${KLIST//,/ })
 local	CLIST="$3"
 local	C=(${CLIST//,/ })

 awk	-v ra=${A[0]} -v dec=${A[1]} -v roll=${A[2]} \
	-v k1=${B[0]} -v k2=${B[1]} -v k3=${B[2]} -v k4=${B[3]} \
	-v cr=${C[0]} -v cd=${C[1]} \
  'BEGIN \
   {	pi=4*atan2(1,1);

	sa0=sin(ra*pi/180.0);
	ca0=cos(ra*pi/180.0);
	sd0=sin(dec*pi/180.0);
	cd0=cos(dec*pi/180.0);
	sr0=sin(roll*pi/180.0);
	cr0=cos(roll*pi/180.0);

	m00=+cr0*sa0+sr0*sd0*ca0;m01=-cr0*ca0+sr0*sd0*sa0;m02=-sr0*cd0;
	m10=+sr0*sa0-cr0*sd0*ca0;m11=-sr0*ca0-cr0*sd0*sa0;m12=+cr0*cd0;
	m20=-cd0*ca0;            m21=-cd0*sa0;            m22=-sd0;
  } \
 {	ra=$(cr)*pi/180.0;
	dec=$(cd)*pi/180.0;
	x0=cos(dec)*cos(ra);
	y0=cos(dec)*sin(ra);
	z0=sin(dec);
	x=-(m00*x0+m01*y0+m02*z0);
	y=+(m10*x0+m11*y0+m12*z0);
	m=1.0/sqrt(1-(x*x+y*y));
	x=x*m;
	y=y*m;
	rc=r2=x*x+y*y;
	w=0.0;
	w += k1*rc;
	rc = rc*r2;
	w += k2*rc;
	rc = rc*r2;
	w += k3*rc;
	rc = rc*r2;
	w += k4*rc;
	x=x*(1+w);
	y=y*(1+w);
	scale=180/pi;
	$(cr)=sprintf("%.8f",x*scale);
	$(cd)=sprintf("%.8f",y*scale);
	print;
  }'
}

# Usage: echo <RA1> <DEC1> <RA2> <DEC2> | celestial_distance
function celestial_distance()
{
 awk \
  'BEGIN \
  {	pi=4*atan2(1,1);
  } \
  {	ra1=$1*pi/180.0;
	dec1=$2*pi/180.0;
	x0=cos(dec1)*cos(ra1);
	y0=cos(dec1)*sin(ra1);
	z0=sin(dec1);
	ra2=$3*pi/180.0;
	dec2=$4*pi/180.0;
	x1=cos(dec2)*cos(ra2);
	y1=cos(dec2)*sin(ra2);
	z1=sin(dec2);
	icos=x0*x1+y0*y1+z0*z1;
	ix=y0*z1-z0*y1;
	iy=z0*x1-x0*z1;
	iz=x0*y1-y0*x1;
	isin=sqrt(ix*ix+iy*iy+iz*iz);
	dist=atan2(isin,icos)*180.0/pi;
	print dist;
  }'
}

# Usage tess_pointing <RA> <DEC> <ROLL> <camera_number>
# This functions tells the camera boresight pointing as the function
# of the spacecraft pointing. Use 1, 2, 3 or 4 for <camera_number>. 
function tess_pointing()
{
 awk \
 'BEGIN { pi=4*atan2(1,1); } \
  {
	ca=cos($1*pi/180.0);
	sa=sin($1*pi/180.0);
	cd=cos($2*pi/180.0);
	sd=sin($2*pi/180.0);
	cr=cos($3*pi/180.0);
	sr=sin($3*pi/180.0);

	mxx=-ca*sd*cr+sa*sr;
	mxy=+ca*sd*sr+sa*cr;
	mxz=ca*cd;
	myx=-sa*sd*cr-ca*sr;
	myy=+sa*sd*sr-ca*cr;
	myz=sa*cd;
	mzx=+cd*cr;
	mzy=-cd*sr;
	mzz=sd;

	# use offset values as follows: 
	# cam1: 36, cam2: 12, cam3: -12, cam4: -36
	offset=36-24*($4-1);
	co=cos(offset*pi/180.0);
	so=sin(offset*pi/180.0);

	cxx= co;cxy=0;cxz=-so;
	cyx=  0;cyy=1;cyz= 0;
	czx= so;czy=0;czz=co;

	# R = M*C, pre-multiply in the case of spacecraft transformations: 
	rxx=mxx*cxx+mxy*cyx+mxz*czx;
	rxy=mxx*cxy+mxy*cyy+mxz*czy;
	rxz=mxx*cxz+mxy*cyz+mxz*czz;
	ryx=myx*cxx+myy*cyx+myz*czx;
	ryy=myx*cxy+myy*cyy+myz*czy;
	ryz=myx*cxz+myy*cyz+myz*czz;
	rzx=mzx*cxx+mzy*cyx+mzz*czx;
	rzy=mzx*cxy+mzy*cyy+mzz*czy;
	rzz=mzx*cxz+mzy*cyz+mzz*czz;

	d=atan2(rzz,sqrt(rxz*rxz+ryz*ryz))*180/pi;

	if ( sqrt(rxz*rxz+ryz*ryz) < 1e-6 )
	 {	a=0.0;
		if ( 0<d )	f=atan2(rxy,-rxx)*180.0/pi;
		else		f=atan2(-rxy,rxx)*180.0/pi;
	 }
	else
	 {	a=atan2(ryz,rxz)*180/pi; if ( a<0 ) a += 360;
		f=atan2(-rzy,rzx)*180/pi;
	 }

	printf("%10.6f %10.6f %10.6f\n",a,d,f);
 }'
}

# Brown-Conrady distortion parameters for TESS cameras: 
k1=0.2855
k2=-0.5389
k3=8.4151

# Usage: tess_ccd_polynomial_hint <camera_number> <ccd_number>
# This function prints two lines: the coefficients of the x and y 
# polynomial distortions for the given Camera and CCD number. 
# These are based on FFI analysis and blind GAIA-DR2-based astrometry and
# the data therein are needed to be considered proprietary. 
function tess_ccd_polynomial_hint()
{
 case "$1,$2" in
	1,1)	echo      2159.082059     -169.8933682       -0.3064495     0.0726296642    0.01276262359   0.001414010413   -0.00428216496  -0.002676836753   0.000273882844 -0.0003854000516
		echo      2100.229404     0.3316066229     -169.8762227   0.002467426348    0.03195093479    0.03029129154 -2.251597995e-05  -0.001557955118  -0.002834967119  0.0005023124102
		;;
	1,2)	echo     -5.282452941     -169.7792983    -0.3528612063   -0.00296471489   0.009213779346   -0.01520520163   0.002428918845   0.002128126297   0.000689065672   0.002973691597
		echo      2097.842005   -0.06307312116     -169.7477217    -0.1227803765    0.00184817234   0.003767655833   -0.01396276019   0.001743961428   0.002334057254   0.003458266447
		;;
	1,3)	echo       2142.24238      169.8827159     0.3079107754    0.03892720505    0.01654874456  -0.003481401775   0.003408274506   0.002213865316 -8.159840261e-05 -0.0004655450206
		echo      2100.830135    -0.2529519832      169.8301102  0.0007512644268    0.03392728724   0.006896156061  -0.001402147683   0.001459292554   0.005076757033  -0.008135233113
		;;
	1,4)	echo     -22.29465626      169.8491315     0.4944153493   -0.06869202624   0.003345357009    0.02114957026   0.004920005854  -0.002032095757  -0.001498153249   0.003177440491
		echo      2100.140194     0.4502027448      170.0054831    -0.2871006162   -0.02991012327    0.07556384808    0.03514060567  -0.006400203951  -0.008636687834     0.0011169042
		;;
	2,1)	echo      2149.247816     -169.9984135     0.3616480673    0.06446644275    0.01204147745   0.009669287722  -0.005468923666  -0.002843276744   0.000717678851   -0.00276442432
		echo      2094.656747    -0.3327031117     -169.9561021  -0.003457614904    0.01052740397    0.06536653569  0.0003785939546 -0.0007550223053 -0.0002705368163  -0.008770946626
		;;
	2,2)	echo     -16.36235904     -169.8340632     0.3398060059   -0.03103454069   0.004140982537    0.01016649715  0.0004018987693   0.001339863256  0.0006177753258  -0.002045919757
		echo       2096.33536    -0.4488869473     -169.8610868   -0.02174334594   -0.01989300315    0.01659349402  -0.002837820147  0.0003337334422   0.002987582069   0.002265882871
		;;
	2,3)	echo      2152.073007      169.8284719    -0.3686469543    0.02832939354   0.009422721961    0.01588508036  0.0005396222504   0.001033983928 -0.0002486009099    0.00244964046
		echo      2106.346818     0.3163156962      169.8840747   -0.01477636213   0.009551973635     0.0484126409  -0.001687227947  -0.000430181732   0.001676198975   0.002934407827
		;;
	2,4)	echo     -13.21699343       169.992794    -0.6634599558   -0.05107243466    0.03135309067   -0.05999019163   0.004170340928  -0.002183847935   0.001822918728  -0.007102512566
		echo      2107.201156     0.7717524785      170.3165548     -0.132290342   0.004656943731     0.1639177574    0.01931322994 -0.0007352825759   0.001334948864    0.01861995058
		;;
	3,1)	echo      2152.301244      169.9046198     0.1559966163    0.06162501823   -0.01958930497   -0.09916428607    0.00509942458 -0.0002366841007  -0.002730839449   -0.01397188637
		echo      2093.021541    -0.4807226998      169.8333859    0.01346061449 -0.0003128632009    0.01370242193   0.002780313129  -0.002336571812   0.002137954091  -0.003292096827
		;;
	3,2)	echo     -10.04640877      169.9030044     0.5362588493   -0.03489095783   0.008014715871  -0.003839305685  0.0002584181858  -0.002272659976  -0.001066874446  -0.001094299245
		echo      2093.832337    -0.5598821237      169.9059615  -0.004422052222   -0.02047204791    0.02683857867    0.00324582935   0.001087203902  -0.002131990811 -0.0007220550286
		;;
	3,3)	echo      2145.863153     -169.9218725    -0.5762276907     0.0323028658    0.01829524522    0.02146219002  0.0007538147644  -0.002584695712  0.0001412529672  -0.003429764891
		echo      2108.725798     0.4341203583     -169.8672797    0.01727758963    0.02356102714     0.0258846125  9.964019459e-05  -0.001822554484  -0.001596140612 -0.0004217529761
		;;
	3,4)	echo     -17.67624345      -170.050879    -0.3072469464   -0.07763408052     0.0198698391   -0.07494221327  -0.004309389943   0.003145184141  0.0001069635906    0.01126747689
		echo      2106.695225     0.7198882268     -170.1207568    0.06292433166   -0.01445564003     0.1232125305   0.007217107136 -0.0002598963884   0.001088740821   -0.01503791049
		;;
	4,1)	echo      2150.040149      170.0069097    0.02768190301    0.04868098327    0.02228488215   -0.00907784519   0.001562503219   0.002533349598 -0.0001051312582  -0.000607060895
		echo      2092.619073     0.1078820982      169.8986019    0.06885841689    0.01974637174    0.01666179629    0.01107066792  0.0009527469274   0.001981689682  -0.002902436645
		;;
	4,2)	echo     -13.40748087      169.9824954     0.1034663488   -0.04764247259   0.009712344067   -0.01855781477   0.002833031107  -0.001605958306 -0.0009791587982  -0.003559731117
		echo      2094.623179    -0.2054246446      170.0105075    0.02518108216   -0.01255887514    0.05919653343   -0.00371439408 -0.0003488722949  -0.002068252535   0.003187809148
		;;
	4,3)	echo      2149.894039     -170.0231415    -0.1425339116    0.05254507667    0.01388682525    0.02991651186  -0.002676868698   -0.00233363912  0.0002467666325  -0.004603056087
		echo      2111.659208    0.05891931729     -169.8852733    0.02844075901  -0.006422694942    0.01934176791  -0.007400814011   0.003212361249  -0.001257938436  0.0004443102735
		;;
	4,4)	echo     -13.79196863     -169.9798385   -0.04851335442   -0.05880514585    0.01855638865   -0.01593509367  -0.004903423041   0.001842147502  -0.001340517562   0.001983458086
		echo       2111.87212     0.2425085003     -170.0027326    0.06335017201   -0.03522374002    0.03811875167    0.01102786522  0.0005839378673    0.00563245981  0.0007876892395
		;;
	*)	echo	0 0 0
		echo	0 0 0
		;;
 esac
}

###############################################################################

# Usage: echo X Y <coefficients> | apply_polynomial 
function apply_polynomial()
{ 
 awk \
  '{	x=$1;
	y=$2;

	ncoeff=NF-2;
	for ( order=0 ; order<100 ; order++ )
	 {	if ( ncoeff < (order+1)*(order+2)/2 )
			break;
	 }
	order--;

	ret=0.0;
	m=(order)*(order+1)/2;
	n=order;ym=1.0;yf=1;
	while ( n>=0 )
	 {      i=n;p=m;w=$(3+m);k=order;
		while ( i>=1 )
		 {      w=w*x/i;
			p-=k;
			w+=$(3+p);
			i--;k--;
		 };
		ret+=w*ym;
		ym=ym*y/yf;
		yf++;
		n--;m++;
	 };
	printf("%.8f\n",ret);
  }'
}	

function tessvisibility_usage()
{
 echo 	"Usage:	$SELF [--help] [-B|--boundary <sector_number>]"
 echo 	"	$SELF [-t <jd_beg>,<jd_end>] <ra> <dec>"
 echo 	"	$SELF [-t <jd_beg>,<jd_end>] '<simbad_target_name>'"
 echo   "	$SELF [-e|--tolerance <pixels>]"
 echo 	"Notes:"
 echo 	" - <ra> and <dec> can either be decimal or sexagesimal. "
 echo 	" - Use colons for separating sexagesimal (arc)minutes and (arc)seconds."
 echo	" - if <ra> is sexagesimal, it is interpreted as hour:min(:sec)."
}

SELF=`basename $0`

RA=""
DEC=""

BOUNDARY_SECTOR=""
J0=0
J1=0

TOLERANCE=0

while [ -n "$1" ]; do
    case "$1" in
	-h|--help)
		tessvisibility_usage
		exit	0
		;;
	-B|--boundary)
		BOUNDARY_SECTOR="$2"
		shift
		;;
	-t|--interval)
		arg="$2"
		A=(${arg//,/ })
		J0=${A[0]}
		J1=${A[1]}
		shift
		;;
	-e|--tolerance)
		TOLERANCE="$2"
		shift
		;;
	-[a-zA-Z]*|--*)
		echo "$SELF: error: invalid command line argument near '$1'." >> /dev/stderr
		exit	1
		;;
	*)
		if ! test -n "$RA"; then
			RA="$1"
		elif ! test -n "$DEC"; then
			DEC="$1"
		else
			echo "$SELF: error: invalid command line argument near '$1'." >> /dev/stderr
			exit	1
		fi
		;;
    esac; shift
done

A=(`tess_pointings | awk -v s=S${BOUNDARY_SECTOR} '{ if ( $1==s ) print; }'`)
if test -n "${A[*]}"; then

	if ! ( grtrans --version ) 2>/dev/null >/dev/null; then
		echo "$SELF: error: FITSH/grtrans is not available." >> /dev/stderr
		exit	1
	fi

	RA=${A[1]}
	DEC=${A[2]}
	ROLL=${A[3]}
	for cam in 1 2 3 4; do
		CAM=(`echo $RA $DEC $ROLL $cam | tess_pointing`)
		ra=${CAM[0]}
		dec=${CAM[1]}
		roll=${CAM[2]}
		for ccd in 1 2 3 4; do
			C=(`tess_ccd_polynomial_hint $cam $ccd`)
			for ((i=0;i<10;i++)); do A[i]=${C[i]}; B[i]=${C[10+i]}; done
			
			atrans=/tmp/tessvisibility-$$.atrans

			 (	echo	"type = polynomial"
				echo	"order = 3"
				echo	"offset = 0, 0"
				echo	"scale = 1"
				echo	"dxfit = ${A[0]}, ${A[1]}, ${A[2]}, ${A[3]}, ${A[4]}, ${A[5]}, ${A[6]}, ${A[7]}, ${A[8]}, ${A[9]}"
				echo	"dyfit = ${B[0]}, ${B[1]}, ${B[2]}, ${B[3]}, ${B[4]}, ${B[5]}, ${B[6]}, ${B[7]}, ${B[8]}, ${B[9]}"
			 ) > $atrans

		 	 (	for ((x=0;x< 2048;x+=256));do echo $BOUNDARY_SECTOR $cam $ccd $((44+x)) 0; done
				for ((x=0;x< 2048;x+=256));do echo $BOUNDARY_SECTOR $cam $ccd $((44+2048)) $x; done
				for ((x=0;x< 2048;x+=256));do echo $BOUNDARY_SECTOR $cam $ccd $((44+2048-x)) 2048; done
				for ((x=0;x<=2048;x+=256));do echo $BOUNDARY_SECTOR $cam $ccd $((44)) $((2048-x)); done
	        	 ) | \
			grtrans --col-xy 4,5 \
				--input-transformation $atrans --reverse | \
			grtrans --wcs ra=$ra,dec=$dec,roll=$roll,k1=$k1,k2=$k2,k3=$k3,tan,degrees \
				--col-pixel 4,5

			#rm -f $atrans

			echo
	
		done
	done

	exit	0
fi

if ! test -n "$RA"; then
	tessvisibility_usage
	exit	0
fi		

if ! test -n "$DEC"; then
	target=`echo "$RA" | tr " " "+"`
	A=(`wget -q -O - "http://cdsweb.u-strasbg.fr/cgi-bin/nph-sesame/-o2/SNV?$target" | grep -v "^#"`)
	if [ ${#A[*]} -lt 2 ]; then
		echo "$SELF: error: target '$target' not found." >> /dev/stderr
		exit	1
	fi
	RA=${A[0]}
	DEC=${A[1]}
	echo "# Target: '$target': ra=$RA dec=$DEC"
fi

A=(${RA//:/ })
if test 2 -le ${#A[*]}; then
	RA=`echo ${A[0]} ${A[1]} ${A[2]} | awk '{ printf("%.6f",$1*15+$2/4.0+$3/240.0); }'`
fi

A=(${DEC//:/ })
if test 2 -le ${#A[*]}; then
	DEC=`echo ${A[0]} ${A[1]} ${A[2]} | awk '{ sign=1;if ( substr($1,1,1)=="-" ) { sign=-1;$1=-$1; } printf("%.6f",sign*($1+$2/60.0+$3/3600.0)); }'`
fi

echo "# $RA $DEC" >> /dev/stderr

tess_pointings | \
awk -v j0=$J0 -v j1=$J1 \
'{	jf=$5;
	jl=$6;
	jdiff=(jf+jl)/2-(j0+j1)/2;
	jlen=(jl-jf)/2+(j1-j0)/2;
	if ( jdiff<0 )	jdiff=-jdiff;
	if ( j0<=0 || j1<=0 )
		print;
	else if ( jdiff<=jlen )
		print;
}' | \
while read orbit SRA SDEC SROLL jd_first jd_last __dummy; do


	# First, compute camera boresight poitings from spacecraft pointing:
	A=($(	echo "	$SRA $SDEC $SROLL 1
			$SRA $SDEC $SROLL 2
			$SRA $SDEC $SROLL 3
			$SRA $SDEC $SROLL 4 " | \
		tess_pointing ))

	CAM1=(${A[0]} ${A[1]} ${A[2]})
	CAM2=(${A[3]} ${A[4]} ${A[5]})
	CAM3=(${A[6]} ${A[7]} ${A[8]})
	CAM4=(${A[9]} ${A[10]} ${A[11]})

	# Check the celestial distance between boresight pointings and input (RA,DEC):
	# For further processing, it should be less than 20 degrees. 
	# It works everywhere on the sky. It is just a pre-filter before
	# applying the gnomonic projections + Brown-Conrady model + higher 
	# order polynomial distortions. These latter ones do not work 
	# everywhere just in the vicinity of the boresight poitings:
	w=$(	echo "	${CAM1[0]} ${CAM1[1]} $RA $DEC
			${CAM2[0]} ${CAM2[1]} $RA $DEC
			${CAM3[0]} ${CAM3[1]} $RA $DEC
			${CAM4[0]} ${CAM4[1]} $RA $DEC	" | \
		celestial_distance | \
		awk '{ print ($1<=20)?"true":"false"; }' )

	# Let's organize stuff in arrays:
	DARR=(false $w)
	RA_ARR=(- ${CAM1[0]} ${CAM2[0]} ${CAM3[0]} ${CAM4[0]})
	DEC_ARR=(- ${CAM1[1]} ${CAM2[1]} ${CAM3[1]} ${CAM4[1]})
	ROLL_ARR=(- ${CAM1[2]} ${CAM2[2]} ${CAM3[2]} ${CAM4[2]})

	#echo $orbit >> /dev/stderr

	# check all Cameras and CCDs one-by-one: 
	for cam in 1 2 3 4; do 

		# skip if distance was larger than 20 degrees:
  		${DARR[cam]} || continue

		# Perform the gnomonic projection + Brown-Conrady distortion: 
		XY=(`echo $RA $DEC | rdr_projection ${RA_ARR[cam]},${DEC_ARR[cam]},${ROLL_ARR[cam]} $k1,$k2,$k3 1,2`)

		for ccd in 1 2 3 4; do

			# Get polynomial coefficients:
			PX=(`tess_ccd_polynomial_hint $cam $ccd | head -n 1`)
			PY=(`tess_ccd_polynomial_hint $cam $ccd | tail -n 1`)

			# Distort with the polynomial using the hint coeffs:
			x=`echo ${XY[0]} ${XY[1]} ${PX[*]} | apply_polynomial`
			y=`echo ${XY[0]} ${XY[1]} ${PY[*]} | apply_polynomial`

			# Print x and y (col, row) coordinates for the given cam/ccd: 
			echo $cam $ccd $jd_first $jd_last $x $y 

		done
	# This below checks for CCD sections and do some pretty-printing:
	done | \
	awk -v orbit=$orbit -v tolerance=$TOLERANCE \
	 '{ 	cam=$1;
		ccd=$2;
		jd_first=$3;
		jd_last=$4;
		x=$5;
		y=$6;
		j0=jd_first;
		j1=jd_last; #+0.5/24.0;
		if ( 44-tolerance<=x && x<=44+2048+tolerance && -tolerance<=y && y<=2048+tolerance )
		 {	printf("%10s %d %d %.5f %.5f %8.3f %8.3f\n",orbit,cam,ccd,j0,j1,x,y);
		 }
	 }'
	
done


