def tableForEachStar(obj, distLimit):
	print "Output all stars within",distLimit,"arcsec to:",ao.starsFile(obj,instr=instrUsed)
	g = open(ao.starsFile(obj,instr=instrUsed),"w")
	print >>g, "\t".join(["object",obj])
	
	for filt in filters:	
		if obj in objectDict[filt]:
			### Output fwhm for filter
			print >>g, "\t".join([ filt, "fwhm", str(round(fwhmDict[obj,filt],2)) ])
			### Does this object have additional nearby stars on the image?
			apertures, starn, xySkyDict, starDict = ao.readPhotMagFile(ao.koiFilterDir(obj,filt,instrUsed), ao.finalKOIimageFile(obj,filt,instrUsed), magSuffix=".mag")
		#	print os.path.isfile(ao.koiFilterDir(obj,filt,instrUsed)+ao.finalKOIimageFile(obj,filt,instrUsed)+".mag")
			
			### Make a koi class for use in undoing rotations
			k = koiPlusFilter.koiPlusFilter(obj,filt,instrUsed)
			refX = eval(xySkyDict[1][0])
			refY = eval(xySkyDict[1][1])
			refXerr = eval(xySkyDict[1][4])
			refYerr = eval(xySkyDict[1][5])
			if k.dir12 == "N":
				northDeltaX = k.arrowDeltaX12
				northDeltaY = k.arrowDeltaY12
				eastDeltaX = k.arrowDeltaX10
				eastDeltaY = k.arrowDeltaY10
			else:
				northDeltaX = k.arrowDeltaX10
				northDeltaY = k.arrowDeltaY10
				eastDeltaX = k.arrowDeltaX12
				eastDeltaY = k.arrowDeltaY12
			
			closeComps = []
			print obj, " has ",len(xySkyDict)-1," comp stars (any distance) in",filt
			### Note stars are 1, not 0, indexed
			for nn in range(1,len(xySkyDict)+1):
				#### Distance ####
			#	distPx = math.sqrt( (eval(xySkyDict[nn][0])-eval(xySkyDict[1][0]))**2 +  (eval(xySkyDict[nn][1])-eval(xySkyDict[1][1]))**2 )
				thisX = eval(xySkyDict[nn][0]) 
				thisY = eval(xySkyDict[nn][1])
				thisXerr = eval(xySkyDict[nn][4])
				thisYerr = eval(xySkyDict[nn][5])
			#	print thisX, thisXerr, thisY, thisYerr, obj, refXerr, refYerr
				deltaX =  thisX - refX
				deltaY =  thisY - refY
				deltaXerr = math.sqrt(thisXerr**2+refXerr**2)
				deltaYerr = math.sqrt(thisYerr**2+refYerr**2)
				## in pixels
				if ((thisX == refX) & (thisY == refY)):
					distPx = math.sqrt( (thisX-refX)**2 + (thisY-refY)**2 )
					distErrPx = 0
				else:
					distPx, distErrPx = gb.distanceWithErrors(deltaX,deltaY,deltaXerr,deltaYerr)
				## in arcsec
				distArcsec = eval(settings[obj]["Plate_scale_"+filt]) * distPx
				distArcsecErr = eval(settings[obj]["Plate_scale_"+filt]) * distErrPx
				## Get position angles in degrees
				useDeltaX, useDeltaY = undoRotations(k.rotation, deltaX, deltaY)
			#	print "\nDiag:",useDeltaX, useDeltaY, "unflipped from",deltaX,deltaY,k.rotation
				if ((thisX == refX) & (thisY == refY)):
					angle = 0
				else:
					angle = getPA(useDeltaX, useDeltaY,northDeltaX,northDeltaY,eastDeltaX,eastDeltaY) 
				#	print "Diag PA:", useDeltaX, useDeltaY, northDeltaX, northDeltaY, eastDeltaX, eastDeltaY, angle
				#### Delta-magnitude ####
				try:
					deltaMag = eval(starDict[nn,'5.00'][3])-eval(starDict[1,'5.00'][3])
				except:
					deltaMag = eval(starDict[nn,'1.00'][3])-eval(starDict[1,'1.00'][3])
					print obj,"WARNING: aperture of 1 instead of 5 px; mag values unreliable. A PSF fit binary?\n"
	
				### Now check if it is within our desired cutoff distance
				if distArcsec <= distLimit:
					closeComps.append([str(round(distArcsec,2)), str(round(deltaMag,2)), xySkyDict[nn][0], xySkyDict[nn][1], str(round(angle,1))])
			#### We want to output the target star even if there are no others (for its pixel location and fwhm)
		##	print obj,closeComps,"\n\n"
			print >>g, "Star","Dist","Delta-mag","X_pixel","Y_pixel","PA"
			for nn,comp in enumerate(closeComps):
				listOut = gb.flattenList([[str(nn)], closeComps[nn]])
				print >>g, gb.listToString(listOut,tab="\t")
		else:
			print "object wasn't found for this filter:",obj,filt
	
	g.close()
def makeTable(useFilter,objectList=[],extra="",doAllTheAps=False,alsoShowKepMags=False):
	if objectList==[]:
		objectList=useList[useFilter]
	magSummaryFile=ao.mainDir+"tables/limitingMagSummary_"+useFilter+extra+".tsv"
	magSummaryFileTex= string.replace(magSummaryFile, ".tsv", ".tex")
	print "\nWriting summary of limits to file:",magSummaryFile
	g = open(magSummaryFile,'w')
	gTex = open(magSummaryFileTex,'w')
	if useFilter == "all":
		ourFilters = filters
	else:	
		ourFilters = [useFilter]
	#### The full set of apertures run makes for a very wide table
	if doAllTheAps:
		specialAps=allApsForObj[objectList[0]] ### implicitly assumes same aps used for all objects; this table gets weird otherwise
		print "\n\n",specialAps,"\n\n"
		print >>g, "\t".join(["Object", "Instr", "Filter", "Target_Mag",  "FWHM"]) + "\t" + "\t".join(specialAps)
		print >>gTex,"\t &".join(["Object", "Instr", "Filter", "Target_Mag", "FWHM"]) + "\t" + "\t &".join(specialAps) + "\\\\"	
	#### A subset of apertures is preferable for published tables
	else:
#		specialAps=["0.1","0.2","0.5","1.0","2.0","4.0"]
#		print >>g, "\t".join(["Object", "Instr-Filter", "Target_Mag", "FWHM","0.1\"","0.2\"","0.5\"","1.0\"","2.0\"","4.0\""])
#		print >>gTex,"\t &".join(["Object", "Instr-Filter", "Target_Mag", "FWHM", "0.1\"","0.2\"","0.5\"","1.0\"","2.0\"","4.0\"","\\\\"])	
		specialAps=["0.1","0.2","0.5","1.0","2.0","4.0","10.0"]
		print >>g, "\t".join(["Object", "Instr-Filter", "Target_Mag", "FWHM","0.1\"","0.2\"","0.5\"","1.0\"","2.0\"","4.0\"","10.0\""])
		print >>gTex,"\t &".join(["Object", "Instr-Filter", "Target_Mag", "FWHM", "0.1\"","0.2\"","0.5\"","1.0\"","2.0\"","4.0\"","10.0\"","\\\\"])	
	for obj in objectList:
		for filt in ourFilters:
			if fwhmDict[obj,filt] == "NA":
				print "No data for:",obj, filt
			else:
				### Print apertures
				### Print 2MASS magnitudes
				if settings[obj]["2MASS_"+filt]=="XX":
					mag2MASS = "NA"
				else:
					mag2MASS =  str(eval(settings[obj]["2MASS_"+filt])[0])
				print >>g, "\t".join( gb.flattenList([[obj, instrUsed+"-"+filt, mag2MASS, str(fwhmDict[obj,filt]) ]])),
				print >>gTex, "\t &".join( gb.flattenList([[obj, instrUsed+"-"+filt, mag2MASS, str(fwhmDict[obj,filt]) ]])),
				### Print limits
				for ap in specialAps:
				#	print "ap",ap,fwhmDict[obj,filt]
					if eval(ap) >= eval(fwhmDict[obj,filt]):
						if byApDict[obj,filt,ap] == "NA":
							printableForm = byApDict[obj,filt,ap]
						else:
							printableForm = round(eval(byApDict[obj,filt,ap]),2)
						print >>g, "\t",printableForm, 
						print >>gTex, "\t&", printableForm,
					else:
						print >>g, "\t -- ",
						print >>gTex, "\t& -- ",
				## be sure to close the line
				print >>g, ""
				print >>gTex, "\\\\"
				#### This prints the Kepler-mag limits directly underneath the J/Ks limits
				if alsoShowKepMags:
					### get the target's Kepler mag
					try:
						kepMag = eval(ksasDict[obj]["kpmag"])
					except:
						kepMag = "--"
					### remember to subtract from the limits (absolute, not relative)
					
					print >>g, "\n",obj+"\t",instrUsed+"-"+filt+"toKp \t  ",kepMag, "\t", str(fwhmDict[obj,filt]),
					print >>gTex, "\n",obj+"& ",instrUsed+"-"+filt+"toKp &  ",kepMag, "\t", str(fwhmDict[obj,filt]),
					for ap in specialAps:
					#	print "ap",ap,fwhmDict[obj,filt]
						if eval(ap) >= eval(fwhmDict[obj,filt]):
							if kepMag == "--":
								print >>g, "\t",byApDict[obj,filt,ap,"KepMag"],
								print >>gTex, "\t&", byApDict[obj,filt,ap,"KepMag"],
							else:
								print >>g, "\t",round(byApDict[obj,filt,ap,"KepMag"] - kepMag, 2), 
								print >>gTex, "\t&", round(byApDict[obj,filt,ap,"KepMag"] - kepMag, 2),
								
						else:
							print >>g, "\t -- ",
							print >>gTex, "\t& -- ",
				## be sure to close the line
				print >>g, ""
				print >>gTex, "\\\\"
	print "\nCreated file:",magSummaryFile
	print "\nCreated file:",magSummaryFileTex
	g.close()