/*
 *	codes from COSMOS system
 *		Mar.1991	Yutaka Satou <ysato@etl.go.jp>
 */

#include <stdio.h>
#include "onew.h"

#define GOTO_NJIS	"\033$B"
#define GOTO_ASCII	"\033(B"

unsigned char *
ONEW_JIS_TO_SJIS1(HI,LO,SJCODE)
        register unsigned char HI,LO,*SJCODE;
{
        if( HI & 1 )
                LO += 0x1F;
        else    LO += 0x7D;
        if( 0x7F <= LO )
                LO++;

        HI = ((int)(HI - 0x21) >> 1) + 0x81;
        if( 0x9F < HI )
                HI += 0x40;
        SJCODE[0] = HI;
        SJCODE[1] = LO;
        return SJCODE;
}
unsigned char *
ONEW_SJIS_TO_JIS1(HI,LO,JCODE)
        register unsigned char HI,LO,*JCODE;
{
        HI -= (HI <= 0x9F) ? 0x71 : 0xB1;
        HI = (HI << 1) + 1;
        if( 0x7F < LO )
                LO--;
        if( 0x9E <= LO ){
                LO -= 0x7D;
                HI++;
        }else   LO -= 0x1F;
        JCODE[0] = HI;
        JCODE[1] = LO;
        return JCODE;
}
unsigned char *
ONEW_EUC_TO_SJIS(src,dst)
        unsigned char *src,*dst;
{       register unsigned char *sp,*dp;

        for(sp=src, dp=dst; *sp; ){
                if( *sp & 0x80 ){
                        if( sp[1] && (sp[1] & 0x80) ){
                                ONEW_JIS_TO_SJIS1(sp[0]&0x7F,sp[1]&0x7F,dp);
                                dp += 2; sp += 2;
                        }else   sp++;
                }else   *dp++ = *sp++;
        }
        *dp = 0;
        return dst;
}
unsigned char *
ONEW_SJIS_TO_EUC(src,dst)
        unsigned char *src,*dst;
{       register unsigned char *sp,*dp;

        for(sp=src, dp=dst; *sp; ){
                if( *sp & 0x80 ){
                        if( sp[1] && (sp[1] & 0x80) ){
                                ONEW_SJIS_TO_JIS1(sp[0],sp[1],dp);
                                dp += 2; sp += 2;
                        }else   sp++;
                }else   *dp++ = *sp++;
        }
        *dp = 0;
        return dst;
}
ONEW_EUC_TO_JIS_FILE(fp,src)
	FILE *fp;
	unsigned char *src;
{	int kana_mode = 0;
	register unsigned char *sp,ch;
	char ki[5],ko[5];

	strcpy(ki,GOTO_NJIS);
	strcpy(ko,GOTO_ASCII);
	for(sp = src; ch = *sp; sp++ ){
		if( ch & 0x80 ){
			if(!kana_mode){ kana_mode = 1; fputs(ki,fp); }
		}else{	if( kana_mode){ kana_mode = 0; fputs(ko,fp);} }
		putc(ch & 0x7F, fp);
	}
	if(kana_mode)
		fputs(ko,fp);
}
Onew_fprintf(fp,form,a,b,c,d,e,f)
	FILE *fp;
	char *form;
	char *a,*b,*c,*d,*e,*f;
{	Mssgbuff out;

	sprintf(out,form,a,b,c,d,e,f);
	ONEW_EUC_TO_JIS_FILE(fp,out);
	fflush(fp);
}


syntax highlighted by Code2HTML, v. 0.9.1