#! /bin/sh

dirs=.:lib:src:doc:sample

cat >sjistoeuc.c <<EOF
/* SJIS to EUC-Japan */
#include <stdio.h>

#define issjis(c) ((0x81 <= (c) && (c) <= 0x9f) || (0xe0 <= (c) && (c) <= 0xfc))
#define iskana(c) (0xa1 <= (c) && (c) <= 0xdf)
#define SS2 0x8e

static int
sjis2euc (ubyte, lbyte)
     int ubyte;
     int lbyte;
{
  unsigned int ub;
  unsigned int lb;

  ub = ubyte;
  lb = lbyte;
  if (lb >= 0x9f) {
    ubyte = ub * 2 - (ub >= 0xe0 ? 0xe0 : 0x60);
    lbyte = lb + 2;
  } else {
    ubyte = ub * 2 - (ub >= 0xe0 ? 0xe1 : 0x61);
    lbyte = lb + (lb >= 0x7f ? 0x60 : 0x61);
  }

  return (ubyte << 8) + lbyte;  
}

static int
putchar_euc (c)
     int c;
{
  static int ch = 0;

  if (ch)
    {
      int wc;
      wc = sjis2euc(ch, c);
      if (putchar((wc >> 8) & 0377) == EOF || putchar(wc & 0377) == EOF)
	return EOF;
      ch = 0;
    }
  else if (issjis(c))
    ch = c;
  else
    {
      if (iskana(c) && putchar(SS2) == EOF)
	return EOF;
      if (putchar(c) == EOF)
	return EOF;
    }

  return 0;
}

main (argc, argv)
     int argc;
     char **argv;
{
  int c;

  while ((c = getchar()) != EOF)
    if (putchar_euc(c) == EOF)
      exit(1);

  exit(0);
}
/*
 * End:
 */
EOF

if eval "${CC-cc} -g -o sjistoeuc sjistoeuc.c >/dev/null 2>&1"; then
  rm sjistoeuc.c
else
  rm sjistoeuc.c sjistoeuc
  exit 1
fi

trap 'rm -f sjistoeuc; exit 1' 1 2 15

IFS="${IFS= 	}"; save_ifs="$IFS"; IFS="${IFS}:"
for dir in $dirs; do
  if test -r $dir/.convfiles; then
    for file in `cat $dir/.convfiles`; do
      if test -f $dir/${file}.sjis; then
        :
      else
        test -f $dir/$file &&
        mv -f $dir/$file $dir/${file}.sjis &&
        ./sjistoeuc < $dir/${file}.sjis > $dir/$file
      fi      
    done
  fi
done
IFS="$save_ifs"

rm sjistoeuc

exit 0
