/*
       rtfindent - indent RTF file

       Useful for revealing nesting structure of RTF documents.
       Also makes them somewhat more readable.

       The output is legal RTF but will not format exactly as the input.
       The extra newlines that are introduced might not make a difference,
       but the extra spaces used to effect indenting levels would.

       28 Jan 91       Paul DuBois     [email protected]

       28 Jan 90 V1.0. Created.
       28 Feb 91 V1.01. Updated for distribution 1.05.
*/

# include       <stdio.h>


int     indLevel = 0;
int     indAmt = 2;
int     c;
int     nChars = 0;
int     escNext = 0;


int main (argc, argv)
int     argc;
char    **argv;
{
       /* not clever; only allows stdin or one named file to be read */

       if (argc > 1)
       {
               if (freopen (argv[1], "r", stdin) == NULL)
               {
                       fprintf (stderr, "Can't open \"%s\"\n", argv[1]);
                       exit (1);
               }
       }

       while ((c = getchar ()) != EOF)
       {
               if (escNext)
               {
                       escNext = 0;
                       Put (c);
                       continue;
               }
               if (c == '\\')  /* this would be wrong for a general reader */
               {
                       escNext = 1;
                       Put (c);
                       continue;
               }
               if (c == '{')
               {
                       Flush ();
                       Put (c);
                       Flush ();
                       ++indLevel;
               }
               else if (c == '}')
               {
                       Flush ();
                       --indLevel;
                       Put (c);
                       Flush ();
               }
               else if (c == '\r')
               {
                       Put ('\n');
                       Flush ();
               }
               else
                       Put (c);
       }
       Flush ();
}


Flush ()
{
       if (nChars > 0)
       {
               Put ('\n');
               nChars = 0;
       }
}


Put (c)
int     c;
{
int     i, j;
       if (nChars == 0)        /* beginning of line, dump out indent */
       {
               for (i = 0; i < indLevel; i++)
               {
                       for (j = 0; j < indAmt; j++)
                       {
                               putchar (' ');
                               ++nChars;
                       }
               }
       }
       putchar (c);
       ++nChars;
}