#!/usr/bin/python
#
"""send successive generations of the cellular automaton described
 by rule 30  to a wireTAP server (see, for example,
 http://mathworld.wolfram.com/ElementaryCellularAutomaton.html)

 usage: rule30client.py wireTAPhost port wireTAPchannel CAsize {sleep}

 author: michael branton

 This script is free software; you can redistribute it and/or
 modify it under the terms of the GNU Lesser General Public
 License as published by the Free Software Foundation; either
 version 2.1 of the License, or (at your option) any later version.

 This library is distributed in the hope that it will be useful,
 but WITHOUT ANY WARRANTY; without even the implied warranty of
 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 Lesser General Public License for more details.

 You should have received a copy of the GNU Lesser General Public
 License along with this script; if not, write to the Free Software
 Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA

 uses danny holth/clinton mcchesney OSC.py module to convert data into OSC format
 and the python wireTAP kit. see http://wiretap.stetson.edu
"""

from wtMessenger import wtMessenger
import sys
import os
from operator import *
from time import sleep

# default sleep time (in seconds)
SLEEP=1

# check arg count
if len(sys.argv) < 5:
	print 'usage:  rule30client.py wireTAPhost port wireTAPchannel CAsize {sleep}'
	sys.exit(1)

# parse args
host	= sys.argv[1]
port	= int(sys.argv[2])
channel = sys.argv[3]
SIZE	= int(sys.argv[4])
if len(sys.argv)>5:
	SLEEP=float(sys.argv[5])

RANGE	= SIZE-1
ENDNEIGHBR=RANGE-1

# create connection to wireTAP server 
mess=wtMessenger()
mess.setServerPort(port)
mess.serverConnect(host,channel)

# initialize Cellular Automaton
currentCA=[]
nextCA=[]
for i in range(SIZE):
	currentCA.append(0)
	nextCA.append(0)
currentCA[SIZE/2]=1

# calculate CA generations and ship them off
while 1:
	try:
		# send off current gen
                for j in range(SIZE):
			mess.add(currentCA[j])
               	#print "Sending %s %d %s %s " % (host, port, channel, currentCA[0:SIZE])
		mess.send()

		# calculate next gen
        	for j in range(SIZE):
			sum=currentCA[mod(j-1,SIZE)]+currentCA[j]+currentCA[mod(j+1,SIZE)]
			if sum==3:
				nextCA[j]=0
			elif sum==2 and currentCA[j-1]==0:
				nextCA[j]=1
			else:
				nextCA[j]=mod(sum,2)
       		temp=currentCA
       		currentCA=nextCA
       		nextCA=temp

		# rest a bit...
		sleep(SLEEP)

        except KeyboardInterrupt:
		mess.serverDisconnect()
		print ' '
                print 'your CA session is now complete'
                print ' '
                sys.exit(0)
