#!/usr/bin/python

import sys
from xml.dom.minidom import parse

def recut(infile,outfile,mpgfilename):
  xml=parse(file(infile))
  xmlde=xml.documentElement

  if (xmlde.nodeType!=xmlde.ELEMENT_NODE or
      xmlde.tagName!="dvbcut"):
    sys.stderr.write("'%s' is not a valid dvbcut file\n"%(infile,))
    sys.exit(1)

  xmlde.setAttribute("mpgfile",mpgfilename)
  xmlde.setAttribute("idxfile",mpgfilename+".idx")

  startpic=None
  count=0

  for c in xmlde.childNodes:
    if (c.nodeType!=c.ELEMENT_NODE or not c.attributes.has_key("picture")):
      continue
    tag,pic=c.tagName, int(c.getAttribute("picture"))

    if (tag=="start"):
      if (startpic==None):
        startpic=pic
    elif (tag=="stop"):
      if (startpic!=None):
        count+=pic-startpic
        startpic=None

    if (startpic==None):
      pic=count
    else:
      pic=pic-startpic+count

    c.setAttribute("picture",str(pic))

  file(outfile,'w').write(xml.toxml()+"\n")

if __name__ == "__main__":
  if (len(sys.argv)!=4):
    sys.stderr.write("Usage: %s <infile> <outfile> <mpgfilename>\n"%(sys.argv[0],))
    sys.exit(1)
  recut(*sys.argv[1:4])
