#! /usr/bin/awk -f
# Copyright (c) 1998-2001 Alessandro Rubini

function eat(pat, start, stop)
{
	N = split($0, arr, "@"pat"{");
	res = arr[1];
	for (i = 2; i <= N; i++) {
		sub("}", stop, arr[i]);
		res = res start arr[i];
	}
	$0 = res;
}

BEGIN {IN=0}

/^%MANPAGE END/ {IN=0; next}
/^%MANPAGE/     {IN=1; USELP=NEEDLP=0; NAME=$2; next}
IN==0           {next}

/^%MSKIP/	{SKIP=1;next}
/^%M/		{SKIP=0}

/^@menu/        {SKIP=1;next}
/^@end menu/    {SKIP=0;next}

SKIP==1         {next}
/^%M$/		{next}
/^@ignore/	{next}
/^@end ign/     {next}

#now perform all the substitutions needed

	        { gsub("^%M ?",""); }

# Use eat for converting tags
#
/@b\{/		{eat("b", "\\fB", "\\fP")}
/@samp\{/	{eat("samp", "`", "'")}
/@code\{/	{eat("code", "`", "'")}
/@file\{/	{eat("file", "`", "'")}
/@var\{/	{eat("var", "\\fI", "\\fP")}

/@xref\{.*\}\./ {
  gsub(/@xref\{.*\}\./,"");
}

/@ref\{.*\}/ {
  gsub("@ref\{","");
  gsub("\}","");
}

/@\*/ {
  gsub(/@\* */,"\n.br\n");
}

/@[a-z]+\{/      {
                gsub("@[a-z]+\\{","");
		gsub("}","");
		}

/^@table/       { TABLE=1; }
/^@itemize/     { TABLE=1; next}

/^@item/        {
	        gsub("^@item *","");
		printf ".TP\n%s\n",$0 > NAME;
		NEEDLP=0; next;
		}

/^@end table/   {TABLE=0}
/^@end itemize/ {TABLE=0}

# discard other texinfo commands

/^@/		{next}

# manage comments and '%'

/^%/		{next}


		{
		gsub("[^\\\\]%.*$","");
		gsub("\\%","%");
		}


# remove leading blanks

/^[ \t]/	{sub("^[ \t]*","")}

# put a .LP at blank lines

/^.nf/          {USELP=0}
/^.fi/          {USELP=1}

/^$/	        {if (USELP) {NEEDLP++; next;} }


/./	        { if (NEEDLP) { printf "\n.LP\n" > NAME; NEEDLP=0; } }

/^.TH/	        {USELP=1}

# Escape single slashes (e.g. in documentation for `-l' command line option)

		{gsub("\\\\ ", "\\\\&");}

                {gsub("~", "~~");}

	        {print > NAME}


