##^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^Lance Simms, Stanford University 2009
#! /usr/bin/env python

##This script will run through all of the files specified on the command line
##
##Run either as 
##	imstat_example.py [filename]
#	imstat_example.py [@list_of_files]
import sys,os
from pyraf import iraf
import pyfits
from numarray import *
from pylab import *
import MySQLdb

##Tell a little about where this file is running from and indicated the 
##operating system class
print 'sys.argv[0] =', sys.argv[0]
print 'sys.argv[1] =', sys.argv[1]
pathname=os.path.dirname(sys.argv[0])
print 'path =', pathname 
print 'full path =', os.path.abspath(pathname)
print 'Current path', os.getcwd()

#GET THE DATE
Fullpath=os.getcwd()
directory=Fullpath.split('/')
Date=directory[6]
Date_Parts=Date.split('-')
Year=Date_Parts[0]
Month=Date_Parts[1]
Day=Date_Parts[2]

print Date

##Open up the connection and include some error handling
try:
        conn=MySQLdb.connect (host="localhost",
                              user="root",
                              passwd="mysql",
                              db="my_test")
except MySQLdb.Error, e:
        print "Error $d: $s" % (e.args[0],e.args[1])
        sys.exit

##CREATE CURSOR OBJECT
cursor=conn.cursor()

try:
        cursor.execute("CREATE DATABASE IMSTAT")
        print "Database Created"
except MySQLdb.Error, e:
        print e
        
try:
        cursor.execute("use IMSTAT");
        cursor.execute('CREATE TABLE '+Month+'_'+Day+
					       '(Filename varchar(20),'+
                                               'NPIX mediumint,'+
                                               'MEAN float,'+
                                               'STDEV float,'+
                                               'MIN float,'+
                                               'Max float);')
except MySQLdb.Error, e:
        print e


########################################FUNCTION
def run_imstat(input):			#Function Definition
	iraf.images(_doprint=0)		#load the image package
	l=len(input)			#input is a list containing filename
	
	for image in input:
		
		s=iraf.imstat(image,Stdout=1)      #S is huge string containing
		lens=len(s)		           #all output from imstat
		print "Total Number Files:",lens   #lens=length of string
		datamax=zeros(lens,Float32)
		i=3

		for i in range(lens-1): 
			#Now we have array containing five strings
			#[Filename,NPIX,MEAN,STDEV,MIN,MAX]
			Values=s[i+1].split()
		        cursor.execute("INSERT INTO "+Month+'_'+Day+
				      " VALUES('"+
				      Values[0]+"','"+Values[1]+"','" +
				      Values[2]+"','"+Values[3]+"','" +
				      Values[4]+"','"+Values[5]+"')")	
			max_count=float(Values[5])
			datamax[i]=max_count
		
	return datamax

if __name__== "__main__":
	datamax=run_imstat(sys.argv[1:]) 

plot(datamax)
xlabel('File Number')
ylabel('Maximum Pixel Value (Counts)')
title('Values For '+Date)
savefig('Datamax_'+Date+'.ps')
show()	
