/* codeprint1a.p
 *
 * 2001 by John Green, Joanju Limited
 *
 * Second part of "codeprint1"
 * This is the part that does the real work
 * 
 * Similar to PREPROCESS output, with these differences:
 * - comments have been stripped
 * - shows where include files begin and end
 *
 */

DEFINE INPUT PARAMETER parser      AS HANDLE NO-UNDO.
DEFINE INPUT PARAMETER nodehandle  AS INTEGER NO-UNDO.
{&_proparse_ prolint-nowarn(varusage)} /* passed by testrun but not used */
DEFINE INPUT PARAMETER programName AS CHARACTER NO-UNDO.
{proparse/api/proparse.i parser}


DEFINE VARIABLE currinc     AS CHARACTER NO-UNDO.
DEFINE VARIABLE outfile     AS CHARACTER NO-UNDO.
DEFINE VARIABLE whitespace  AS CHARACTER NO-UNDO.
DEFINE VARIABLE i1          AS INTEGER   NO-UNDO.
DEFINE VARIABLE numResults  AS INTEGER   NO-UNDO.
DEFINE VARIABLE numws       AS INTEGER   NO-UNDO.
DEFINE VARIABLE result      AS INTEGER   NO-UNDO.
DEFINE VARIABLE haveHidden  AS LOGICAL   NO-UNDO.

ASSIGN outfile = SESSION:TEMP-DIRECTORY + "/joanju_codepr1_out.txt":U.

OUTPUT TO VALUE(outfile).

/* Create a node handle */
ASSIGN result = parserGetHandle().

/* Create an unfiltered query
 * "all" is the query name
 * "" to get all nodes (unfiltered query)
 */
ASSIGN numResults = parserQueryCreate(nodehandle, "all":U, "").

results-loop:
DO i1 = 1 TO numResults:

  /* Get query result number i1 into our "result" node handle */
  parserQueryGetResult("all":U, i1, result).

  /* There are nodes that only have to do with the structure
   * of the tree, and don't actually relate to any token with
   * text. We skip those.
   */
  IF parserGetNodeText(result) = "" THEN
     NEXT results-loop.

  /* When we change from one include to the next, print the
   * include file name and the line number.
   */
  IF currinc <> parserGetNodeFilename(result) THEN DO:
    ASSIGN currinc = parserGetNodeFilename(result).
    PUT UNFORMATTED
      SKIP(1)
      "/* ----- ":U
      currinc
      " line ":U
      parserGetNodeLine(result)
      " ----- */":U
      SKIP
      .
  END.

  /* Print the last two chunks of whitespace in front of the token.
   * Token type "WS" is "whitespace".
   */
  ASSIGN
    whitespace = ""
    numws      = 0
    haveHidden = parserHiddenGetBefore(result).
  DO WHILE haveHidden AND numws < 2:
    IF parserHiddenGetType() = "WS":U THEN
       ASSIGN
         whitespace = parserHiddenGetText() + whitespace
         numws = numws + 1.
    ASSIGN haveHidden = parserHiddenGetPrevious().
  END.
  PUT UNFORMATTED whitespace.

  /* Now print the node's text */
  PUT UNFORMATTED parserGetNodeText(result).

END.

OUTPUT CLOSE.
RETURN.

