'''
luaParse.py

Parses the joint angles from a lua motion file of the following type:

----------------------------------------
  -- a wake-up motion, used to clear the legs and get the robot ready

  wakeUp = {
    -- "broadbase", slowly
    { numFrames = 120, 
      joints = { 
	head = {0, 0, 0},
	mouth = 0,
	tail = {0, 0},
	legs = {
	  90, 90, 0,
	  90, 90, 0,
	  -20, 90, 120, 
	  -20, 90, 120}
      }
    },
    -- sleeping, slowly
    { numFrames = 64, 
      joints = { 
	head = {0, 0, 0},
	mouth = 0,
	tail = {0, 0},
	legs = {
	  90, 0, 0,
	  90, 0, 0,
	  90, 0, 0, 
	  90, 0, 0}
      }
    },
    -- getting up
    { numFrames = 120,
      joints = { 
	head = {0, 0, 0},
	mouth = 0,
	tail = {0, 0},
	legs = {
	  -30, 0, 120,
	  -30, 0, 120,
	  -30, 6, 104,
	  -30, 6, 104}
      }
    },
    -- idle position
    { numFrames = 40,
      joints = idleBody
    },
  }, -- end wakeUp

----------------------------------------

My first python program :)

'''

import sys, string

if len(sys.argv)==1:
	print 'Usage:'
	sys.exit(0)


# A function to print the results of the parse
def printResults (values):
	out = 'setPose(mseq_mc,'
	for v in values:
		out += str(v) + ','
	out = out[0:-1]
	out += ');'
	print out
	


f = open(sys.argv[1], "r")

idlebody = [0,0,-20,0,0,0,-5,10,115,-5,10,115,-30,6,104,-30,6,104]
values = []

for line in f:
	# Remove comments
	if line.find('--') != -1:
		line = line[0:line.find('--')]
			    
	# Idle body specified
	if line.find('joints') != -1 and line.find('idleBody') != -1:
		values.extend(idlebody)
		printResults(values)
		del values[:]
		continue

	start = -1
	end = -1

	for i in range(len(line)):
		if line[i].isdigit() or line[i]=='-':
			start = i
			break

	for i in range(len(line)):
		if (line[-i].isdigit()):
			end = -i
			break

	# Create the substring with digits at both ends
	sub = line[start:end+1]
	if len(sub) <= 0:
		continue

	# Split by commas
	t = sub.split(',')
	for s in t:
		values.append(int(s))

	# Print of the finished string of values
	if len(values) >= 17:
		printResults(values),
		del values[:]
