#!/usr/bin/env python
# -*- coding: utf-8 -*-

import os, sys, signal
import time
import glob

#----------------------------------------------------------------------------------
# main
#----------------------------------------------------------------------------------
if __name__ == '__main__':
	
	#---- get main args 
	if(len(sys.argv)<2):
		print "usage: pipe_cat.py {file_in}"
		sys.exit(1)
	myprog=sys.argv[0]
	mode=int(sys.argv[1])
	file_in=sys.argv[2]
	wkfile="wklog"+str(mode)+".txt"
	dfp=open(wkfile,"w+")
	
	if(mode==1):
		#time.sleep(1.0)
		file_o=sys.argv[3]
		print >>dfp ,"file_o=%s" % (file_o)
		dfp.flush()
		fo=open(file_o,"w")
	else:
		#time.sleep(1.0)
		fo=open("wkout.ts","w+")
	
	print >>dfp ,"myprog=%s" % (myprog)
	print >>dfp ,"file_in=%s" % (file_in)
	dfp.flush()
	
	fi=open(file_in,"r")
	loop=True
	print >>dfp ,"file_in="+str(fi)
	print >>dfp ,"file_out="+str(fo)
	print >>dfp ,"begin read/write loop"
	dfp.flush()
	
	try:
		while (loop):
			buf=fi.read(5000)
			if(buf):
				print >>dfp ,"buf is valid: write to out "
				dfp.flush()
				fo.write(buf)
				fo.flush()
			else:
				print >>dfp ,"buff is null: exit loop"
				dfp.flush()
				loop=0
	except IOError:		
		#print "IOError"
		print >>dfp ,"IOError"
		dfp.flush()
		loop=0
	
	print >>dfp ,"stopping.."
	time.sleep(30.0)
	fo.close()
	fi.close()

