#!/usr/local/bin/python
# play back a movie in the format of record-movie.

import sys, string, time

MovieError = "MovieError"

def read_rec():
    infile = sys.stdin
    type = infile.read(1)
    if type == '':
        return None # eof
    nums = []
    while 1:
        num = infile.read(1)
        if num == '': break
        if num in '0123456789': nums.append(num)
        else: break
    if num != ':':
        raise MovieError, ("invalid record lead %s" %
                           repr(string.join([type] + nums + [num], "")))
    length = int(string.join(nums, ""))
    contents = infile.read(length)
    if len(contents) != length:
        raise MovieError, "Record truncated: %s, %s < %s" % (type,
                                                             len(contents),
                                                             length)
    trailer = infile.read(1)
    if trailer != ',':
        raise MovieError, ("Invalid record termination '%s'" % trailer)
    return type, contents

def playback(argv):
    start = time.time()
    if len(argv) > 1:
        speed = 24
    else:
        speed = 1
    while 1:
        try: rec = read_rec()
        except MovieError, value:
            sys.stderr.write("Error in movie file: %s\n" % value)
            return
        if rec is None:
            sys.stderr.write("Premature EOF in movie\n")
            return
        type, content = rec
        if type == 's':
            sys.stdout.write(content)
            sys.stdout.flush()
        elif type == 't':
            now = time.time() - start
            target = float(content)/speed
            if target > now: time.sleep(target - now)
        elif type == 'e':
            return
        else:  # unknown record type
            pass

if __name__ == "__main__": playback(sys.argv)
