#!/usr/bin/python
#socket -l -f gsn.eps 192.168.1.7 10000

debug=False

import time, os.path, sys
interval=1
file=sys.argv[1]
host=sys.argv[2]
port=int(sys.argv[3])

# Wait here until the file exists
if debug: print 'Waiting for file to exist...'
file_exists = False
while not file_exists:
    try:
        old_mtime = os.path.getmtime(file)
        file_exists=True
    except:
        #no op
        file_exists=False
    time.sleep(interval)


if debug: print 'File exists, getting ready to rock n roll.'
# File is about to be fired, loaded like a gun.
loaded = False

while True:
    new_mtime = os.path.getmtime(file)
            
    if not loaded and new_mtime != old_mtime:
        # If changed, get ready to send
        if debug: print 'Loading up file...'
        loaded=True
        old_mtime = new_mtime

    elif loaded and new_mtime != old_mtime:
        if debug: print "File hasn't stabilized?"
        old_mtime = new_mtime
        
    elif loaded and new_mtime == old_mtime:
        # File has stabiliized?
        if debug: print "Firing off file!"
        os.system("~/bin/socket %s %d < %s" % (host, port, file))
        old_mtime=new_mtime
        loaded=False
    time.sleep(interval)
