#!/bin/sh

usage()
{
    echo "Usage: $0 directory" >&2
    exit -1
}

resolve_vars()
{
    awk '{
     if ( index($0, "&") == 0 ) print
     else {
       #print "orig: " $0
       # status codes:
       #  0 outside quotation
       #  1 inside quotation
       #  2 expecting var
       #  3 processing var
       status=0
       substatus=0
       escape=0
       idx=1
       var_count=1
       while (idx<=length()) {
         c = substr($0, idx, 1)
         if (c == "\\" && escape=0) { escape=1; continue; }
         if (escape==1) {
           if (c=="\"") printf "\""
           escape=0
         }
         if (status==0) {
	        if (c == "\"") status=1
            printf "%c", c
         }
         else if (status==1) {
         	if (c == "&") status=2
         	else {
              if (c == "\"") status=0
              printf "%c", c
            }
         }
         else if (status==2) {
            if (c == "\"") status=3
            else { printf "&%c", c ; status=1 ; }
         }
         else if (status==3) {
		    if (c == "(") substatus=1
		    if (c == ")" && substatus==1) substatus=0;
		    else {
              if (c == "," || c == ")") {
                # string finished with var, need to print quotation mark
                printf "VAR%i", var_count++
                printf "\"%c", c
                status=0
              }
              if (c == "\"") {
                printf "VAR%i", var_count++
            	status=1
              }
            }
         }
         idx++
       }
       if (status==3) printf "\""
       printf "\n"
     }
   }'
}

extract_lines()
{
awk -vFUNCNAME="$1" '{
  if ( FOUND==1 && WRAP==1 ) {
    printf $0
    if ( substr( $0, length(), 1) == ";" ) {
       printf "\n"
       WRAP=0
    }
  }
  else {
    if ( substr( $0, length(), 1) != ";" )
      WRAP=1
    else
      WRAP=0
    if ( match( $0, FUNCNAME ) >0 ) {
      if ( WRAP == 1 ) printf $0 ; else print
      FOUND=1
    }
    else
      FOUND=0
  }
}'
}


test -z "$1" && usage

find $( eval echo $1 ) -name \*cc | xargs cat | extract_lines "->Print" | tr '\t' ' ' | grep '"' |
  sed -e 's/, *Progress::verbose//g' | resolve_vars
find $( eval echo $1 ) -name \*cc | xargs cat | extract_lines "LOGERR" | tr '\t' ' ' | grep '"' |
  sed -e 's/, *Progress::verbose//g' | resolve_vars
find $( eval echo $1 ) -name \*cc | xargs cat | extract_lines "LOGTRANS" | tr '\t' ' ' | grep '"' |
  sed -e 's/, *Progress::verbose//g' | resolve_vars
find $( eval echo $1 ) -name \*cc | xargs cat | extract_lines "Journal::cmd_message" | tr '\t' ' ' | grep '"' |
  sed -e 's/, *Progress::verbose//g' | resolve_vars

exit $status
