4.3BSD/usr/contrib/icon/src/cmd/delamc.icn

#	DELAMC(1)
#
#	Delaminate file using tab characters
#
#	Thomas R. Hicks
#
#	Last modified 7/10/83
#

procedure main(a)
    local tabset, inpt, fylist, nxtarg
    if (not a[1]) | a[1] == "?" then
	Usage()
    else if match("-t",a[1]) then		# tab char given
        tabset := cset(a[1][3:0])
    else if ("-" == a[1]) then			# standard input specified
        inpt := &input
    else if not(inpt := open(a[1])) then	# file name assumed
        {
        write(&errout,"Cannot open ",a[1])
	Usage()
        }
    nxtarg := 2
    if /inpt then				# no file arg yet
        {
        if not a[2] then
	    Usage()
        else if match("-",a[2]) then		# standard input specified
            inpt := &input
        else if not(inpt := open(a[2])) then	# file name assumed
            stop("Cannot open ",a[2])
        nxtarg := 3
        }
    if 0 = *(fylist := doutfyls(a,nxtarg)) then
	Usage()
    /tabset := &ascii[10]			# tab is default separator
    delamrc(inpt,tabset,fylist)			# call main routine
end

# Usage - write usage message
#
procedure Usage()
    stop("usage: delamc [-tc] {infile | -} {outputfile | -}...")
end

# delamrc - do actual division of input file using tab chars
#
procedure delamrc(ifd,tabset,fylist)
    local i, flen, line
    while line := read(ifd) do
        {
        i := 1
        flen := *fylist
        line ? while (i <= flen) do
            {
            if i = flen then
                write(fylist[i][2],tab(0) | "")
            else
                write(fylist[i][2],tab(upto(tabset)) | tab(0) | "")
            move(1)
            i +:= 1
            }
        }
end

# doutfyls - process output file arguments; return list
#
procedure doutfyls(a,i)
    local lst, x
    lst := []
    while \a[i] do
        {
        if x := llu(a[i],lst) then		# already in list
            lst |||:= [[a[i],lst[x][2]]]
        else					# not in list
            if a[i] == "-" then			# standard out
                lst |||:= [[a[i],&output]]
            else				# a new file
                if not (x := open(a[i],"w")) then
                    stop("Cannot open ",a[i]," for output")
                else
                    lst |||:= [[a[i],x]]
        i +:= 1
        }
    return lst
end

# llu - lookup file name in output file list
#
procedure llu(str,lst)
    local i
    i := 1
    while \lst[i] do
        {
        if \lst[i][1] == str then
            return i
        i +:= 1
        }
end