# Extract a message, substituting arguments where appropriate

BEGIN {
    found = 0;
    message = "NullMessage"
}

/^Message / {
    if (message == "NullMessage") {
        message=$2
        messagetag=message ":"
        arg[1] = $3
        arg[2] = $4
        arg[3] = $5
        arg[4] = $6
        next
    }
}

/^Product / {
   productstring = substr($0, 9);
   next
}

/^#/ {
    next
}


{
    if (found == 1) {
       next
    }
    if (index($0,messagetag) != 1)  {
       next
    }
    while (index($0,"-<") != 1) {
        getline
    }
    getline
    while (index($0,">-") != 1) {
        # Cant use gsub here because not all awks support it
        # Watch for off by 1s when testing this
        line = $0
        while ((d=index(line,"#1")) != 0) {
            pre = substr(line, 1, d-1)
            post = substr(line, d+2)
            line = pre arg[1] post
        }
        while ((d=index(line,"#2")) != 0) {
            pre = substr(line, 1, d-1)
            post = substr(line, d+2)
            line = pre arg[2] post
        }
        while ((d=index(line,"#3")) != 0) {
            pre = substr(line, 1, d-1)
            post = substr(line, d+2)
            line = pre arg[3] post
        }
        while ((d=index(line,"#4")) != 0) {
            pre = substr(line, 1, d-1)
            post = substr(line, d+2)
            line = pre arg[4] post
        }
        while ((d=index(line,"#P")) != 0) {
            pre = substr(line, 1, d-1)
            post = substr(line, d+2)
            line = pre productstring post
        }
        print line;
        getline
    }
    found = 1
    next
}
