code: def refine(args):
      
      p = OptionParser(refine.__doc__)
      opts, args = p.parse_args(args)
  
      if len(args) != 3:
          sys.exit(not p.print_help())
  
      abedfile, bbedfile, refinedbed = args
      fw = open(refinedbed, "w")
      intersected = refined = 0
      for a, b in intersectBed_wao(abedfile, bbedfile):
          if b is None:
              print(a, file=fw)
              continue
  
          intersected += 1
          aspan_before = a.span
          arange = (a.start, a.end)
          brange = (b.start, b.end)
          irange = range_intersect(arange, brange)
          a.start, a.end = irange
          aspan_after = a.span
          if aspan_before > aspan_after:
              refined += 1
          print(a, file=fw)
  
      fw.close()
      print("Total intersected: {0}".format(intersected), file=sys.stderr)
      print("Total refined: {0}".format(refined), file=sys.stderr)
      summary([abedfile])
      summary([refinedbed])
docs: %prog refine bedfile1 bedfile2 refinedbed
  
      Refine bed file using a second bed file. The final bed is keeping all the
      intervals in bedfile1, but refined by bedfile2 whenever they have
      intersection.