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

 usage: rule90client.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:  rule90client.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])  # number of cells
if len(sys.argv)>5:
        SLEEP=float(sys.argv[5])

RANGE   = SIZE-1	    # index of last cell
ENDNEIGHBR=RANGE-1	    # index of next-to-last cell


# 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:
                for j in range(SIZE):
                	mess.add(currentCA[j])
               	#print "Sending %s %d %s %s " % (host, port, channel, currentCA[0:SIZE])
		mess.send()

        	for j in range(1,RANGE):
                	nextCA[j]=mod(currentCA[j-1]+currentCA[j+1],2)
       		nextCA[0]=mod(currentCA[RANGE]+currentCA[1],2)
       		nextCA[RANGE]=mod(currentCA[ENDNEIGHBR]+currentCA[0],2)
       		temp=currentCA
       		currentCA=nextCA
       		nextCA=temp

		sleep(SLEEP)

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