#!/bin/sh
# skk2cdb: convert SKK dictionary file to cdb
# Author: Tatsuya Kinoshita <tats@debian.org>
# Unlimited permission is granted to use, copy, distribute and/or modify
# this file.  There is NO WARRANTY.
set -e

if [ $# -gt 2 ]; then
    echo "usage: ${0##*/} [ SKK-JISYO [SKK-JISYO-CDB]]" >&2
    exit 1
fi

CDB="`command -v cdb`" || CDB=""
if [ -z "$CDB" ]; then
    echo "${0##*/}: tinycdb's cdb command not found" >&2
    exit 1
fi

INFILE="$1"
OUTFILE="$2"

if [ -z "$INFILE" ]; then
    INFILE=/dev/stdin
fi
if [ -z "$OUTFILE" ]; then
    OUTFILE=/dev/stdout
fi

trap 'rm -f "$TMPFILE" "$TMPFILE2"' EXIT INT TERM
TMPFILE=`mktemp`
TMPFILE2=`mktemp`

LC_ALL=C awk '
    /^[^;]/ {
	s = substr($0, index($0, " ") + 1)
	print "+" length($1) "," length(s) ":" $1 "->" s
    }
    END {
	print ""
    }
' "$INFILE" | "$CDB" -c -t "$TMPFILE" "$TMPFILE2"
cat "$TMPFILE2" > "$OUTFILE"

exit 0
