+def find_toplevel_snippets (infile, outfile, types):
+ s = infile.read ()
+ res = {}
+ for i in types:
+ res[i] = ly.re.compile (snippet_res[format][i])
+
+ snippets = []
+ index = 0
+ found = dict ([(t, None) for t in types] )
+
+ #
+ # We want to search for multiple regexes,
+ # without searching the string multiple times for one regex.
+ #
+ # Hence, we use earlier results to limit the string portion
+ # where we search. We're hosed if the first type only occurs
+ # at the end of the string, since it will then use quadratic
+ # time.
+ #
+
+ while 1:
+ first = None
+ endex = 1 << 30
+ for type in types:
+ if not found[type] or found[type].start (0) < index:
+ found[type] = None
+ m = res[type].search (s[index:endex])
+ if m:
+ found[type] = Snippet (type, m)
+
+ if found[type] \
+ and (first == None \
+ or found[type].start (0) < found[first].start (0)):
+
+ first = type
+ endex = found[first].start (0)
+
+ if not first:
+ break
+
+ snippets.append (found[first])