#!/bin/sh
# Extract all examples from the manual source.
# Copyright (C) 1992 Free Software Foundation, Inc.

# This script is for use with GNU awk.

FILE=${1-/dev/null}

rm -f generated-tests/*.test 2>/dev/null

${AWK-gawk} '

BEGIN {
  node = "";
  seq = -1;
  count = 0;
  file = "NONE";
}

/^@node / {
  if (seq > 0)
    printf(" --  %d test%s", seq, seq == 1 ? "" : "s");
  if (seq >= 0)
    printf("\n");

  split($0, tmp, ",");
  Node = substr(tmp[1], 7);
  node = tolower(Node);
  gsub(" ", "", node);
  if (length(node) > 8) {
    printf("Node: %s - truncated", node);
    node = substr(node, 1, 8);
  } else {
    printf("Node: %s ", node);
  }
  seq = 0;
}

/^@comment ignore$/ {
  getline;
  next;
}

/^@example$/, /^@end example$/ {
  if (seq < 0)
    next;
  if ($0 ~ /^@example$/) {
    if (count > 0)
      close (file);
    seq++;
    count++;
    o = 0; 
    e = 0;
    error_flag = 0;
    i = 0;
    include_flag = 0;
    file = sprintf("generated-tests/%s.%d.test", node, seq);
    printf ("#!/bin/sh\n\n") > file;
    printf ("# %s is part of the GNU m4 testsuite\n", file) >> file;
    printf ("# generated from example in %s line %d\n\n", FILENAME, NR) >>file;
    printf (". ${srcdir}/defs\n") >> file;
    next;
  }
  if ($0 ~ /^@end example$/) {
    printthem(input, i, "in");
    printthem(output, o, "ok");
    printthem(error, e, "okerr");
    printf ("\n") >> file;
    if (include_flag == 1) printf ("M4PATH=$srcdir ") >> file;
    printf ("$M4 -d in >out") >> file;
    if (error_flag == 1) printf (" 2>err") >> file;
    if (error_flag == 1) printf ("\nsed -e \"s,^[^:]*[lt-]*m4[.ex]*:,m4:,\" err >sederr && mv sederr err") >> file;
    printf ("\n\n$CMP -s out ok") >> file;
    if (error_flag == 1) printf (" && $CMP -s err okerr") >> file;
    printf ("\n\n") >> file;
    next;
  }
  if ($0 ~ /^\^D$/)
    next;
  if ($0 ~ /^@result\{\}/) {
    gsub(/^@result\{\}/, "", $0);
    output[o++] = $0;
  }
  else if ($0 ~ /^@error\{\}/) {
    gsub(/^@error\{\}/, "", $0);
    error[e++] = $0;
    error_flag = 1;
  }
  else {
    input[i++] = $0;
    if ($0 ~ /s*include\(/) include_flag = 1;
  }
}

END {
  printf("\n");
  if (count > 0)
    close (file);
}

function printthem(thearray, thecounter, thefile) {
  if ((thecounter>0) || (thefile=="ok")) {
    printf ("\ncat <<\\EOF >%s\n", thefile) >> file;
    for (j=0; j<thecounter; j++) {
      gsub("@[{]", "{", thearray[j]);
      gsub("@}", "}", thearray[j]);
      gsub("@@", "@", thearray[j]);
      gsub("@comment.*", "", thearray[j]);
      printf ("%s\n", thearray[j]) >> file;
    }
    printf ("EOF\n") >> file;
  }
}

' $FILE >/dev/null

chmod +x generated-tests/*.test
