Struggling to follow your code. I like to use state machines for this kind of thing; it makes code a lot clearer (well for me anyway).
Anyway, what you're going to have to do is to open the input file and read it line by line, at each line deciding if you're going to use the currently opened BRT file or to create a new one, then derive the BRT filename from the line just read in from the input file.