def makeCompositePlotOfZoomedInImages(koiAndFilterList):
	fig=pylab.figure(0,figsize=(5,10))
	nkoi = len(koiAndFilterList)
	ncols = 1
	if (nkoi % ncols) == 0:
		nrows = nkoi/ncols
	else:
		nrows = nkoi / ncols +1
	print nrows, len(koiAndFilterList)
	
	for ii,kkff in enumerate(koiAndFilterList):
		koi = kkff[0]
		filt = kkff[1]
		myKoi = koiPlusFilter.koiPlusFilter(koi,filt)
		print ii, koi, filt
		if os.path.isfile(ao.koiFilterDir(koi,filt,instrUsed)+ao.finalKOIimageFile(koi,filt,instrUsed)):
#			pylab.subplot(nrows,ncols,ii+1)
			finderPlots.zoomedInSubPlot(myKoi,nrows,ncols,ii+1)
					
#			os.system("./finderPlots.py "+koi+" Ks "+str(nrows)+" "+str(ncols)+" "+str(ii+1))
			pylab.title(koi)
	# Finish and export
	pylab.subplots_adjust(wspace=0.1,hspace=0.1)
	binaryOutfile = ao.plotDir+"combined.pdf"
	pylab.savefig(binaryOutfile)
	pylab.close()
def makeSingleImagePrettyPlot(koi, outfile, useFilts=["J","Ks"], useInstr="ARIES", showColorBar=True, useScaleMin=0, useScaleMax=100,useColorMap=cm.jet, showArrows=True, useArrowScale=1):
	print "\n gersdaf",useArrowScale,"\nsdlkfjdkfj"
	pylab.figure(0,figsize=(10,5))
	n=0
	for filt in useFilts:
		if os.path.isdir(ao.koiFilterDir(koi,filt,useInstr)):
			n=n+1
	ii=1
	for filt in useFilts:
		if os.path.isdir(ao.koiFilterDir(koi,filt,useInstr)):
	#		print koi, useInstr, filt, ii, useColorMap
			myKoi = koiPlusFilter.koiPlusFilter(koi,filt,useInstr)
			finderPlots.fullSizeSubPlot(myKoi, 1, n, ii, scaleMin=useScaleMin, scaleMax=useScaleMax, showColorBar=showColorBar, useColorMap=useColorMap, showArrows=showArrows,useArrowScale=useArrowScale)
			ii = ii + 1
	if showColorBar:
		pylab.colorbar(shrink=0.85)
	pylab.savefig(outfile)
	pylab.close()	
	def __init__(self,koi,filt,instr="ARIES"):
		self.koi = koi
		self.filt = filt
		self.instr = instr
		self.peakScaleFactor = self.peakScaleFactorForKOI(koi,filt,instr)
		self.rotation = self.rotateImage(koi,filt,instr)
		self.scalingLaw = self.scalingLawForKOI(koi,filt,instr)
		self.betterRefNum = self.betterRefNumForKOIfilt(koi,filt)
		self.zoomedBoxHalfSizeArcsec = self.getZoomedBoxSizeForKOI(koi)
		self.artificialBoostToAvoidZeroBkg=50
		# Directory structure: if data is NOT from ARIES, it still needs to be stored the same way
		self.fitsDir=ao.koiFilterDir(koi,filt,instr)
		self.fitsFile=ao.finalKOIimageFile(koi,filt,instr)
			
		self.cooFile = self.fitsFile+".coo"
		self.shiftListFile=self.fitsDir+ao.shiftListFile(koi,filt)
		## The shiftlist used to be named the same for all objects:
		if os.path.isfile(self.shiftListFile) == False:
			self.shiftListFile = self.fitsDir+"Shiftlist_obj.txt"
		## We can use any extension for the finder plots
		self.outfile = ao.finderPlotName(koi,filt,ext="pdf")
#		print self.koi, self.filt, self.instr
		if self.instr=="ARIES":
			self.setThreeDitherPoints(koi,filt)
			self.doPlotSetup(koi,filt)
		else: #### probably should have something for Lick
			self.doPlotSetupPHARO(koi, filt)
			
		## Want to tweake where the arrows are placed? Nudge things after the setup
		if (koi == "K00013") & (instr == "ARIES"):
			self.extraX = self.extraX +20
			self.extraY = self.extraY - 50
		if (koi == "K00094") & (instr == "ARIES"): 
			self.extraX = self.extraX + 20 ### optimized for big plot
			self.extraY = self.extraY + 780 ### optimized for big plot
		#	self.extraX = self.extraX - 30 ### 12"
		#	self.extraY = self.extraY + 30 ### 12"
		#	self.extraX = self.extraX - 60 ### 24"
		#	self.extraY = self.extraY + 60 ### 24"
		if (koi == "K00097") & (instr == "ARIES"):
			self.extraX = self.extraX -10
			self.extraY = self.extraY - 0
		if (koi == "K00098") & (instr == "ARIES") & (filt == "J"):
			self.extraX = self.extraX -5
			self.extraY = self.extraY +0
		if (koi == "K00098") & (instr == "ARIES") & (filt == "Ks"):
			self.extraX = self.extraX -5
			self.extraY = self.extraY +0
		if (koi == "K00141") & (instr == "ARIES") & (filt == "Ks"):
			self.extraX = self.extraX -5
			self.extraY = self.extraY +0
		if (koi == "K00174") & (instr == "ARIES"):
			self.extraX = self.extraX +2
			self.extraY = self.extraY -10
		if (koi == "K00263") & (instr == "ARIES"):
			self.extraX = self.extraX +60
			self.extraY = self.extraY -10
		if (koi == "K00264") & (instr == "ARIES") & (filt == "J"):
			self.extraX = self.extraX -30
			self.extraY = self.extraY -10
		if (koi == "K00264") & (instr == "ARIES") & (filt == "Ks"):
			self.extraX = self.extraX + 0
			self.extraY = self.extraY - 10
		if (koi == "K00268") & (instr == "ARIES"):
			self.extraX = self.extraX +20
			self.extraY = self.extraY -20
		if (koi == "K00700") & (instr == "ARIES"):
			self.extraX = self.extraX + 0
			self.extraY = self.extraY -150
		if (koi == "K01054") & (instr == "ARIES"):
			self.extraX = self.extraX +150
			self.extraY = self.extraY - 0
		if (koi == "HAT-P-6b") & (instr == "ARIES"):
			self.extraX = self.extraX +0
			self.extraY = self.extraY +20
		if (koi == "HAT-P-9b") & (instr == "ARIES"):
			self.extraX = self.extraX +0
			self.extraY = self.extraY -70
		if (koi == "HAT-P-30b") & (instr == "ARIES"):
			self.extraX = self.extraX +20
			self.extraY = self.extraY -20
		if (koi == "TrES-1b") & (instr == "ARIES"):
			self.extraX = self.extraX +20
			self.extraY = self.extraY -20
		if (koi == "WASP-2b") & (instr == "ARIES"):
			self.extraX = self.extraX -20
			self.extraY = self.extraY -0
		if (koi == "WASP-33b") & (instr == "ARIES"):
			self.extraX = self.extraX +0
			self.extraY = self.extraY - 20
		if (koi == "XO-4b") & (instr == "ARIES"):
			self.extraX = self.extraX +20
			self.extraY = self.extraY -20
		if (koi == "Corot-1b") & (instr == "ARIES"):
			self.extraX = self.extraX +0
			self.extraY = self.extraY -0
import grabBag as gb
import kepler
import catalogs

################### END PREAMBLE ############################

args = sys.argv
obj = args[1]
filt = args[2]
if len(args)>3:
	instrUsed = str(args[3])
else:
	instrUsed = "ARIES"

### Find the directory and file
fitsDir = ao.koiFilterDir(obj,filt,instrUsed)
fitsFile = ao.finalKOIimageFile(obj,filt)

### Read settings file to get plate scale
settingsDict={}
settingsFile = ao.koiDir(obj,instrUsed)+"settings_"+obj+".tsv"
print settingsFile+"\n"
settingsDict=ao.readSettingsFile(settingsFile)
#### Change if some other Speckle instrument besides Steve Howell's first one (i.e., if Gemini)
if instrUsed == "Speckle":
	try:
		plateScale = eval(settingsDict['Plate_scale_Speckle'])
	except:
		print "\n\nWARNING! using hardcoded plate scale in magLimits.py\n\n"
		plateScale = 0.0228156
#### Should we ever have plate scales differ on different filters, this will need to change
def makeOmniPlot(koiList,name,npix,useHardCodedFigSize=False, useHalfBox=2.0,ncols=4, scalebarLabel="", noLabels=False, figWidth=12, useFilts=["J","Ks"], useInstr= ["ARIES","PHARO"], plotExt=".pdf", plotContourList=False, extraScalebar=False):
	if (npix % ncols) == 0:
		nrows = npix/ncols
	else:
		nrows = npix / ncols +1
	if ncols > 3:
		fig=pylab.figure(0,figsize=(figWidth,3.5*nrows))
	elif ncols ==3:
		fig=pylab.figure(0,figsize=(figWidth,4.25*nrows))
	elif useHardCodedFigSize != False:
		fig=pylab.figure(0,figsize=(useHardCodedFigSize[0],useHardCodedFigSize[1]))
		
	else:
		fig=pylab.figure(0,figsize=(4,2.5*nrows))
	ii=0
	for koi in koiList:
		if koi == "blank":
			print "leaving blank square"
			ii = ii + 1
		elif koi == "scalebar":
			ax=pylab.subplot(nrows,ncols,ii+1)
			pylab.plot([0,1],[1,1],color="k",linewidth=2.0)
			pylab.text(0.5,1.05, scalebarLabel, color="k", fontsize=18, horizontalalignment='center')
			pylab.xlim(xmin=0,xmax=1)
			pylab.ylim(ymin=0,ymax=1.15)
			pylab.box(on=False)
			ax.set_xticks([])
			ax.set_yticks([])
#			pylab.title(scalebarLabel)
			ii = ii + 1
		else:
			for filt in useFilts:
				for instr in useInstr:
#					print "Looking for object:", ao.koiFilterDir(koi,filt,instr)
					if os.path.isdir(ao.koiFilterDir(koi,filt,instr)):
						print koi, instr, filt, ii
						myKoi = koiPlusFilter.koiPlusFilter(koi,filt,instr)
						if plotContourList == False:
							useContours = False
						else:
							useContours = plotContourList[ii]
						if ii == 0: ## only plot the (optional) scale bar on the first image
							finderPlots.zoomedInSubPlot(myKoi,nrows,ncols,ii+1,useColorMap=colorScheme,plotContours=useContours,plotLowerScalebar=extraScalebar,scalebarLabel=scalebarLabel)
						else:
							finderPlots.zoomedInSubPlot(myKoi,nrows,ncols,ii+1,useColorMap=colorScheme,plotContours=useContours,plotLowerScalebar=False)
						if noLabels == False:
							if (len(useFilts)==1 & (len(useInstr)==1)):
								pylab.title(koi)
							else:
						#		pylab.title(koi+"\n"+instr+" "+filt)
								pylab.title(koi+" "+" "+filt+" ("+scalebarLabel+")")
						ii = ii + 1
							
	# Finish and export
	pylab.subplots_adjust(wspace=0.1,hspace=0.1)
	binaryOutfile = ao.plotDir+"allBinaries_"+name+plotExt
	if plotExt == ".eps":
		pylab.savefig(binaryOutfile, format='eps')
	else:
		pylab.savefig(binaryOutfile)
	pylab.close()
## Import settings files
settings={}
for obj in useObjects:
	settings[obj]={}
	settings[obj]=ao.readSettingsFile(ao.settingsFile(obj))

################### END PREAMBLE ############################

createIndividualPlots = False

#### Create finder charts for each individual object
if createIndividualPlots:
	for filt in filters:
		for obj in useObjects:
			fitsFile=ao.koiFilterDir(obj,filt,instrUsed) + ao.finalKOIimageFile(obj,filt,instrUsed)
			if os.path.isfile(fitsFile):
				## Could also call finderPlots directly
				os.system("./finderPlots.py "+obj+" "+filt+ " "+instrUsed)
			

######## Settings ##########
#colorScheme = cm.jet    # blues
#colorScheme = cm.hot    # white-red on black
colorScheme = cm.gray    # grayscale


######## Functions ######### 

# Make zoomed-in-only plots for binary KOI
def makeCompositePlotOfZoomedInImages(filt):
def setDictValues(keyword):
	# Accept the old value if it exists (though some will be superceded)
#	if oldSettings[keyword] != 'XX':
#		print "This was set to something:",keyword,oldSettings[keyword]
#	else:
#		print "nothing here:",keyword
	if (oldSettings[keyword] != "XX"):
		useValue = oldSettings[keyword]

	# Otherwise set defaults
	elif keyword == "Instrument":
		useValue = instrUsed
	elif keyword == "Night":
		try:
			useValue = aries.objectsForNight[obj] ## a dict, not a function
		except KeyError:
			print "The observing night for",obj,"was not listed in aries.objectsForNight[obj]"
			useValue = "XX"
	elif keyword == "RefFrame_J":
		useValue = "XX"
	elif keyword == "RefFrame_Ks":
		useValue = "XX"
	elif keyword == "Camera_mode":
		useValue = "XX"
	elif keyword == "Plate_scale_J":
		try:
			useValue = ao.getPlateScaleFromHeader(ao.koiFilterDir(obj,"J")+ao.finalKOIimageFile(obj,"J"),True,instrUsed)
		except:
			useValue = "XX"
	elif keyword == "Plate_scale_Ks":
		try:
			useValue = ao.getPlateScaleFromHeader(ao.koiFilterDir(obj,"Ks")+ao.finalKOIimageFile(obj,"Ks"),True,instrUsed)
		except:
			useValue = "XX"
	elif keyword == "2MASS_J":
		useValue = jMag
	elif keyword == "2MASS_H":
		useValue = hMag
	elif keyword == "2MASS_Ks":
		useValue = kMag
	elif keyword == "FrameList_J":
		useValue = obj+"_J"
	elif keyword == "FrameList_Ks":
		useValue =obj+"_Ks"
	elif keyword == "TargetPixelRange_J":
		useValue = [[500,1000],[100,500]]
	elif keyword == "TargetPixelRange_Ks":
		useValue = [[500,1000],[100,500]]
	else:
		useValue = "NA"
	# Here are the ones that get superceded
	if keyword == "KOI":
		useValue = obj
###	if keyword == "Raw_data_dir":
###		useValue = ao.dataDir+settingsDict["Night"]+"/"
		
	# Notify user if there are missing, required entries
	if useValue == "XX":
		print "Need value for: ",obj,keyword
		
	return useValue

## Now change to the night directory
os.chdir(nightPath)


## Copy all files to objects/OBJECT/FILTER/
g = open("summary_"+useNight+".txt","w")
for nn,ff in enumerate(useObjList):
	elems = ff.split("_")
	prefix = elems[0]
	obj = elems[1]
	filt = elems[2].split(".")[0]  ### gets rid of the trailing .txt
	print "\nCopying files for",obj, filt,"\n"
	objDir = ao.koiDir(obj,instr="ARIES")
	objFilterDir = ao.koiFilterDir(obj,filt,instr="ARIES")
	savedDir = objFilterDir+"saved/"
	print "Making archive directories if they don't already exist"
	if os.path.exists(objDir) == False:
		os.mkdir(objDir)
	if os.path.exists(objFilterDir) == False:
		os.mkdir(objFilterDir)
	if os.path.exists(savedDir) == False:
		os.mkdir(savedDir)
	
	## The shiftlist, object list, and final image are saved in the main folder
	print "Copying shiftfile"
	os.system("cp Shiftlist_"+obj+"_"+filt+".txt "+objFilterDir)
	print "Copying list of frames"
	os.system("cp "+ff+" "+objFilterDir+ff)
	print "Copying final image"
def obsNotesForKOI(koi):
	#print settings[koi]
	if ((koi in koiDict["J"]) & (koi in koiDict["Ks"])):
		filtersUsed = "J and Ks"
		filterList=["J","Ks"]
		seeingText = str(round(longtext[koi,"J","seeing"],2))+"\" in J and "+str(round(longtext[koi,"Ks","seeing"],2))+"\" in Ks."
		fov = 1024.*eval(settings[koi]["Plate_scale_Ks"])
		limitsLinkText = linkForFile(koi,"Ks","lim.tsv") + ", " + linkForFile(koi,"J","lim.tsv")
##		imageLinkText = "PNG images: "+linkForFile(koi,"Ks",".png") + ", " + linkForFile(koi,"J",".png") + "\nFITS images: " + linkForFile(koi,"Ks",".fits") + ", " + linkForFile(koi,"J",".fits")
		imageLinkText = "\nFITS images: " + linkForFile(koi,"Ks",".fits") + ", " + linkForFile(koi,"J",".fits")
		

	elif (koi in koiDict["Ks"]):
		filtersUsed = "Ks"
		filterList=["Ks"]
		fov = 1024.*eval(settings[koi]["Plate_scale_Ks"])
		seeingText = str(round(longtext[koi,"Ks","seeing"],2))+"\" in Ks."
		limitsLinkText = linkForFile(koi,"Ks","lim.tsv") 
##		imageLinkText = "PNG image: "+linkForFile(koi,"Ks",".png") + "\nFITS image: " + linkForFile(koi,"Ks",".fits")
		imageLinkText = "\nFITS image: " + linkForFile(koi,"Ks",".fits")
	else: # only  J
		filtersUsed = "J"
		filterList=["J"]
		fov = 1024.*eval(settings[koi]["Plate_scale_J"])
		seeingText = str(round(longtext[koi,"J","seeing"],2))+"\" in J."
		limitsLinkText = linkForFile(koi,"J","lim.tsv") 
##		imageLinkText = "PNG image: "+linkForFile(koi,"J",".png") + "\nFITS image: " + linkForFile(koi,"J",".fits")
		imageLinkText = "\nFITS image: " + linkForFile(koi,"J",".fits")

	## Does this object have additional nearby stars on the image?
	for filt in filterList:
		apertures, starn, xySkyDict, starDict = ao.readPhotMagFile(ao.koiFilterDir(koi,filt), ao.finalKOIimageFile(koi,filt), magSuffix=".mag")
		closeComps = []
		if (len(xySkyDict)>1):
			print "Found ",len(xySkyDict)," companions"
			### Okay, how close are they?
			for nn in range(2,len(xySkyDict)+1):
				distPx = math.sqrt( (eval(xySkyDict[nn][0])-eval(xySkyDict[1][0]))**2 +  (eval(xySkyDict[nn][1])-eval(xySkyDict[1][1]))**2 )
				deltaMag = eval(starDict[nn,'5.00'][3])-eval(starDict[1,'5.00'][3])
				distArcsec = eval(settings[koi]["Plate_scale_"+filt]) * distPx
				print koi, nn,distArcsec
				if distArcsec <= closeDist:
					closeComps.append([round(distArcsec,2),round(deltaMag,2)])
		else:
			print koi," has no companions"

		### Now figure out the text to output
		if closeComps == []:
			binaryText = "No companions were detected on the field of view."
		else:
			binaryText = str(len(closeComps))+" companion star(s) detected within "+str(closeDist)+"\" of the target: "
			if len(closeComps)>=1:
				for nn,comp in enumerate(closeComps):
					if (nn == len(closeComps)-1):
						post = ". "
					else:
						post = "; "
					#if comp[1] < closeDist:
					binaryText = binaryText + str(comp[1])+ " mag fainter in Ks at "+str(comp[0])+"\""+post
		
			else:
				binaryText = "No companions were detected within "+str(closeDist)+"\"."
	#	print binaryText
	
		## combine
		text = "ARIES AO observations for "+koi+" were taken on "+settings[koi]["Night"]+" in "+settings[koi]["Mode"]+" in "+filtersUsed+" (plate scale = "+settings[koi]["Plate_scale_Ks"]+"\" per pixel, FOV = "+str(round(fov,1))+"\"). The seeing was "+seeingText + " \n\n"+binaryText+"\n\nLimits on additional companions: "+limitsLinkText+"\n"+imageLinkText
		g = open(obsNotesBatchDir+koi+".txt",'w')
		print >>g, text
if os.path.exists(batchDir):
	os.system("rm -f "+batchDir+"/*")
else:
	os.makedirs(batchDir)	
if os.path.exists(obsNotesBatchDir):
	os.system("rm -f "+obsNotesBatchDir+"/*")
else:
	os.makedirs(obsNotesBatchDir)	

### Figure out which koi have J and or K data
koiDict = {}
for filt in filters:
	koiDict[filt]=[]
	for obj in useObjects:
		if os.path.isfile(ao.koiFilterDir(obj,filt) + ao.finalKOIimageFile(obj,filt)):
			koiDict[filt].append(obj)

print "\nThese files have J data:"
print koiDict["J"]
print "\nThese files have Ks data:"
print koiDict["Ks"]

# we will need to rename: Ia means imaging-AO
def getBatchName(koi,filt,suffix):
	return koi+"Ia-ea"+settings[koi]["Night"]+filt+suffix

# Open text file to go with each file in the tar file
g = open(batchDir+tarFileContentsName,'w')

## Now copy
print "Using:",useObjects
filters = ao.filterNames
print "Searching for filters:",filters

################### END PREAMBLE ############################

### Should we overwrite the .mag files if they already exist? Probably not.
overwrite=False


useList={}
for ff in filters:
	useList[ff]=[]
for obj in useObjects:
	for filt in filters:
		imageDir = ao.koiFilterDir(obj,filt,instrUsed)
		image = imageDir + ao.finalKOIimageFile(obj,filt)
		## Make sure the image exists
		if os.path.isfile(image):
			useList[filt].append(obj)
			## Check to see if there are already results from a prior run
			if os.path.isfile(image+".mag"):
				## Delete them if we are redoing things
				if overwrite:
					print "Deleting existing file for",obj
					os.system("rm "+image+".mag")
			## If we're NOT redoing things, we should only proceed if .mag files are missing
			if os.path.isfile(image+".mag"):
				print ".mag file already exists for",obj
			else:
				print "Running",image
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()
	### This should never be set in the settings file!!!
	settings[obj]["Raw_data_dir"] = ao.dataDir + settings[obj]["Night"] + "/"

################### END PREAMBLE ############################

closeDist = 4.1 # arcsec
farDist = 10.0 # arcsec

makeObservingSummary = True

### Figure out which objects have J and or K data
objectDict = {}
for filt in filters:
	objectDict[filt]=[]
	for obj in useObjects:
		if os.path.isfile(ao.koiFilterDir(obj,filt,instrUsed) + ao.finalKOIimageFile(obj,filt,instrUsed)):
			objectDict[filt].append(obj)

print "\nThese files have J data:"
print objectDict["J"]
print "\nThese files have Ks data:"
print objectDict["Ks"]

## Get details from .coo file:
initSigma=5.
fwhmDict={}
for filt in filters:
	for obj in objectDict[filt]:
		fwhmDict[obj,filt] =""
		if (obj in useObjects) & (makeObservingSummary == True):
			fitsFile = ao.koiFilterDir(obj,filt,instrUsed)+ao.finalKOIimageFile(obj,filt,instrUsed)