"""
Graphcha
Copyright (c) 2008, Alexandru Toth
All rights reserved.

Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
    * Redistributions of source code must retain the above copyright
      notice, this list of conditions and the following disclaimer.
    * Redistributions in binary form must reproduce the above copyright
      notice, this list of conditions and the following disclaimer in the
      documentation and/or other materials provided with the distribution.

THIS SOFTWARE IS PROVIDED BY Alexandru Toth ''AS IS'' AND ANY
EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL <copyright holder> BE LIABLE FOR ANY
DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE."""

"""
Ver 0.01

The tool generates on standard output a graph in  DOT format. It has to be 
rendered by Graphviz dot.

Basic usage:
python grapcha.py | dot -T png -o alexandru.png

For more useful scenarios, import the module and call it's chain() function 
with the string you want renderred as parameter.
"""

import random

SIZE = 2	#size of cluster
MIN = 16

#graphviz dot file header
def header():
	return 'digraph {\n'

#graphviz dot file footer	
def footer():
	return '\n}\n'
	
#split list into equally sized subgraphs
def clusters(l):
	random.shuffle(l)
	res = []
	for i in xrange(len(l)):
		if i == 0:
			res.append('subgraph cluster_%d {' % i)
		elif i % SIZE == 0:
			res.append('}\nsubgraph cluster_%d {' % i)
		res.append(l[i])
		
	res.append('}')
	return res
			
#generate random string
def garbagePad(text):
	need = MIN - len(text)
	if need < 0:
		return ''
	letters = map(chr, range(ord('a'),ord('z')))
	random.shuffle(letters)
	return ''.join(letters[:need])
	

def chain(text):
	res = [ header() ]
	inner = []
	
	garbage = garbagePad(text)
	lg = len(garbage)
	all = garbage[:lg/2] + text + garbage[lg/2:]
	for i in xrange(len(all)):
		if i == lg / 2 :
			inner.append('N%d [shape = Mdiamond, color=green, label="%s"];' % (i, all[i]))
		elif i == lg/2  + len(text)-1:
			inner.append('N%d [shape = Msquare, color=red, label="%s"];' % (i, all[i]))
		else:
			inner.append('N%d [label="%s"];' % (i, all[i]))
		
	random.shuffle(inner)
	inner = clusters(inner)
	
	res.extend(inner)
	
	res.append (' -> '.join(['N%d' % i for i in xrange(len(all))]) )
	res.append(';')
	res.append(footer())	
	
	return '\n'.join(res)
	
	
if __name__ == '__main__':
	text = 'alexandru.toth'
	print chain(text)
