/*
   Copyright by Jingbai Wang 1989
   jbw@pittvms.bitnet
   jbw@cisunx.UUCP

   The author permits free distribution of this program for non-profit
   purposes. Commercial application is reserved by the author.
*/

/**********************************************************************
*                          ChTeX/Scribe/WStroff                       *
*                                                                     *
*      Translate a CCDOS output file into a Scribe or TeX file, and   *
*        creates a PostScript font header file in the same time       *
*         it will also be able to translate a CCDOS file into         *
*          a Scribe or TeX file for ASCII output (i.e., file device)  *
*           CCDOS files can also be dumped into PostScript directly   *
*                                                                     *
*								      *
*	For the ones without TeX or Scribe or proper dvi->ps driver   *
*	chtex -w  serves as a Chinese -> PS device driver and it is   *
*	also an ASCII -> PS device driver. It will		      *
* 	be able to interpret WordStar and troff commands	      *
***********************************************************************/
#if VMS|unix
#else    /* DOS should be treated separated */
#define MSDOS 1
/*
#if TURBO
#include <mem.h>
#endif
*/
#endif

/*
Ideas: 
   1) Use either of the 48x48, 24x24 or 16x16 Chineses character font library
      when 24x24 library is used, about 2000 distinct Chinese characters
      can be used in a document, but if 48x48 is used no more than 1000
      should be used, otherwise printer VM will be exceeded.

 * Today's cclib.16 has 7 symbol zooms (with the remaining 8 zooms skipped),
 and 40 + 32 Chinese characters zooms. In each zoom, there are 94x32 bytes
 It is recommended for draft version output, or the output for e-mail, or
 documents with small fonts.

 ** Today's cclib.24 has 15 symbol zooms (including 5 blank ones),
 and 40 + 32 Chinese characters zooms. In each zoom, there are 94x72 bytes
 It is recommended for general use.

 *** Today's cclib.48 has 12 symbol zooms which are copied from cclib.24
   i.e., the symbol section length is 72x94x12=81216 bytes (72 bytes per
   symbol), and 40+32 Chinese character zooms of 1082880 + 866304 bytes
   (288 bytes per character); 
   This version of 48x48 library is of poor quality, many lines are too thin.
   If the font size is scaled up to 14pts or more, the output is acceptable,
   otherwise some lines will disappear.  Thus,  I do not recommend
   using it unless you need large characters.

   2) Each Chinese character is encoded with two extended ASCII codes
      ranging 161 ~ 254
   3) Use standard Mainland China GuoBiao code as standard input
   4) In PostScript use dynamic encoding, i.e., just encode as many distinct
      characters as appeared in the document.
   5)  Use 33 ~ 251, 218 characters in PostScript, and  maximum number of
      characters does not exceed 94x94. 
   6) If used with Scribe and TeX/LaTeX, this program is a pre-processor
      and post-processor. Otherwise, it works for WordStar as a 
      post-processor , or works like troff.
   7) Fonts can be built for the entire document, 
             flushed per page, or per n pages.


*/

/* ************** The following block is site-dependent, edit before use */

/* What are the Chinese font library files */
/* UNIX environment variables:
CCLIB16jt
CCLIB16ft
CCLIB24jt
CCLIB24ft
CCLIB48jt
CCLIB48ft

VMS logical names:
CCLIB16$jt
CCLIB16$ft
cclib24$jt
cclib24$ft
cclib48$jt
cclib48$ft


if no environment or logical is found use the following definitions:
*/

#if unix|VMS
#if unix
extern char *getenv();

#ifndef CCLIB16jt
#define CCLIB16jt "/afs/ir/users/m/mpyoung/tex/chtex/cclib/cclib.16"  /* Simplified */
#endif
#ifndef CCLIB16ft
#define CCLIB16ft "/afs/ir/users/m/mpyoung/tex/chtex/cclib/cclibf.16"   /* Long form */
#endif
#ifndef CCLIB24jt
#define CCLIB24jt "/afs/ir/users/m/mpyoung/tex/chtex/cclib/cclib.24"  /* Simplified */
#endif
#ifndef CCLIB24ft
#define CCLIB24ft "/afs/ir/users/m/mpyoung/tex/chtex/cclib/cclibf.24"   /* Long form */
#endif
#ifndef CCLIB48jt
#define CCLIB48jt "/afs/ir/users/m/mpyoung/tex/chtex/cclib/cclib.48"  /* Simplified */
#endif
#ifndef CCLIB48ft
#define CCLIB48ft "/afs/ir/users/m/mpyoung/tex/chtex/cclib/cclibf.48"   /* Long form */
#endif
#else
#define CCLIB16jt "usr2:[10555.jwang.ccdos]CCLIB.16"  /* Simplified */
#define CCLIB16ft "usr0:[12162.jbw.ccdos]CCLIBf.16"   /* Long form */
#define CCLIB24jt "usr0:[12162.jbw.ccdos]CCLIB.24"  /* Simplified */
#define CCLIB24ft "usr0:[12162.jbw.ccdos]CCLIBf.24"   /* Long form */
#define CCLIB48jt "usr0:[12162.jbw.ccdos]CCLIB.48"  /* Simplified */
#define CCLIB48ft "usr0:[12162.jbw.ccdos]CCLIBf.48"   /* Long form */
#endif
#else  /* Now for DOS only */
extern char *getenv(); 
#define CCLIB16jt "CCLIB.16"  /* Simplified */
#define CCLIB16ft "CCLIBf.16"   /* Long form */
#define CCLIB24jt "CCLIB.24"  /* Simplified */
#define CCLIB24ft "CCLIBf.24"   /* Long form */
#define CCLIB48jt "CCLIB.48"  /* Simplified */
#define CCLIB48ft "CCLIBf.48"   /* Long form */
#endif


#define MAX_CHAR 8400    /* what's the maximum number of characters in the
                            library , normally 8176 maximum*/

#if VMS|unix
#define MAX_USED 4500    /* suppose we'd use 4500 maximum distinct chars in an
                            article, you may use MAX_CHAR*/
#else
#define MAX_USED 1    /* if it is DOS, load characters one by one*/
#endif

#define FALSE 0
#define TRUE 1
#define version "(1.00)"    /* version number */

#define TWENTY_FOUR TRUE  /* Let us use  24x24 library*/

/* default 24x24 fonts */
#define record_length 72
#define cclib_length 610000

  
/**********************************************************************/


#if VMS
#include <file.h>
#else
#include <fcntl.h>
#endif
#include <stdio.h>
#include <string.h>
#include <math.h>


#define font_group_size 218
#define font_overhead 32

int sideway = 0;  /* printing characters vertically?  -v */
int Cconvert= 0;  /* translate English punctuations into Chinese mode?  -c */
int AllConvert=0; /* translate English Characters into Chinese mode?  -a */
int jt3 = 1;      /* Use simplified characters as default */
int final_version=0;  /* If it is final version, use simplified 48x48 fonts -F
			otherwise 24x24 */
int draft_version=0;  /* If it is draft version, use simplified 16x16 fonts -D
			otherwise 24x24 */
int newheader=0;   /* use a new header? */
int WStroff=0;    /* translate WStroff file into PostScript -w */
int rec_len = 72; /* record length of cclib, default for 24x24 fonts*/

#define CLS printf("")

int chinese[MAX_CHAR];        /* MAX_CHAR Chinese characters */  
int chinese_group[79];    /* divide MAX_CHAR Chinese characters into 79 groups
                             each containing 219 codes maximum, in
                             .e.g, /chfont1, chfont2*/  
int max_group;            /* maximum number of groups in this document */
char mpyfontsize[80];
char ccnormalsize[2400];
int chinese_pair=1;  /* Check two ASCII bytes for a Chinese character */
int chinese_byte1;
int chinese_used=0;   /* Number of Chinese characters used */
int max_quwei=0;      /* largest quwei number */

unsigned char inbuffer[1025];  /* read in 1 kbyte a time */
char infile_name[60], outfile_name[60], logfile_name[60];
char tempfile[60];
FILE *infile, *outfile, *errfile;
long int line_no=0, line_last=0;
int err_no = 0;



begin_dofont(outfile)
FILE *outfile;
{
int i;

if (draft_version)
fputs("\
dofont\n\
/imagemaskmatrix [1 0 0 -1 0 0] def\n\
/FontMatrix [0.04532 0 0 0.04532 0 0] def Encoding\n\
", outfile);
else
fputs("\
dofont\n\
/imagemaskmatrix [1 0 0 -1 0 0] def\n\
/FontMatrix [0.03021 0 0 0.03021 0 0] def Encoding\n\
", outfile);

fputs("\
dup 32 /ch32 put dup 33 /ch33 put dup 34 /ch34 put dup 35 /ch35 put\n\
dup 36 /ch36 put dup 37 /ch37 put dup 38 /ch38 put dup 39 /ch39 put\n\
", outfile);

for (i=4; i<25; i++)
fprintf(outfile, "\
dup %d0 /ch%d0 put dup %d1 /ch%d1 put\n\
dup %d2 /ch%d2 put dup %d3 /ch%d3 put dup %d4 /ch%d4 put dup %d5 /ch%d5 put\n\
dup %d6 /ch%d6 put dup %d7 /ch%d7 put dup %d8 /ch%d8 put dup %d9 /ch%d9 put\n",
i,i,i,i,i,i,i,i,i,i,i,i,i,i,i,i,i,i,i,i);

fputs("\
dup 250 /ch250 put dup 251 /ch251 put\n\
pop /CharData 252 dict def\n\
CharData begin\n\
", outfile);

if (final_version)
 fputs("/ch32 [0.0331 0 0 0 0 1 1 0 0 1 <>] def", outfile);
else if(draft_version)
 fputs("/ch32 [0.0497 0 0 0 0 1 1 0 0 <>] def", outfile);
else
 fputs("/ch32 [0.0331 0 0 0 0 1 1 0 0 <>] def", outfile);

}


end_dofont(n)
int n;
{
 fprintf(outfile, "\n/.notdef [.24 0 0 0 0 1 0 0 <>] def\n\
end\n\
end\n\
/chfont%d exch definefont pop\n", n);
}


initialize() /* print out the PostScript prologue and initialize some vectors*/
{
 int i;
   for (i=0; i<MAX_CHAR; i++)
     chinese[i]=0;

   chinese_group[0] = 0;
   for (i=1; i<75; i++)
     chinese_group[i] = chinese_group[i-1] + font_group_size;

}


Extended_Ascii()
{
int i;

fputs("\
      Entry (Char \"128\", width 725),\n\
      Entry (Char \"129\", width 725),\n\
", outfile);
for (i=13; i<25; i++)
fprintf(outfile, "      Entry (Char \"%d0\", width 725),\n\
      Entry (Char \"%d1\", width 725),\n\
      Entry (Char \"%d2\", width 725),\n\
      Entry (Char \"%d3\", width 725),\n\
      Entry (Char \"%d4\", width 725),\n\
      Entry (Char \"%d5\", width 725),\n\
      Entry (Char \"%d6\", width 725),\n\
      Entry (Char \"%d7\", width 725),\n\
      Entry (Char \"%d8\", width 725),\n\
      Entry (Char \"%d9\", width 725),\n\
", i,i,i,i,i,i,i,i,i,i);

fputs("\
      Entry (Char \"250\", width 725),\n\
      Entry (Char \"251\", width 725),\n\
      Entry (Char \"252\", width 725),\n\
      Entry (Char \"253\", width 725),\n\
      Entry (Char \"254\", width 725),\n\
      Entry (Char \"255\", width 725),\n\
", outfile);
}


Sort_Fonts()   /* Check which Chinese characters are used;
                 Sort through the whole file to check which different
                 Chinese characters have been used, and store them
                 into an array for the later use*/
{
int quwei, inchar,  i, input_file=0, j;
FILE *input_F;
char inputname[80];

  while( fgets(inbuffer, 1024, infile) != NULL)
 {/* start analysing input file */

INFILE: if (input_file)
	{
	if(fgets(inbuffer, 1024, input_F) == NULL) 
		{
			input_file = 0;
			fclose(input_F);
		}
	}

   for (i=0; i<strlen(inbuffer); i++)
 {   
    switch(inbuffer[i])
   {
	/* we also need to find things in the include/input files */
    case '.':
    		if(WStroff&&(i==0)) /* here comes WStroff commands*/
		{       inputname[0] = '\0';
			for (j=1; j<3; j++)
       			if ((inbuffer[j] > 96) && (inbuffer[j] <126))
			inbuffer[j] -= 32;
		if (strncmp(&inbuffer[1], "IF", 2)==0)
			{sscanf(&inbuffer[3], "%s", inputname);
			if ((input_F=fopen(inputname, "r"))!=NULL)
				input_file = 1;
			else fprintf(stderr, 
			"Warning: can't open input files%s.\n", inputname);
			goto next_while;
			}	
			
		}
    		break;
    case '@':  /* check Scribe @include command, not done yet */
    		break;
    case '\\': /* check TeX/LaTeX \input and \include command, not done yet*/
    		break;
    case 10:
    case 138:
    case 13:
         if (chinese_pair<0) 
           {fprintf(stderr, "Unbalanced Chinese characterbyte %d!\n", chinese_byte1); chinese_pair = 1;}
           break;
    default: if ((inbuffer[i] > 160) && (inbuffer[i] < 255)) /* Chinese */
         {
          chinese_pair *= -1;
            if (chinese_pair<0) {chinese_byte1=inbuffer[i];
             /*  In older library, 168 ~ 175 are repeating 176 ~ 183 */
             /*   if (chinese_byte1>175) chinese_byte1 -= 8; */
                }
              else { quwei = (chinese_byte1-161)*94+(inbuffer[i]-161) ;
                 if (quwei>max_quwei) max_quwei = quwei;
             if (!chinese[quwei])
                chinese[quwei] = ++chinese_used;
                }
            break;
         }
         else  if (Cconvert)  /* if it is ASCII and to be converted */
          {  
            if (WStroff)
	    {	if (inbuffer[i]==32) quwei = 0;
		else quwei=All_Ch(inbuffer[i]);
	    }
	    else quwei=Part_ASCII_Ch(inbuffer[i]);

	    if (quwei>=0)
	    {
                if (quwei>max_quwei) max_quwei = quwei;
                if (!chinese[quwei])
                    chinese[quwei] = ++chinese_used;
	    }

          }

    	}
      }
    next_while:;
    if (input_file) goto INFILE;
    }
/* Since the file pointer has gone to the end, 
   close the file and open it up again */
 fclose(infile);

 infile=fopen(infile_name, "r");

    max_group = chinese_used/font_group_size + 0.9;
       fprintf(stderr, "Number of distinct Chinese characters used=%d\n", 
chinese_used);
     fprintf(stderr, "Maximum QuWei number=%d ...\n", max_quwei);

}


Scribe_preprocessor() /* Translate ccdos format into Scribe format */
{

int quwei, tmpchar, i, current_group, the_group, group_member, line_length;
int end_ch, last_char=0;

current_group = -1;
group_member = 0;

fprintf(stderr, "Generating New Manuscript %s ...\n", tempfile);

  outfile = fopen("chfont.raw", "w");
 

for (i=0; i<= max_group; i++)
  {fprintf(outfile, "\
@Marker(RawFont, chfont%d, PostScript)\n\
@DefineRawFont<chfont%d,\n\
      AboveBaseLine 730,\n\
      BelowBaseLine 10,\n\
      Location \"Select =  '/chfont%d'\",\n\
", i, i, i);
Extended_Ascii();
  fputs("\
      Entry (Char AsciiGraphics, width 725),\n\
      Entry  (Char \"32\", width 3)>\n\n\
", outfile);
  }

  fclose(outfile);

  outfile = fopen(tempfile, "w");

 fputs("\
@definefont{ChineseFont,\n", outfile);

  for (i=0; i<=max_group; i++)
fprintf(outfile, "\
%c = <RawFont chfont%d>,\n", 65+i, i);

   fputs("}\n\
", outfile);

fputs("@textform<sp=@hsp(0.001pts),\n\
bf={@!@parm(text)@/@hsp(0.2pt)@parm(text)@/@hsp(0.2pt)@parm(text)}>", outfile);
  for (i=0; i<=max_group; i++)
fprintf(outfile, "\
@define(chfont%d, Font=ChineseFont, facecode=%c, spaces=ignored)\n", i, 65+i);

line_length = 0;

  while( fgets(inbuffer, 1024, infile) != NULL)
 {

   for (i=0; i<strlen(inbuffer); i++)
  { end_ch = 0;   
    switch(inbuffer[i])
   {
    case 26: break;
    case 10:
    case 138: fputc('\n', outfile); line_length=0;
            chinese_pair = 1;
           break;
    case 141:
    case 13:  break;
    default:
/* 1. If it is a Chinese character */
   if ((inbuffer[i] > 160) && (inbuffer[i] < 255))
         {
          chinese_pair *= -1;
            if (chinese_pair<0) {chinese_byte1=inbuffer[i];
             /* 168 ~ 175 are repeating 176 ~ 183 
              if (chinese_byte1>175) chinese_byte1 -= 8; */
                }
              else 
                { quwei = (chinese_byte1-161)*94+(inbuffer[i]-161) ;
begin_ch:              the_group = chinese[quwei]/font_group_size;

	switch(quwei) /* if it is a punctuation, stick to the previous char */
	{
		case 1:
		case 2:
		case 188:
/*
		case 195:
*/
		case 196:
		case 199:
		case 201:
		case 213:
		case 214:
		case 218:
			last_char = 0; break;
	}

             if (current_group != the_group) 
                   {
                       if (group_member > 0)
                         {end_ch++;
                         fprintf(outfile, "@end{chfont%d}", current_group);
                         line_length += 14;}
                         if (line_length>78) {fputs("@~\n", outfile);
                                            line_length=0;}

                       current_group = the_group;
                         fprintf(outfile, "@begin{chfont%d}", current_group);
                       line_length += 15;
                         if (line_length>78) {fputs("@~\n", outfile);
                                            line_length=0;}

                      group_member = 0;

                   }
                   group_member ++;
     tmpchar = chinese[quwei]-font_group_size*the_group+1 + font_overhead; 
     if (tmpchar>126) tmpchar ++;

                       if (line_length>75) {fputs("@~\n", outfile);
                                            line_length=0;
                                           }

         if (tmpchar != '@') 
             {if (last_char)
		fputc(32, outfile);
		fputc(tmpchar, outfile);
		
                       line_length += 2;
             }     
            else {if (last_char)
			fputc(32, outfile);
			fputs("@@ ", outfile);
                       line_length += 3;
                  }
		 last_char = 1;
           }
          break;
        }
  /* 2. else it is not a Chinese character */
    else 
       {  
/*  do not do converting here, do it in ChText
           if (Cconvert)
                 {  
                   quwei=Part_ASCII_Ch(inbuffer[i]);
                   if (quwei>=0) goto begin_ch;

                 }
*/
		 last_char = 0;
              if (group_member > 0)
                         {fprintf(outfile, "@end{chfont%d}", current_group);
                          group_member = 0;
                          end_ch ++;
                          current_group = -1;
                         }

           if (inbuffer[i]>127) inbuffer[i] -= 128; /* It's a WordStar char*/
/*
           if((inbuffer[i]==32)&&(inbuffer[i+1]!=32)&&(end_ch==1))
           fprintf(outfile, " @sp()");
           else
*/
           fputc(inbuffer[i], outfile);
           line_length ++;



       }
   }
  }
 }

 if (group_member > 0) fprintf(outfile, "@end{chfont%d}", current_group);
                        
  fclose (infile);
  fclose (outfile);

}



TeX_preprocessor() /* Translate ccdos format into TeX format */
{

int quwei, tmpchar, i, current_group, the_group, group_member, line_length;
int last_char = 0;
char mpycary[10][256];
char mpycsize[10][256];
int j;

fprintf(stderr, "Generating TeX file %s ... \n", tempfile);
current_group = -1;
group_member = 0;

  outfile = fopen(tempfile, "w");

for (i=0; i<= max_group; i++)
  { 
                       if (i>25) tmpchar = i + 97;
                         else  tmpchar = i + 65;
          fprintf(outfile, "\\font\\chfont%cx=chfont%d %s\n\
\\def\\chfont%c{\\chfont%cx \\def~{\\hskip 0pt plus 1pt }}\n", tmpchar, i,
mpyfontsize,tmpchar,tmpchar);
  }

strcpy(mpycary[0], "\\def\\ccnormalsize{");
strcpy(mpycsize[0], mpyfontsize);
strcpy(mpycary[1], "\\def\\cHuge#1{");
strcpy(mpycsize[1], "scaled 30000 ");
strcpy(mpycary[2], "\\def\\chuge#1{");
strcpy(mpycsize[2], "scaled 25000 ");
strcpy(mpycary[3], "\\def\\cLarge#1{");
strcpy(mpycsize[3], "scaled 20000 ");
strcpy(mpycary[4], "\\def\\clarge#1{");
strcpy(mpycsize[4], "scaled 15000 ");
strcpy(mpycary[5], "\\def\\cMedium#1{");
strcpy(mpycsize[5], "scaled 12000 ");
strcpy(mpycary[6], "\\def\\cmedium#1{");
strcpy(mpycsize[6], "scaled 10000 ");
strcpy(mpycary[7], "\\def\\cSmall#1{");
strcpy(mpycsize[7], "scaled 8000 ");
strcpy(mpycary[8], "\\def\\csmall#1{");
strcpy(mpycsize[8], "scaled 5000 ");

for (j=0; j<=8; j++) {
fprintf(outfile, "%s", mpycary[j]);
for (i=0; i<= max_group; i++)
  { 
                       if (i>25) tmpchar = i + 97;
                         else  tmpchar = i + 65;
          fprintf(outfile, "\\font\\chfont%cx=chfont%d %s\n", tmpchar, i, mpycsize[j]);
  }
if (j < 1)
  fprintf(outfile, "}\n");
else
  fprintf(outfile, "#1\\ccnormalsize}\n");
}

line_length = 0;

  while( fgets(inbuffer, 1024, infile) != NULL)
 {

   for (i=0; i<strlen(inbuffer); i++)
  {   
    switch(inbuffer[i])
   {
    case 26: break;
    case 10:
    case 138:
           if ((group_member>0)&&(line_length>0))
              fputs("%\n", outfile);
              else fputc('\n', outfile);
           line_length=0;
               chinese_pair = 1;
           break;
    case 141:
    case 13:  break;
    default:
/* 1. If it is a Chinese character */
   if ((inbuffer[i] > 160) && (inbuffer[i] < 255))
         {
          chinese_pair *= -1;
            if (chinese_pair<0) {chinese_byte1=inbuffer[i];
             /* 168 ~ 175 are repeating 176 ~ 183 
              if (chinese_byte1>175) chinese_byte1 -= 8; */
                }
              else 
                { quwei = (chinese_byte1-161)*94+(inbuffer[i]-161) ;
begin_ch:              the_group = chinese[quwei]/font_group_size;

	switch(quwei) /* if it is a punctuation, stick to the previous char */
	{
		case 1:
		case 2:
		case 188:
/*
		case 195:
*/
		case 196:
		case 199:
		case 201:
		case 213:
		case 214:
		case 218:
			last_char = 0; break;
	}


             if (current_group != the_group) 
                   {
                       if (group_member > 0)
                         {
                         fputc('}', outfile);
                         line_length ++;}
                         if (line_length>78) {fputs("%\n", outfile);
                                            line_length=0;}

                       current_group = the_group;
                       if (current_group>25) tmpchar = current_group + 97;
                         else  tmpchar = current_group + 65;
                         fprintf(outfile, "{\\chfont%c ", tmpchar);
                       line_length += 10;
                         if (line_length>78) {fputs("%\n", outfile);
                                            line_length=0;}

                       group_member = 0;

                   }
                   group_member ++;
     tmpchar = chinese[quwei]-font_group_size*the_group+1 + font_overhead; 

                       if (line_length>75) {fputs("%\n", outfile);
                                            line_length=0;
                                           }
       switch(tmpchar)
             { /* check out special symbols. */
               case '#':
               case '$':
               case '%':
               case '&':
	       	if(last_char) fputc('~', outfile);
			fprintf(outfile, "\\%c", tmpchar);
                       line_length += 3;
                       break;
               case '_':
               case '\\':
               case '{':
               case '}':
               case '~':
               case '^':
	       	if(last_char) fputc('~', outfile);
                       fprintf(outfile, "\\char%d", tmpchar);
                       line_length += 8; break;
           default:
                 if (tmpchar>126)
                    { tmpchar ++;
	       	if(last_char) fputc('~', outfile);
                       fprintf(outfile, "\\char%d", tmpchar);
                       line_length += 8;
                    }
                   else 
                    {
	       	if(last_char) fputc('~', outfile);
	       	    fputc(tmpchar, outfile);
                    line_length += 2;           
                    }
               }
		 last_char = 1;

           }

        }
  /* 2. else it is not a Chinese character */
    else 
       {
/* do not do converting here
           if (Cconvert)
                 {  
                   quwei=Part_ASCII_Ch(inbuffer[i]);
                   if (quwei>=0) goto begin_ch;

                 }
*/
		 last_char = 0;
                if (group_member > 0)
                         {fputs("}", outfile);
                          group_member = 0;
                          current_group = -1;
                         }
           if (inbuffer[i]>127) inbuffer[i] -= 128; /* It's a WordStar char*/
           	       		fputc(inbuffer[i], outfile);
           line_length ++;

       }
   }
  }
 }

 if (group_member > 0) fputc('}', outfile);
                        
  fclose (infile);
  fclose (outfile);

}


Scribe_preprocessor1() /* Translate ccdos format into Scribe format for
			lpt or doc device*/
{

int i, current_group, line_length, last_char=0, byte1;
long int quwei;

current_group = -1;

fprintf(stderr, "Generating New Manuscript %s ...\n", tempfile);


  outfile = fopen(tempfile, "w");

 fputs("\
@definefont{ChineseFont,\n\
r = <RawFont jbwlptr>}", outfile);


fputs("\
@define(chfont, Font=ChineseFont, facecode=R, spaces=ignored)\n", outfile);

line_length = 0;

  while( fgets(inbuffer, 1024, infile) != NULL)
 {

   for (i=0; i<strlen(inbuffer); i++)
  { 
    switch(inbuffer[i])
   {
    case 26: break;
    case 10:
    case 138: fputc('\n', outfile); line_length=0;
           chinese_pair = 1;
           break;
    case 141:
    case 13:  break;
    default:
/* 1. If it is a Chinese character */
   if ((inbuffer[i] > 160) && (inbuffer[i] < 255))
         {
          chinese_pair *= -1;

            if (chinese_pair<0) {
             if (current_group < 0) 
                   {
                         if (line_length>78) {fputs("@~\n", outfile);
                                            line_length=0;}

                       current_group = 1;
                         fputs("@begin{chfont}", outfile);
		   }
		
		   byte1 = inbuffer[i];
                       line_length ++;
                }
              else 
                { 
			quwei = (chinese_byte1-161)*94+(inbuffer[i]-161) ;
                       if (line_length>75) {fputs("@~\n", outfile);
                                            line_length=0;
                                           }
	switch(quwei) /* if it is a punctuation, stick to the previous char */
	{
		case 1:
		case 2:
		case 188:
/*
		case 195:
*/
		case 196:
		case 199:
		case 201:
		case 213:
		case 214:
		case 218:
			last_char = 0; break;
	}

		if (last_char) fputc(32, outfile);
		fputc(byte1, outfile);
		fputc(inbuffer[i], outfile);
                       line_length += 2;
		       last_char = 1;

		}
          break;
        }
  /* 2. else it is not a Chinese character */
    else 
       {  
	last_char = 0;
              if (current_group > 0)
                         {fputs("@end{chfont}", outfile);
                          current_group = -1;
                         }

           if (inbuffer[i]>127) inbuffer[i] -= 128; /* It's a WordStar char*/

           fputc(inbuffer[i], outfile);
           line_length ++;



       }
   }
  }
 }

 if (current_group > 0) fputs("@end{chfont}", outfile);
                        
  fclose (infile);
  fclose (outfile);

}



TeX_preprocessor1() /* Translate ccdos format into TeX format for dvidoc */
{

int i, current_group, line_length, last_char=0, byte1;
long int quwei;

fprintf(stderr, "Generating TeX file %s ... \n", tempfile);
current_group = -1;

  outfile = fopen(tempfile, "w");

    fputs("\\font\\chfontcx=chfont0 ", outfile);
    fputs(mpyfontsize, outfile);
    fputs("\n\\def\\chfont{\\chfontcx \\ignorespaces \\def~{\\hskip 0 plus 1 }}\n", outfile);

line_length = 0;

  while( fgets(inbuffer, 1024, infile) != NULL)
 {

   for (i=0; i<strlen(inbuffer); i++)
  {   
    switch(inbuffer[i])
   {
    case 26: break;
    case 10:
    case 138:
           if (line_length>0)
              fputs("%\n", outfile);
              else fputc('\n', outfile);
           line_length=0;
              chinese_pair = 1;
           break;
    case 141:
    case 13: break;
    default:

   if ((inbuffer[i] > 160) && (inbuffer[i] < 255))
         {/* 1. If it is a Chinese character */
          chinese_pair *= -1;
            if (chinese_pair<0) {
             if (current_group <0 ) 
                   {

                       current_group = 1;
                         fputs("{\\chfont ", outfile);
                       line_length += 8;
                         if (line_length>78) {fputs("%\n", outfile);
                                            line_length=0;}

                   }
		   byte1 = inbuffer[i];

                }
		else
		{
			quwei = (chinese_byte1-161)*94+(inbuffer[i]-161) ;

	switch(quwei) /* if it is a punctuation, stick to the previous char */
	{
		case 1:
		case 2:
		case 188:
/*
		case 195:
*/
		case 196:
		case 199:
		case 201:
		case 213:
		case 214:
		case 218:
			last_char = 0; break;
	}

		if (last_char) fputc('~', outfile);
 	        fprintf(outfile, "\\char%d\\char%d", byte1, inbuffer[i]);
                       line_length += 10;
		       last_char = 1;

              }

          }
  /* 2. else it is not a Chinese character */
    else 
       {
                if (current_group > 0)
                         {fputc('}', outfile);
                          current_group = -1;
                         }

           if (inbuffer[i]>127) inbuffer[i] -= 128; /* It's a WordStar char*/
           	       		fputc(inbuffer[i], outfile);
           line_length ++;

       }
   }
  }
 }

 if (current_group > 0) fputc('}', outfile);
                        
  fclose (infile);
  fclose (outfile);

}



main(argc, argv)
int argc;
char *argv[];
{
int in_file,out_file, status;
int i,j, name_count=0;
char string[60];
char out_ok=1;
char ch, quit;
#if MSDOS|PCDOS
FILE *datafile;
#endif
/* the following variables are used for the option flags */
int Scribe=0,      /* Convert into a Scribe file              -s */
    TeX=1,         /* Convert into a TeX file                 -t */
    TexT=0,         /* Convert into a TeX file                 -x */
    LaTeX=0,       /* Convert into a LaTeX file               -l */
    Decode=0,      /* decode the encoded file                 -d */
    Encode=0;      /* encode into standard ASCII file         -e */

/* The following flags are global 

   Cconvert convert all English characters into Chinese mode         -c
   sideway  print Chinese characters vertically(use Chinese mode)    -v

*/


CLS;
in_file=1; out_file=1;

jt3 = 1;

strcpy(mpyfontsize, "at 10pt\0");
ccnormalsize[0] = '\0';
for (i = 1; i<argc; i++)
 if (argv[i][0] == '-')
  { for (j=1; j<strlen(argv[i]); j++)
     switch(argv[i][j])
      {
       case 's': 
       case 'S': Scribe = 1; TeX = 0; LaTeX = 0; break;
       case 't': 
       case 'T': TeX = 1; Scribe = 0; LaTeX = 0; break;
       case 'l': 
       case 'L': LaTeX = 1; Scribe = 0; TeX = 0; break;
       case 'w': 
       case 'W': WStroff = 1; Scribe = 0;  TeX = 0; break;
       case 'v': 
       case 'V': sideway = 1; break;
       case 'c': 
       case 'C': Cconvert =1; break;
       case 'x': 
       case 'X': TexT =1; break;
       case 'a': 
       case 'A': AllConvert =1; Cconvert=0; break;
       case 'D':
       case 'd': Decode =1; Scribe = 0; TeX = 0; break; 
       case '-': draft_version = 1; rec_len = 32; break;
       case 'e': 
       case 'E': Encode =1; Scribe = 0;  TeX = 0; break;
       case '+': final_version = 1; rec_len = 288; break; 
       case 'F':
       case 'f': jt3 =0; break;
	case '1': strcpy(mpyfontsize, "scaled 30000\0"); break;
	case '2': strcpy(mpyfontsize, "scaled 25000\0"); break;
	case '3': strcpy(mpyfontsize, "scaled 20000\0"); break;
	case '4': strcpy(mpyfontsize, "scaled 15000\0"); break;
	case '5': strcpy(mpyfontsize, "scaled 12000\0"); break;
	case '6': strcpy(mpyfontsize, "scaled 10000\0"); break;
	case '7': strcpy(mpyfontsize, "scaled 8000\0"); break;
	case '8': strcpy(mpyfontsize, "scaled 5000\0"); break;
       default: fprintf(stderr, "Invalid flag = %c\n", argv[i][j]);
      }
   

  }
 else
  { 

   switch (name_count++)
   {
    case 0: in_file=0; strcpy(infile_name,argv[i]); break;
    case 1: out_file=0; strcpy(outfile_name,argv[i]); break;
    default: fprintf(stderr, "Extra argument = %s\n", argv[i]);
   }

  }



if (Scribe)
  fprintf(stderr, "ChScribe %s JBW 1989\n", version);
if (TeX||LaTeX)
  fprintf(stderr, "ChTeX %s JBW 1989\n", version);
if (WStroff)
   fprintf(stderr, "Chinese WStroff->ps %s JBW 1989\n", version);

 if (in_file) 
   {
   printf("   ** Input file >");
   scanf("%s",infile_name);
   fflush(stdin);
   }


   if ((infile=fopen(infile_name,"r"))==NULL)
     {
       printf("Can't find the input file\n");
       goto quit;
     }

if (Scribe||TeX||LaTeX||WStroff) out_ok = 0;

while (out_ok)
 {  if (out_file) 
    {
    printf("   **Output file name >");
    fscanf(stdin, "%s",outfile_name);
    fflush(stdin);
    }


    out_ok=0; 
   if ((outfile=fopen(outfile_name,"r"))!=NULL)
     { out_ok=1;
       out_file=1;
      fflush(stdin);
      printf(" File <%s> already exist, overwrite ? [N]", outfile_name);

     while((ch=fgetc(stdin))=='\n');

        if ((ch=='y')||(ch=='Y')) out_ok=0;
        fclose(outfile);

     }

    if (out_ok==0)
       {
	outfile=fopen(outfile_name,"w");
       }
  }



if (Scribe||TeX||LaTeX)
 { i = 0;
  while ((infile_name[i] != '.')&&(i < strlen(infile_name)))
  	{string[i] = infile_name[i]; i++;}
  string[i] ='\0';

if (!TexT)
	{
		sprintf(outfile_name, "%s.hdr", string);
		initialize();
		Sort_Fonts();
		if (chinese_used>0) 
		{
         if ((outfile=fopen(outfile_name,"r"))!=NULL)
            { fclose(outfile);
             fflush(stdin);
      fprintf(stderr,"Font header file <%s> already exists, rebuild? [Y]", outfile_name);

             while((ch=fgetc(stdin))=='\n');

        if ((ch=='n')||(ch=='N'))
                return(-1); 

            }

   outfile=fopen(outfile_name,"w");

		build_chfonts(argv[0]);
		fclose(outfile);
		}
 	}

}


if (Scribe)
{
  sprintf(tempfile, "%s.ChS", string);
  sprintf(logfile_name, "%s.err", string);

if (!TexT)
{
   Scribe_preprocessor();

#if VMS
	outfile=fopen("chscribe.com", "w");

  fprintf(outfile, "$scribe %s/dev: postscript\n\
$append %s.ps %s.hdr\n\
$ren %s.hdr %s.ps\n",tempfile, string, string, string, string);
fclose(outfile);
  system("@chscribe.com");

#endif

#if unix
  sprintf(inbuffer, "scribe %s -dev postscript", tempfile);
  system(inbuffer);
  strcpy(inbuffer, "");
  sprintf(inbuffer, "cat %s.hdr %s.ps>%s.lps", string, string, string);
  system(inbuffer);
  strcpy(inbuffer, "");
  sprintf(inbuffer, "mv %s.lps %s.ps", string, string);
  system(inbuffer);
#endif
goto quit;

  }
 else
  {
   Scribe_preprocessor1();
  sprintf(inbuffer, "scribe %s", tempfile);
  system(inbuffer);
goto quit;

  }
 }

if (TeX)
{
  sprintf(tempfile, "%s.chtex", string);
  sprintf(logfile_name, "%s.err", string);
if (TexT)
   TeX_preprocessor1();
   else
   TeX_preprocessor();
   fclose(outfile);
  fprintf(stderr, "%s has been created for you to TeX.\n", tempfile);

goto quit;
 }

 if (WStroff)
{
 		initialize();
		Sort_Fonts(); 
 i = 0;
 while ((infile_name[i] != '.')&&(i < strlen(infile_name)))
  	{string[i] = infile_name[i]; i++;}
  string[i] ='\0';
  sprintf(tempfile, "%s.ps", string);
  sprintf(logfile_name, "%s.err", string);

  outfile = fopen(tempfile, "w"); /* open the output file */

  if (chinese_used>0) build_chfonts("ch->ps by JBW");
  else
  fputs("%!PS-Adobe-2.0\n\
%% Creator ch->ps\n",outfile);

  WS_troff();

  goto quit;
}
if (Encode)
   ccdos_encode();

if (Decode)
   ccdos_decode();



quit:;

/*
fprintf(stderr, "\n\t>>> Thank you for using ChScribe >>>\n");
fprintf(stderr, "\t>>> by Jingbai Wang, August 1989 >>>\n");
*/

}

#if MSDOS|PCDOS
FILE *cclib;
#endif


open_cclib(mode)
int mode;
{
char *cclibfile;
int cclibhd;

  if (mode == 3) /* final version use 48x48 fonts */
  {
#if unix|VMS
#if unix

   if (jt3==1) 
   	{if (!(cclibfile = getenv("CCLIB48jt")))
		 cclibfile = CCLIB48jt;
	}
   else  
   	{if (!(cclibfile = getenv("CCLIB48ft")))
		 cclibfile = CCLIB48ft;
	}

   if (( cclibhd = open(cclibfile, O_RDONLY) )< 0)
    {warning("Can't find the CCLIB file"); exit(-1);}

#endif


#if VMS

 if (jt3==1){
		if (( cclibhd = open("cclib48$jt", O_RDONLY) )< 0)
		{ cclibfile = CCLIB48jt;
		if (( cclibhd = open(cclibfile, O_RDONLY) )< 0)
		{warning("Can't find the CCLIB file"); exit(-1);}
		}
      	    }
	    else
	    {
		if (( cclibhd = open("cclib48$ft", O_RDONLY) )< 0)
		{ cclibfile = CCLIB48jt;
		if (( cclibhd = open(cclibfile, O_RDONLY) )< 0)
		{warning("Can't find the CCLIB file"); exit(-1);}
		}

      	    }

#endif
#else

#if MSDOS|PCDOS   /* DOS system */
	cclibfile = getenv("CCLIB48");
	if (jt3==1) strcat(cclibfile, "\\cclib.48");
	else  strcat(cclibfile, "\\cclibft.48");

	if ((cclib = fopen(cclibfile, "rb"))==NULL)
	{
	if (jt3==1) cclibfile = CCLIB48jt;
	else  cclibfile = CCLIB48ft;	
	if ((cclib = fopen(cclibfile, "rb"))==NULL)
	{warning("Can't find the CCLIB file"); exit(-1);}
  	}
#else
	if (jt3==1) cclibfile = CCLIB48jt;
	else  cclibfile = CCLIB48ft;
   if (( cclibhd = open(cclibfile, O_RDONLY) )< 0)
    {warning("Can't find the CCLIB file"); exit(-1);}
#endif
#endif
   }

 else if (mode==1)/* draft version use 16x16 fonts */
  {
#if unix|VMS
#if unix

   if (jt3==1) 
   	{if (!(cclibfile = getenv("CCLIB16jt")))
		 cclibfile = CCLIB16jt;
	}
   else  
   	{if (!(cclibfile = getenv("CCLIB16ft")))
		 cclibfile = CCLIB16ft;
	}

   if (( cclibhd = open(cclibfile, O_RDONLY) )< 0)
    {warning("Can't find the CCLIB file\n"); exit(-1);}

#endif


#if VMS

 if (jt3==1){
		if (( cclibhd = open("cclib16$jt", O_RDONLY) )< 0)
		{ cclibfile = CCLIB16jt;
		if (( cclibhd = open(cclibfile, O_RDONLY) )< 0)
		{warning("Can't find the CCLIB file"); exit(-1);}
		}
      	    }
	    else
	    {
		if (( cclibhd = open("cclib16$ft", O_RDONLY) )< 0)
		{ cclibfile = CCLIB16jt;
		if (( cclibhd = open(cclibfile, O_RDONLY) )< 0)
		{warning("Can't find the CCLIB file"); exit(-1);}
		}

      	    }

#endif
#else

#if MSDOS|PCDOS
	cclibfile = getenv("CCLIB16");
	if (jt3==1) strcat(cclibfile, "\\cclib.16");
	else  strcat(cclibfile, "\\cclibft.16");
	if ((cclib = fopen(cclibfile, "rb"))==NULL)
	{
	if (jt3==1) cclibfile = CCLIB16jt;
	else  cclibfile = CCLIB16ft;	
	if ((cclib = fopen(cclibfile, "rb"))==NULL)
	{fprintf(stderr, "Can't find the CCLIB file %s", cclibfile); exit(-1);}
  	}
#else
	if (jt3==1) cclibfile = CCLIB16jt;
	else  cclibfile = CCLIB16ft;

   if (( cclibhd = open(cclibfile, O_RDONLY) )< 0)
    {warning("Can't find the CCLIB file"); exit(-1);}

#endif

#endif
   }
 else /* regular version use 24x24 fonts */
  {
#if unix|VMS
#if unix

   if (jt3==1) 
   	{if (!(cclibfile = getenv("CCLIB24jt")))
		 cclibfile = CCLIB24jt;
	}
   else  
   	{if (!(cclibfile = getenv("CCLIB24ft")))
		 cclibfile = CCLIB24ft;
	}

   if (( cclibhd = open(cclibfile, O_RDONLY) )< 0)
    {warning("Can't find the CCLIB file\n"); exit(-1);}

#endif


#if VMS

 if (jt3==1){
		if (( cclibhd = open("cclib24$jt", O_RDONLY) )< 0)
		{ cclibfile = CCLIB24jt;
		if (( cclibhd = open(cclibfile, O_RDONLY) )< 0)
		{warning("Can't find the CCLIB file"); exit(-1);}
		}
      	    }
	    else
	    {
		if (( cclibhd = open("cclib24$ft", O_RDONLY) )< 0)
		{ cclibfile = CCLIB24jt;
		if (( cclibhd = open(cclibfile, O_RDONLY) )< 0)
		{warning("Can't find the CCLIB file"); exit(-1);}
		}

      	    }

#endif
#else

#if MSDOS|PCDOS
	cclibfile = getenv("CCLIB24");
	if (jt3==1) strcat(cclibfile, "\\cclib.24");
	else  strcat(cclibfile, "\\cclibft.24");

	if ((cclib = fopen(cclibfile, "rb"))==NULL)
	{
	if (jt3==1) cclibfile = CCLIB24jt;
	else  cclibfile = CCLIB24ft;	
	if ((cclib = fopen(cclibfile, "rb"))==NULL)
	{warning("Can't find the CCLIB file"); exit(-1);}
  	}
#else
	if (jt3==1) cclibfile = CCLIB24jt;
	else  cclibfile = CCLIB24ft;

   if (( cclibhd = open(cclibfile, O_RDONLY) )< 0)
    {warning("Can't find the CCLIB file"); exit(-1);}
#endif

#endif
   }

 return(cclibhd);

}


build_chfonts(s)    /* Build PostScript fonts */
char *s;
{
char junk[288];
static int types[8] ={1,2,4,8,16,32,64,128};
auto short int matrix[2304], matrix1[48][48];
auto int byte1, byte2, byte3, byte4, byte5, byte6;
int cclibhd, bytes;
int word_size;
auto short int ASCII_bit[256][8];
 char tmpchar;
 int  tmpc;
 int i, group, chinese_sorted[MAX_CHAR], j;
 long int quwei_loc; 
 auto unsigned char cclib_array[MAX_USED*record_length];
 long int k;

     if (chinese_used==0) {

			fputs("No Chinese characters are used!\n", stderr);
			return(-1);
			}

	for(i=0; i<256; i++)
		for(j=7; j>=0; j--)
			ASCII_bit[i][j]=(i>>(7-j)) & 01 ;/*genarate ASCII table*/


fprintf(outfile, "%%!PS-Adobe-2.0\n\
%%%% Creator %s\n", s);

 /* Output some the PostScript definitions */

if (final_version)
fputs( "\
/dofont {\n\
10 dict dup begin\n\
/FontType 3 def	\n\
/FontBBox [0 0 0 0] def	\n\
/Encoding 252 array def\n\
31 1 251 {Encoding exch /.notdef put} for\n\
/BuildChar\n\
{ 0 begin\n\
	/char exch def\n\
	/fontdict exch def\n\
	/charname fontdict /Encoding get char get def\n\
	\n\
	/charinfo fontdict /CharData get charname\n\
	 get def\n\
	/wx charinfo 0 get def\n\
	/charbbox charinfo 1 4 getinterval def\n\
	wx 0 charbbox aload pop setcachedevice	\n\
	charinfo 5 get charinfo 6 get true\n\
	\n\
	fontdict /imagemaskmatrix get\n\
	  dup 4 charinfo 7 get put\n\
	  dup 5 charinfo 8 get put\n\
	  dup 0 charinfo 9 get put\n\
	  dup 3 charinfo 9 get neg put\n\
	charinfo 10 1 getinterval cvx\n\
	imagemask\n\
end\n\
} def\n\
\n\
/BuildChar load 0 6 dict put\n\
} def\n", outfile);
else 
fputs( "\
/dofont {\n\
9 dict dup begin\n\
/FontType 3 def	\n\
/FontBBox [0 0 0 0] def	\n\
/Encoding 252 array def\n\
31 1 251 {Encoding exch /.notdef put} for\n\
/BuildChar\n\
{ 0 begin\n\
	/char exch def\n\
	/fontdict exch def\n\
	/charname fontdict /Encoding get char get def\n\
	\n\
	/charinfo fontdict /CharData get charname\n\
	 get def\n\
	/wx charinfo 0 get def\n\
	/charbbox charinfo 1 4 getinterval def\n\
	wx 0 charbbox aload pop setcachedevice	\n\
	charinfo 5 get charinfo 6 get true\n\
	\n\
	fontdict /imagemaskmatrix get\n\
	  dup 4 charinfo 7 get put\n\
	  dup 5 charinfo 8 get put\n\
	charinfo 9 1 getinterval cvx\n\
	imagemask\n\
end\n\
} def\n\
\n\
/BuildChar load 0 6 dict put\n\
} def\n", outfile);

 
  /* now open the font file */

 if (draft_version)
 { /* 16x16 fonts */
   word_size = 32;
   rec_len = 32;
   cclibhd = open_cclib(1);
 }
 else if (final_version)
 { /* 48 x 48 fonts*/
  word_size = 288;
   cclibhd = open_cclib(3);
 }
 else 
 { /* 24 x 24 fonts*/
  word_size = 72;
  rec_len = 72;
   cclibhd = open_cclib(2);
 }

  group=0;

fputs("Building Chinese Fonts ... \n", stderr);


#if MSDOS|PCDOS
for (i=0; i<= max_quwei; i++)
	if(chinese[i]) chinese_sorted[chinese[i]] = i; 
word_size = 0;
#else
/* load the font information into an array */

for (i=0; i<= max_quwei; i++)
  { /* begin for */

    if(final_version)
       {
	if (i<1128) rec_len = 72;  /*12 symbol sections use 24x24 bitmap */
	else if (i>=1410) rec_len = 288;  /* otherwise use 48x48 bitmap */
	else goto next_for;
       }

    if(draft_version)
       {
	if (i>657&&i<1410)  /*8 missing symbol sections */
	 goto next_for;
       }
      
    if (!chinese[i]) 
    	{
#if VMS
	 bytes = read(cclibhd, junk, rec_len);
	 if (bytes<rec_len)
	 	for(j=0; j<rec_len-bytes; j++) read(cclibhd, &junk[0], 1);

#else
	 bytes = read(cclibhd, junk, rec_len);
#endif
	}
         else
	{
		/* sort out the characters in sequence of occurrence */
		chinese_sorted[chinese[i]] = i; 
#if VMS
	 bytes = read(cclibhd, &cclib_array[chinese[i]*word_size],
	 rec_len);		
	 if (bytes<rec_len)
	 	for(j=0; j<rec_len-bytes; j++)
		read(cclibhd, 
		&cclib_array[bytes+j+chinese[i]*word_size], 1);
#else
	 bytes = read(cclibhd, &cclib_array[chinese[i]*word_size],
	 rec_len);		
#endif
        }
	next_for:;
  }

close(cclibhd);
#endif

begin_dofont(outfile);


  for (i=0; i<=chinese_used; i++)
   { /* Start to build bitmap font in PostScript */

     if (((i%font_group_size)==0)&&(i>0))
      {
       end_dofont(group);
       ++group;
       begin_dofont(outfile);
     }
    tmpc = i-font_group_size*group+1 + font_overhead;
    if (tmpc > 126) tmpc ++;

    if(final_version)
       {
	if (chinese_sorted[i]<1410) rec_len = 72;
	else rec_len = 288;
       }

#if MSDOS|PCDOS
  if (final_version) /* figure out the offset */
  	{
	if (chinese_sorted[i]<1128) {k = (long int) (72*chinese_sorted[i]);
	fseek(cclib, (long int)(k*72), 0);
			}
	else if (chinese_sorted[i]>=1410) {
		k = (long int) (chinese_sorted[i] - 12*94);
		fseek(cclib, (long int)(k*288), 0);
		}
	else {k = 0;
		fseek(cclib, 0L, 0);
	}

	fread(cclib_array, (unsigned int) rec_len, (unsigned)1, cclib);

	}
  else if (draft_version)
  	{
	if (chinese_sorted[i]>=1410)  /*8 missing symbol sections */
		k = (long int) (chinese_sorted[i]-752);
		else k = (long int) (chinese_sorted[i]);
	fseek(cclib, (long int)(k*32), 0);
	fread(cclib_array, (unsigned)rec_len, (unsigned)1, cclib);
	}
  else  
  	{
	k = (long int) chinese_sorted[i];
	fseek(cclib, (long int)(k*72), 0);
	fread(cclib_array, (unsigned)rec_len, (unsigned)1, cclib);

 	}
#endif

if (rec_len == 32) /* 16x16 fonts */
  {
      fprintf(outfile, "\n/ch%d [16 1 0 16 15 16 16 0.5 15.5 <",tmpc);
       
    if(sideway) /* rotate the font */
       {

 	 for (k=0; k<32; k++)
  	  for(j=0; j<8; j++)
      		matrix[k*8 + j] = ASCII_bit[cclib_array[k+i*word_size]][j];

    	for (j=0; j<16; j++)
     	  for (k=0; k<16; k++)
        	matrix1[j][k] = matrix[15-j+k*16];

    	 for (j=0; j<16; j++)
        	{ byte1=byte2=0;
         	 for(k=0; k<8; k++)
           	{
          	byte1 += matrix1[j][7-k]*types[k];
           	byte2 += matrix1[j][15-k]*types[k];
           	}
          fprintf(outfile, "%02x%02x", byte1, byte2);

         }

       }
   else{
        for (j=0; j<32; j++)
          fprintf(outfile, "%02x", cclib_array[i*word_size+j]);
        }

      fputs(">] def", outfile);
  }
else if (rec_len==288)
 {  /* 48x48 */ 
  
      fprintf(outfile, "\n/ch%d [24 1 0 48 47 48 48 0.5 47.5 2 <",tmpc);
       
    if(sideway) /* rotate the font */
       {

  	for (k=0; k<rec_len; k++)
   	 for(j=0; j<8; j++)
      		matrix[k*8 + j] = ASCII_bit[cclib_array[k+i*word_size]][j];

    	for (j=0; j<48; j++)
     	 for (k=0; k<48; k++)
        	matrix1[j][k] = matrix[47-j+k*48];

     	for (j=0; j<48; j++)
        { byte1=byte2=byte3=byte4=byte5=byte6=0;
          for(k=0; k<8; k++)
           {
           byte1 += matrix1[j][7-k]*types[k];
           byte2 += matrix1[j][15-k]*types[k];
           byte3 += matrix1[j][23-k]*types[k];
           byte4 += matrix1[j][31-k]*types[k];
           byte5 += matrix1[j][39-k]*types[k];
           byte6 += matrix1[j][47-k]*types[k];
           }
          fprintf(outfile, "%02x%02x%02x%02x%02x%02x",
	  byte1, bytes, byte3, byte4, byte5, byte6);

         }

       }
   else{
        for (j=0; j<288; j++)
          fprintf(outfile, "%02x", cclib_array[i*word_size+j]);
        }

      fputs(">] def", outfile);

  }
  else /* 24x 24 fonts*/
  {
 	if (final_version)
      fprintf(outfile, "\n/ch%d [24 1 0 24 23 24 24 0.5 23.5 1 <",tmpc);
      else
      fprintf(outfile, "\n/ch%d [24 1 0 24 23 24 24 0.5 23.5 <",tmpc);
       
    if(sideway) /* rotate the font */
       {

 	 for (k=0; k<72; k++)
  	  for(j=0; j<8; j++)
      		matrix[k*8 + j] = ASCII_bit[cclib_array[k+i*word_size]][j];

    	for (j=0; j<24; j++)
     	  for (k=0; k<24; k++)
        	matrix1[j][k] = matrix[23-j+k*24];

    	 for (j=0; j<24; j++)
        	{ byte1=byte2=byte3=0;
         	 for(k=0; k<8; k++)
           	{
          	byte1 += matrix1[j][7-k]*types[k];
           	byte2 += matrix1[j][15-k]*types[k];
           	byte3 += matrix1[j][23-k]*types[k];
           	}
          fprintf(outfile, "%02x%02x%02x", byte1, byte2, byte3);

         }

       }
   else{
        for (j=0; j<72; j++)
          fprintf(outfile, "%02x", cclib_array[i*word_size+j]);
        }

      fputs(">] def", outfile);
  }


     if (i==chinese_used)
      {
       end_dofont(group);
      }
  }
#if MSDOS|PCDOS
fclose(cclib);
#endif
 return(-1);
}


warning(s)
char *s;
{
fprintf(stderr, "%s", s);
}


int Part_ASCII_Ch(inchr)
char inchr;
{
  switch(inchr)
   {
     case ',':
     case '!':
     case '.':
     case ';':
     case '?':
/*
     case '/':
     case '[':
     case ']':
     case '(':
     case ')':
     case '{':
     case '}':
     case '<':
     case '>':
     case '\'':
     case '~':
     case '|':
     case '\\':
     case  ':':
     case '&':
     case '%':
     case '^':
     case '#':
*/

     		return(155+inchr);
     default: return(-1);

   }

}


int All_Ch(inchr)
char inchr;
{
     if ((inchr>32)&&(inchr<127)) 
        return(155+inchr);
     else return(0);

}


ccdos_encode() /* Shift all charaters < 32 by adding 32
                 and those > 160 by substracting 128 */ 
               /* escape codes:
                 \h@  -- begin characters > 128
                 \l@  -- begin characters < 32
                 \s@  --  126< WordStar characters <161 
                 \c@  --  continue line
               */
{
int bh, i, ws, bl, line_length;
   bh = 0;
   bl = 0;
   ws = 0;
   line_length = 0;

  while( fgets(inbuffer, 1024, infile) != NULL)
 {

   for (i=0; i<strlen(inbuffer); i++)
 {   

  switch(inbuffer[i])
   {

    case 13:
    case 10: line_length = 0; 
    case 12:            
    case 9:
           if (line_length>75)
            {
               fprintf(outfile, "\\c@\n");
               line_length=0;
            }

            fprintf(outfile, "%c", inbuffer[i]); line_length ++; break;
    case 32:
           if (line_length>75)
            {
               fprintf(outfile, "\\c@\n");
               line_length=0;
            }
             fprintf(outfile, " "); line_length ++; break;

    default:
     if ((inbuffer[i] > 160) && (inbuffer[i] < 255))
         { bl = 0;
           ws = 0;
          if (!bh) 
             {
              if (line_length>75)
               {
               fprintf(outfile, "\\c@\n");
               line_length=0;
                }
               fprintf(outfile, "\\h@");
               line_length +=5;
               bh = 1;
             }
           if (line_length>75)
            {
               fprintf(outfile, "\\c@\n");
               line_length=0;
            }

                inbuffer[i] -= 128;
                fprintf(outfile, "%c", inbuffer[i]);
                line_length ++;
                break;
         }
      else if (inbuffer[i]>126) /* Probably the WordStar stuff */
         { 
           bl = 0;
           bh = 0;
          if (!ws) 
             {
              if (line_length>75)
               {
               fprintf(outfile, "\\c@\n");
               line_length=0;
                }
               fprintf(outfile, "\\s@");
               line_length +=3;
               ws = 1;
             }
           if (line_length>75)
            {
               fprintf(outfile, "\\c@\n");
               line_length=0;
            }

                inbuffer[i] -= 95;
                fprintf(outfile, "%c", inbuffer[i]);
                line_length ++;
                break;
         }
      else if (inbuffer[i]<32)
         {
          bh = 0;
          ws = 0;
          if (!bl) 
             {
              if (line_length>75)
               {
               fprintf(outfile, "\\c@\n");
               line_length=0;
                }
               fprintf(outfile, "\\l@");
               line_length +=5;
               bl = 1;
             }
           inbuffer[i] += 32;
           if (line_length>75)
            {
               fprintf(outfile, "\\c@\n");
               line_length=0;
            }
           fprintf(outfile, "%c", inbuffer[i]);
           line_length ++;
           break;
         }
       
      else 
         {

           if (bh||bl||ws)
            {  if (line_length>75)
               {
               fprintf(outfile, "\\c@\n");
               line_length=0;
                }
               fprintf(outfile, "\\e@");
               line_length +=5;
               bh = 0;
               bl = 0;
               ws = 0;
             }

           if (line_length>75)
            {
               fprintf(outfile, "\\c@\n");
               line_length=0;
            }
           fprintf(outfile, "%c", inbuffer[i]);
           line_length ++;

         }

   }
  }
 }

fclose(infile);
fclose(outfile);

}


ccdos_decode() /* Shift all the bytes back to original */
{
int bh, bl, i, line_length, shift;
   shift = 0;


  while( fgets(inbuffer, 1024, infile) != NULL)
 {

   for (i=0; i<strlen(inbuffer); i++)
 {   
    switch(inbuffer[i])
   {
    case 9:  
    case 32: 
    case 12: 
    case 13:
    case 10:
              fprintf(outfile, "%c", inbuffer[i]); break;
    case '\\':
             if (strncmp(&inbuffer[i+1], "h@", 2) == 0)
                { shift = 128;
                  i += 2; break;
                }
              else if (strncmp(&inbuffer[i+1], "l@", 2) == 0)
                { shift = -32;
                  i += 2; break;
                }
              else if (strncmp(&inbuffer[i+1], "e@", 2) == 0)
                { shift = 0;
                  i += 2; break;
                }
              else if (strncmp(&inbuffer[i+1], "w@", 2) == 0)
                { fprintf(outfile, "%c", 138);
                  i += 3; break;
                }
              else if (strncmp(&inbuffer[i+1], "s@", 2) == 0)
                { shift = 95;
                  i += 2; break;
                }
              else if (strncmp(&inbuffer[i+1], "c@", 2) == 0)
                {
                  i += 3; break;
                }
              else 
                { inbuffer[i] += shift;
                   fprintf(outfile, "%c", inbuffer[i]);
                }

           break;
    default:
           inbuffer[i] += shift;
           fprintf(outfile, "%c", inbuffer[i]);

   }
  }
 }

fclose(infile);
fclose(outfile);


}
