#! /usr/bin/mawk -f
BEGIN { 

ID    =    "dclpsfont 0.32"
DATE  =                               "95/03/19(numaguti)" 

EX    =    "convert dcl.ps characters into PostScript font"

USAGE =  "% dclpsfont [f=<font id>..] [<option>=<value>...] <file>"

#----------------------------------------------------------------------------
# OPTIONS

        f="ccCChhHHHttTT"; 
         q["f"]="font id (((idx,ifont),idx=1,imax),ifont=1,..) [ccCChhHHHttTT]"
	imax=4           ; q["imax"]="max. of index [4]"
        r=0              ; q["r"]="rotate angle [0]"
	v=0              ; q["v"]="1/0 : verbose [0]"
	inq=0            ; q["inq"]="1/0 : inquire conversion [0]"
        small=0.7        ; q["small"]="ratio of sub(super)script [0.7]"
        shift=0.3        ; q["shift"]="shift of sub(super)script [0.3]"
	lcntl=0          ; q["lcntl"]="1/0 : sub(super)script on/off [0]"
	isup="|"         ; q["isup"]="begin superscript [|]"
	isub="_"         ; q["isub"]="begin subscript [_]"
	irst="\""        ; q["irst"]="end sub(super)script [\"]"
	greek=1          ; q["greek"]="1/0 : convert greek char. [1]"
	fact=7500        ; q["fact"]="scale factor [7500]"
	fw=1             ; q["fw"]="width scale factor [1]"
	fh=1             ; q["fh"]="hight scale factor [1]"
	ofs=0            ; q["ofs"]="offset for non-standard char.(c<32) [0]"
	force=0          ; q["force"]="1/0 : convert non-standard char. [0]"
	fontu="userdef1" ; q["fontu"]="user specified font   [userdef1]"
	fontU="userdef2" ; q["fontU"]="user specified font-2 [uderdef2]"
        xmin=0           ; q["xmin"]="x min. of region [0]"
        xmax=1000        ; q["xmax"]="x max. of region [1000]"
	ymin=0           ; q["ymin"]="y min. of region [0]"
	ymax=1000        ; q["ymax"]="y max. of region [1000]"

	font["c"]="Courier";                 fwf["c"]=1.18; fhf["c"]=0.7
	font["C"]="Courier-Bold";            fwf["C"]=1.18; fhf["C"]=0.7
	font["o"]="Courier-Oblique";         fwf["o"]=1.18; fhf["o"]=0.7
	font["O"]="Courier-BoldOblique";     fwf["O"]=1.18; fhf["O"]=0.7
	font["h"]="Helvetica";               fwf["h"]=1.18; fhf["h"]=0.7
	font["H"]="Helvetica-Bold";          fwf["H"]=1.18; fhf["H"]=0.7
	font["s"]="Helvetica-Oblique";       fwf["s"]=1.18; fhf["s"]=0.7
	font["S"]="Helvetica-BoldOblique";   fwf["S"]=1.18; fhf["S"]=0.7
	font["t"]="Times-Roman";             fwf["t"]=1.18; fhf["t"]=0.7
	font["T"]="Times-Bold";              fwf["T"]=1.18; fhf["T"]=0.7
	font["i"]="Times-Italic";            fwf["i"]=1.18; fhf["i"]=0.7
	font["I"]="Times-BoldItalic";        fwf["I"]=1.18; fhf["I"]=0.7
	font["a"]="AvantGarde-Book";         fwf["a"]=1.18; fhf["a"]=0.7
        font["A"]="AvantGarde-Demi";         fwf["A"]=1.18; fhf["A"]=0.7
	font["b"]="Bookman-Light";           fwf["b"]=1.18; fhf["b"]=0.7
        font["B"]="Bookman-Demi";            fwf["B"]=1.18; fhf["B"]=0.7
	font["n"]="NewCenturySchlbk-Roman";  fwf["n"]=1.18; fhf["n"]=0.7
        font["N"]="NewCenturySchlbk-Bold";   fwf["N"]=1.18; fhf["N"]=0.7
	font["p"]="Palatino-Roman";          fwf["p"]=1.18; fhf["p"]=0.7
        font["P"]="Palatino-Bold";           fwf["P"]=1.18; fhf["P"]=0.7
	font["z"]="ZapfChancery";            fwf["z"]=1.18; fhf["z"]=0.7
        font["Z"]="ZapfChancery-Bold";       fwf["Z"]=1.18; fhf["Z"]=0.7
	font["u"]=fontu;                     fwf["u"]=1.18; fhf["u"]=0.7
	font["U"]=fontU;                     fwf["U"]=1.18; fhf["U"]=0.7

	for (i=0;i<256;i++)  tab[i]=0
	for (i=32;i<127;i++) tab[i]=i
        asc="@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`abcdefghijklmnopqrstuvwxyz{|}~"
        gdcl="ABGDEZHQIKLMNXOPRSTUFCYWabgdezhJiklmnxoprstujcyw"
#       cdcl="   ,-./] P r5%  11478 9:  #35 Y\"\"\"VLHIGN6Qrr    %B@DCER"
#       ddcl=" `'     ^ <   -+     =  <>   ~ "

        if (ARGV[1]=="help") { print_usage(); exit }
      }

/^%%Creator/     { print $0 " | " ID; next }       # add myself to Creator:

/^%%BeginProlog/ { print

                   if (fontU=="") fontU=fontu;     # user specified font
		   font["u"]=fontu;
   		   font["U"]=fontU;

	           print "/fsm " small " def"      # sub(super) script
	           print "/fsu " (1-small)/2+shift " def"
	           print "/fsd " (1-small)/2-shift " def"

		   if (greek>0) {                     
		     for (i=128;i<=175;i++) tab[i]=i		     
	             for (i=1;i<=length(gdcl);i++) { # greek character
	  	       tab[i+127] = index(asc,substr(gdcl,i,1))+128+63
		     }
		     for (i=1;i<=length(f);i++) {   # composite font
	                fn=font[substr(f,i,1)]
		        if (fn!="" && !cf[fn]) {
			   make_cf(fn); cf[fn]=1
		        }
                     }
                   }
  	           next
	         }

/^%%Begin SZTX / { 
                 print
                 sub("\\[","",$3); 
                 sub("\"","",$8); sub("\]$","",$8)
                 rsize=$3*fact; rot=$4+0; cent=$5+0; idx=$6+0; 
                 fn=$7+0; iws=$8+0

		 if(iws<0) rot=rot-90             # iws rotation

                 if(fn<=0) fn=1                   # font selection
	         i=int((length(f)+imax-1)/imax)
	         if (fn<=i)   fx = substr(f,(fn-1)*imax+1,imax)
                 else         fx = substr(f,(i-1)*imax+1,imax)
		 id=idx; if (idx>length(fx)) id=length(fx)
                 fi = substr(fx,id,1)

                 if ( font[fi] != "" ) {           # set font
 	           fon = font[fi]; 
                   sf=fw*fwf[fi]*rsize; df=fh*fhf[fi]*rsize
	           if (greek>0) {
	   	      print "/" fon "-Sy findfont " sf " scalefont setfont"   
                   }
                   else {
    		      print "/" fon " findfont " sf " scalefont setfont"   
                   }
		   if(v>0) printf("Font(%d,%d): %s\n",idx,fn,fon)>"/dev/stderr"
                 }
                 else if ( fi == "X" ) {           # remove text 
		   if(v>0) printf("Remove Font(%d,%d)\n",idx,fn)>"/dev/stderr"
                   while($0!="%%End SZTX")
                    { getline; if($NF=="W"||$NF=="RGB") print }  
                 }
                 else {                            # no conversion 
		   if(v>0) printf("NoConv Font(%d,%d)\n",idx,fn)>"/dev/stderr"
                   while($0!="%%End SZTX") { getline; print }  
                 }
                 next
              }

/%%Begin SZTXZ / {
		 print
                 sub("\\[","",$3); 
                 x=$3; y=$4; 
                 i=index($0,"\""); str=substr($0,i+1)
                 sub("\"\]$","",str)

		 xx=x*0.1; yy=y*0.1
                 if (iws<0) { xx=y*0.1; yy=x*0.1 }
		 if (xx<xmin||xx>xmax||yy<ymin||yy>ymax) { # out of bound
		   if(v>0) 
                 printf("NoConv String(%d,%d) : %s\n",xx,yy,str)>"/dev/stderr"
                   while($0!="%%End SZTXZ") { getline; print }  
                   next
	         }

	         if (expand_meta()==0) {  # unprintable 
		   if(v>0) printf("NoConv String : %s\n",str)>"/dev/stderr"
                   while($0!="%%End SZTXZ") { getline; print }  
                   next
                 }

	         if (inq>0) {             # inquire
		   printf("Convert String ? : %s\n(y/n)? >",str)>"/dev/stderr"
		   getline yn < "/dev/stderr"
	           if ( match(yn,"^Y|^y")==0 ) {
  		     if(v>0) 
                       printf("NoConv String : %s\n",str)>"/dev/stderr"
                     while($0!="%%End SZTXZ") { getline; print }  
                     next
                   }
                 }

                 if (v>0)
                 printf("Convert String : %s into %s\n",str,fon)>"/dev/stderr"
		 while ($0!="%%End SZTXZ")          # remove original
                 { getline; if($NF=="W"||$NF=="RGB") print }

		 print "gsave"                        # convert
 	         print "/sw 0 def"     
		 print x " " y " moveto"
		 print r+rot " rotate"
	         if (cent!=-1) {                    # count width to justify
 	           s=str
                   while (s!="") {
                      expand_sub()                  # split sub(super)script
		      print "/str (" sx ") def"
                      print "/sw sw str stringwidth pop add def"
	              if (sup!=0) {
 		        print "/str (" sy ") def"
                        print "/sw sw str stringwidth pop fsm mul add def"
                      }
                   }
		   if (cent==0) print "sw 2 div neg 0 rmoveto"
		   if (cent==1) print "sw neg 0 rmoveto"
                 }

		 print 0,-df/2 " rmoveto"           # sink

	         s=str
                 while (s!="") {
	            expand_sub()                    # split super(sub)script
		    print "/str (" sx ") def"       # print
		    print "str show"
	            if (sup!=0) {                   # sub(super) script
 		      print "/str (" sy ") def"
                      print "gsave"
                      if (sup==1)
                        print 0, df " fsu mul rmoveto"
	              else
                        print 0, df " fsd mul rmoveto"
                      print "fsm fsm scale"
                      print "str show"              # print sub(super) script
                      print "grestore"
 		      print "str stringwidth pop fsm mul 0 rmoveto"
                    }
                 }
		 print "grestore"
		 print; next
	    }

	    { print }

function expand_meta( ispr)                         # %ddd -> \ooo 
{                                                   # and convert greek
     gsub(/\\/,"\\\\",str)                          # \ -> \\
     ispr=1
     while(i=match(str,"%[0-9][0-9][0-9]")) {
       j=substr(str,i+1,3)
       if(j+0<32 && ofs>0) c=j+ofs
       else                c=tab[j+0]
       if (c==0) {
	  if (force==0) { ispr=0; c=j+0 }
	  else          c=32
       }
       h=sprintf("\\%03o",c)
       jj="%" j
       sub(jj,h,str)
    }
    return ispr
}
                   

function expand_sub()                              # split super(sub)script
{
     u=index(s,isup); d=index(s,isub); t=index(s,irst)
     if(lcntl>0 && u>0 &&(d==0||d>u)) {            # superscript
        sx=substr(s,1,u-1)
        if (t<u+1) t=length(s)
        sy=substr(s,u+1,t-u-1)
        sup=1
        if (t<length(s)) s=substr(s,t+1)
        else s=""
     }
     else if (lcntl>0 && d>0 &&(u==0||u<d)) {      # subscript
        sx=substr(s,1,d-1)
        if (t<d+1) t=length(s)
        sy=substr(s,d+1,t-d-1)
	sup=-1
        if (t<length(s)) s=substr(s,t+1)
        else s=""
     }
     else {                                        # none
       sx=s
       sup=0
       sy=""
       s=""
     }
}

function make_cf( f )                              # make composite font
{
     print "/" f "-Sy"
     print "12 dict begin"
     print " /Fontname 1 index def"
     print " /Encoding [0 1] def"
     print " /FontType 0 def"
     print " /FontMatrix matrix def"
     print " /WMode 0 def"
     print " /FMapType 4 def"
     print " /FDepVector"
     print " [ /" f " findfont"
     print "   /Symbol findfont"
     print " ] def"
     print " currentdict"
     print "end"
     print "definefont pop"
}


function print_usage()
{
 if  (ENVIRON["PAGER"]!="") filt="sort -f | " ENVIRON["PAGER"]
 else filt="sort -f | more"

 print "  " ID,DATE | filt
 print " --- " EX | filt
 print " usage : " USAGE | filt

 print "*** Options are:" | filt
 for (i in q) 
    printf("+ %8s : %s\n",i,q[i]) | filt

 print "+** Font id are:" | filt
 for (i in font)
    if(match(i,"[A-Z]")) 
       printf("- %1s ::  %s\n",i,font[i]) | filt
    else
       printf("- %1s :   %s\n",i,font[i]) | filt
}
