#! @@AWK@@ -f
BEGIN { 

ID    =    "dclpsselect 1.0"
DATE  =                               "2003/02/01(kagimoto)" 

EX    =    "select pages of dcl.ps file"

USAGE =  "% dclpsselect [p=<page>,<page>...] [from=<page>] [to=<page>] <file>"

#----------------------------------------------------------------------------
# OPTIONS
    p=0;      q["p"]   ="select pages [0]"
    from=0;   q["from"]="select range of page from: [0]"
    to=0;     q["to"]  ="select range of page to: [0]"

    if (ARGV[1] == "-help" || ARGV[1] == "help") { 
        print "  " ID,DATE
        print " --- " EX
        print " usage : " USAGE
        print "Options:"
        for (i in q) printf("+ %8s : %s\n",i,q[i])
        exit
    }

    page=0
    pages=0 
    body=0 
    ip=0
    n=-1
    llast=1
}

NR == 1 {
    while (match(p,"[,\-]")) {
        i = match(p,"[,\-]")
        c = substr(p,i,1)
        if (c == ",") {
            n++
	    plist[n] = substr(p,i-1)+0
            p = substr(p,i+1)
            llast = 1
        } else if (c == "-") {
  	    j = match(p,",")
            if (j == 0) j = length(p)+1
            kst = substr(p,1,i-1)+0; kend = substr(p,i+1,j-i-1)+0
            for (k = kst; k < kend; k++) {
                n++
                plist[n] = k
	    }
            n++
            plist[n] = kend
            p = substr(p,j+1)
            llast = 0
	}
    }
    if (llast) {
        n++; plist[n] = p+0
    }
    printf("Print Page...") > "/dev/tty"
}

/(^%%Page:)|(translate$)/ {
    page++; body=1
    if (plist[0] == 0 && from == 0  && to == 0 ) plist[0]=1
    if (body == 0+0 || (page == plist[ip] && ip < n)) {
        pages++
        ip++
        printf("[%d]",page) > "/dev/tty"
        print_label()
        next
    } else if (page >= from+0 && page < to+0) {
        pages++
        printf("[%d]",page) > "/dev/tty"
        print_label()
        next
    } else if (page == plist[n] || (page == to+0 && to+0 != 0)) {
        pages++
        ip++
        printf("[%d]\n",page) > "/dev/tty"
        print_label()
        next
    }
}

/^%%Trailer/ {
    print 
    print "%%Pages:", pages
    print "%%EOF"
    exit
}

{
    if (body == 0 || page == plist[ip-1])
        print
    else if (page >= from+0 && page <= to+0)
        print
    if (page > plist[n] && page > to+0) {
        print "%%Trailer"
        print "%%Pages:", pages
        print "%%EOF"
        exit
    }
}

function print_label() {
    if ($1 == "%%Page:")
        print "%%Page:",$2,pages
    else
        print
}
