#! /usr/bin/python

import sys, os, string, getopt, re


#some default definitions
colours = {	
			'none'		:	"",
			'default'	:	"\033[0m",
			'bold'		:	"\033[1m",
			'underline'	:	"\033[4m",
			'blink'		:	"\033[5m",
			'reverse'	:	"\033[7m",
			'concealed'	:	"\033[8m",

			'black'		:	"\033[30m", 
			'red'		:	"\033[31m",
			'green'		:	"\033[32m",
			'yellow'	:	"\033[33m",
			'blue'		:	"\033[34m",
			'magenta'	:	"\033[35m",
			'cyan'		:	"\033[36m",
			'white'		:	"\033[37m",

			'on_black'		:	"\033[40m", 
			'on_red'		:	"\033[41m",
			'on_green'		:	"\033[42m",
			'on_yellow'		:	"\033[43m",
			'on_blue'		:	"\033[44m",
			'on_magenta'	:	"\033[45m",
			'on_cyan'		:	"\033[46m",
			'on_white'		:	"\033[47m",

			'beep'		:	"\007"
			}

def add2list(clist, m, patterncolour):
	for group in range(0, len(m.groups()) +1):
		if group < len(patterncolour):
			clist.append((m.start(group), m.end(group), patterncolour[group]))
		else:
			clist.append((m.start(group), m.end(group), patterncolour[0]))


conffilepath = [os.environ['HOME']+"/.grc/", "/usr/local/share/grc/", "/usr/share/grc/", ""]
for i in conffilepath:
	if os.path.isfile(i+sys.argv[1]):
		conffile = i+sys.argv[1]
		break
regexplist = []

f = open(conffile, "r")
is_last = 0
while not is_last:
	ll = {'count':"more"}
	while 1:
		l = f.readline()
		if l == "": 
			is_last = 1
			break
		if l[0] == "#" or l[0] == '\012':
			continue
		if not l[0] in string.letters:
			break
		keyword, value = string.split(l[:-1], "=", 1)
		keyword = string.lower(keyword)
		if not keyword in ["regexp", "colours", "count", "command"]:
			raise "Invalid keyword"
		ll[keyword] = value

	# Split string into one string per regex group
	# e.g. split "brown bold, red" into "brown bold" and
	# "red"
	colstrings = []
	for colgroup in string.split(ll['colours'], ','):
		colourlist = string.split(colgroup)
		c = ""
		for i in colourlist :
			c = c + colours[i]
		colstrings.append(c);

	cs = ll['count']
	ll['regexp'] = re.compile(ll['regexp'])
	ll['colours'] = colstrings
	regexplist.append(ll)

f = sys.stdin
while 1:
	l = f.readline()
	if l == "" :
		break
	line = l[:-1]
	clist = []
	for pattern in regexplist:
		pos = 0
		while 1:
			m = pattern['regexp'].search(line, pos)
			if m != None:
				if pattern.has_key('colours'):
					add2list(clist, m, pattern['colours'])
					if pattern['count'] == "stop": break
					if pattern['count'] == "more": pos = m.end(0)
					else: pos = sys.maxint
				if pattern.has_key('command'):
					os.system(pattern['command'])
			else: break
		if m != None and pattern['count'] == "stop":
			break
	cline = (len(line)+1)*[colours['default']]
	for i in clist:
		# each position in the string has its own colour
		cline[i[0]:i[1]] = [colours['default']+i[2]]*(i[1]-i[0])
	nline = ""
	clineprev = ""
	for i in range(len(line)):
		if cline[i] == clineprev: 
			nline = nline + line[i]
		else:
			nline = nline + cline[i] + line[i]
			clineprev = cline[i]
	nline = nline + colours['default']
	print nline
		
