in reply to Mixed-up output

You read the file until endline in the first while loop
You then read the rest of the file into @index and $startline is probably greater than the tail of the file, so you print it.
You then print your template and then print whatever is left in @index which is empty.