/* vi: set sw=4 ts=4: */
/*
 * KON2 - Kanji ON Console -
 * Copyright (C) 1992-1996 Takashi MANABE (manabe@papilio.tutics.tut.ac.jp)
 *
 * CCE - Console Chinese Environment -
 * Copyright (C) 1998-2003 Rui He (rhe@3eti.com)
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in the
 *    documentation and/or other materials provided with the distribution.
 *
 * THIS SOFTWARE IS PROVIDED BY TAKASHI MANABE ``AS IS'' AND ANY
 * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 * ARE DISCLAIMED.  IN NO EVENT SHALL THE TERRENCE R. LAMBERT BE LIABLE
 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
 * SUCH DAMAGE.
 * 
 */

#include	<stdio.h>
#include	<stdlib.h>
#include	<sys/types.h>
#include	<string.h>
#include	<unistd.h>

#include    <defs.h>
#include	<font.h>
#include    <safestring.h>

static u_char  *FontLoadBdf(FILE *fp, FontInfo *fi);
int CodingByRegistry(char *reg);

int main(int argc,char **argv)
{
  FILE *in, *out;
  u_char *font;
  u_int  font_size;
  FontInfo fi;

  if (argc != 3)
  {
    fprintf(stderr,"usage: %s  <input_name> <output_name>\n",argv[0]);
    return 1;
  }

  in = fopen(argv[1],"r");
  out = fopen(argv[2], "wb");
  if (in == NULL || out == NULL)
  {
     fprintf(stderr, "Can't open input or output file!\n");
     return 1;
  }

  font = FontLoadBdf(in, &fi);

  if (font != NULL)
  {
       printf("Font %s: Type=%d, Height=%d, Width=%d, FontWidthBytes=%d, FontBytes=%d TotalSize = %d\n\n",
           argv[2], fi.type, fi.height, fi.width, FONTWIDTHBYTES(fi.width), FONTBYTES(fi.width, fi.height), fi.size);

	   font_size = fi.size;
	   ConvertCPUToLE32(font_size, (unsigned char *)&fi.size); /* store it in little endian mode! */
       fwrite(&fi, sizeof(FontInfo), 1, out);
       fwrite(font, font_size, 1, out); 
  }
  else 
  {
      fprintf(stderr, "Error reading input file!\n");
  }

  fclose(in);
  fclose(out);

  return 0;
}

static u_char  *FontLoadBdf(FILE *fp, FontInfo *fi)
{
    char *fdata = NULL, line[256], *p, *w, reg[256];
    u_char ch, ch2;
    int num, width, high, i,j, code = 0, data, k;
    FontRegs *fReg;

    fReg = &fSRegs[0];
	memset(fi, 0, sizeof(FontInfo));
    fi->type = CodingByRegistry("ISO8859-1");
    num = width = high = 0;

    while(fgets(line, 256, fp)) 
    {

        if (!width && !high &&
            !strncmp("FONTBOUNDINGBOX", line, strlen("FONTBOUNDINGBOX"))) 
		{
            p = line + sizeof("FONTBOUNDINGBOX");
            sscanf(p, "%d %d", &width, &high);
        } 

		else if (!strncmp("CHARSET_REGISTRY", line, 16)) 
		{
            w = strchr(line+sizeof ("CHARSET_REGISTRY"), '"');
            if (w==NULL)  buffer_error("bdf2bin_FontLoadBdf(1)");
            p = strchr(++w, '"');
            if (p==NULL)  buffer_error("bdf2bin_FontLoadBdf(2)");
            *p = '\0';

            safe_strncpy(reg, w, sizeof (reg));
	
	#if 0
            p = line + sizeof("CHARSET_REGISTRY");
            while(*p != '"') p++;
            w = ++p;
            while(*p != '"') p++;
            *p = '\0';
            strcpy(reg, w);    /* CHARSET_REGISTRY "ISO8859" */
	#endif
        } 

		else if (!strncmp("CHARSET_ENCODING", line, 16)) 
		{
#if 0
            p = line + sizeof("CHARSET_ENCODING");
            while(*p != '"') p ++;
            w = ++p;
            while(*p != '"') p ++;
            *p = '\0';
            strcat(reg, "-");
            strcat(reg, w);
#endif
            w = strchr(line+sizeof ("CHARSET_ENCODING"), '"');
            if (w==NULL)  buffer_error("bdf2bin_FontLoadBdf(3)");
            p = strchr(++w, '"');
            if (p==NULL)  buffer_error("bdf2bin_FontLoadBdf(4)");
            *p = '\0';
        	if (strlen(reg) + 1 + strlen(w) + 1 < sizeof(reg)) 
			{
        		strcat(reg, "-");
        		strcat(reg, w);
        	} 
			else buffer_error("bdf2bin_FontLoadBdf(5)");

			printf("Registry is %s\n", reg);

            fi->type = CodingByRegistry(reg);

#ifdef DEBUG
			fprintf(stderr, "Registry is %s, sizeof(fi) is %d, fi->type=0x%x\n", reg, sizeof(*fi), fi->type);
#endif
        } 

		else if (!num && !strncmp("CHARS ", line, 6)) 
		{
            p = line + sizeof("CHARS");
            sscanf(p, "%d", &num);
            break;   /* Stop Here, the following are char bitmaps */
        }
    }

    fi->width = width;
    fi->height = high;

    if (fi->type & CHR_DBC)   /*double charset */
    {
        fReg = &fDRegs[fi->type & ~CHR_DFLD];
		fontbytes2 = FONTBYTES(width, high);  /* fontbytes2 is defined in font.c, used in addr */
        if (fReg->max)
		{
            fi->size = fReg->addr(fReg->max >> 8, fReg->max & 0xFF) + fontbytes2;
		}
        else fi->size = fontbytes2 * num ; 
    } 
    else  /* non-double charset */
    {
        fReg = &fSRegs[fi->type & ~CHR_SFLD];
		fontbytes = FONTBYTES(width, high);  /* fontbytes is defined in font.c */
        if (fReg->max)
			fi->size = (fReg->max + 1 ) * fontbytes;  /* 12 * 24, 48 bytes */
        else fi->size = num * fontbytes;
    }

#ifdef DEBUG
#endif

    if ((fdata = (u_char *)malloc(fi->size)) == NULL) 
	return(NULL);
    k = 0;

    while(fgets(line, 256, fp)) 
    {
        if (!strncmp("ENCODING", line, strlen("ENCODING"))) 
		{
            p = line + sizeof("ENCODING");
            code = atoi(p);
        } 
		else if (!strncmp("BITMAP", line, strlen("BITMAP"))) 
		{
            k ++;
	
#ifdef BDFCAT
            fprintf(stderr,"----- %X -----\n", code);
#endif

            if (!(fi->type & CHR_DBC)) 
	    	{
				
            	p = fdata + code * fontbytes;  /* 12 * 24, 48 bytes, 8x16, 16 bytes */

                for (i = 0; i < fi->height; i++)
                {
					for(j = 0; j < FONTWIDTHBYTES(width); j++)
					{
                    	fscanf(fp, "%2X", &data);
#ifdef BDFCAT
                    	for (n = 0; (n < 8) && (n < width - 8*j); n ++)
                        	fprintf(stderr,"%c", ((data << n) & 0x80) ? '#':' ');
#endif
                    	*p++ = (data & 0xFF);
					}
#ifdef BDFCAT
                    fprintf(stderr,"\n");
#endif
                }
            } 
	    	else  /* double charset */
	    	{
                ch = (code >> 8) & 0xFF;
                ch2 = code & 0xFF;
                num = fReg->addr(ch, ch2);  /* using fontbytes2 */

                p = fdata + num;
                for (i = 0; i < fi->height; i++) 
				{

                    for(j = 0; j < FONTWIDTHBYTES(width); j++)
                    {
                        fscanf(fp, "%2X", &data);
#ifdef BDFCAT
                        for (n = 0; (n < 8) && (n < width - 8*j); n ++)
                            fprintf(stderr,"%c", ((data << n) & 0x80) ? '#':' ');
#endif
                        *p++ = (data & 0xFF);
                    }
#ifdef BDFCAT
                    fprintf(stderr,"\n");
#endif
                }
            }
        }
    }

    return(fdata);
}

