# $Id$
# Public domain.  Originally written 2014 by Karl Berry.
# Split chapter 2 of plain text output from makeinfo,
# making each section into a separate README file.

BEGIN {
  lastline = "";   # have to read one line ahead
  outfile = "";    # where we are currently outputting
}

{
  if (/^[*]+$/) { # starting new chapter
    # if we're at the index or an appendix, quit.
    if (lastline == "Index" || lastline ~ /^Appendix /) exit (0);
    
    # move on unless starting a chapter we want (not top, intro, etc.)
    if (lastline !~ /^[2-9]/) next;
    
    # ok, we want this chapter.  if we had a file open already, close it.
    if (outfile) close (outfile);
    
    # turn chapter title into filename and start new.
    outfile = tolower (lastline);	# all lowercase
    chapnum = substr (outfile, 0, 1);   # chapter number
    sub ("^. ", "", outfile);		# remove chapnum and following space
    sub (" .*", "", outfile);		# remove next space and everything
    					# after, leaving just the first word.

    # start numbering the README files at 0.
    chapnum = chapnum - 2;
    outfile = "README." chapnum outfile;	# prefix "README.
    #
    print "(This file was generated by makeinfo and splitinfo.gawk.)">outfile;
    print "(Released under the old-style GNU documentation license;" >outfile;
    print " see sources or other output files for full text.)"       >outfile;
    print "" >outfile;
    print lastline >outfile;
    # $0 will be printed as lastline, next time through.

  # splitting output.
  } else if (outfile) {
    print lastline >outfile;
  }
  
  lastline = $0;
}
