##^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^Lance Simms, Stanford University 2009
#! /usr/bin/env python
##
##This script will open up a fits image and crop it according to the boundaries
##contained in the arguments, xstart, xstop, ystart ,ystop
##
#CALLING SEQUENCE:
#run ~/python/pyraf/CropFitsImage.py '/nfs/slac/g/ki/ki09/lances/Reduced/07Apr26/M13Final/M13_G_SlopeFlatFieldedCenteredDitheredMean.fits' 100 4000 100 4000 

import sys,os,re,string
from pyraf import iraf
import pyfits
import numpy
from numpy import *
from pylab import *
import TableIO

#The filename will be specified as the first argument. These files have
#the form [Object Name]_[Filter Used]_SlopeFlatFielded...fits
FitsFileName = sys.argv[1]
XStart	     = int(sys.argv[2])
XStop	     = int(sys.argv[3])
YStart	     = int(sys.argv[4])
YStop	     = int(sys.argv[5])

#Extract various keys from the full path
BaseName     = os.path.basename(FitsFileName)
DirName      = os.path.dirname(FitsFileName)
BaseParts    = BaseName.split('_')
ObjectName   = BaseParts[0]
ThisFilter   = BaseParts[1]
BaseParts    = BaseName.split('.')
BaseKey      = BaseParts[0]

#Create a directory for Astrometry output
OutDir = DirName+'/'
if not os.path.exists(OutDir): os.mkdir(OutDir)

#Open up the image and change the keywords for NAXIS1 & NAXIS2
FitsHDU      = pyfits.open(FitsFileName)
Im           = FitsHDU[0].data
FitsHeader   = FitsHDU[0].header

#Crop the image
Im = Im[XStart:XStop, YStart:YStop]
FitsHDU[0].data=Im

#Write it to a new file
OutFile = OutDir+ObjectName+'_'+ThisFilter+'_'+'Cropped.fits'
if os.path.exists(OutFile) : os.remove(OutFile)
FitsHDU.writeto(OutFile)


