#!/bin/sh -e
# -*- mode: Shell-script; tab-width: 8; fill-column: 70; -*-
PROG="${0##*/}"
ALDCONV=/usr/bin/ALDConvert
SUBST=/usr/bin/subst
SED=/bin/sed

Fatal() {
  printf "$PROG: Fatal: %s\n" "$*" >&2
  exit 1
}

outdir="$1" && shift || Fatal "more argumets required"
target_document="$1" && shift 
params="$*"
create_document="$outdir/`basename $target_document .m-k`.html"

# Dirty hack for build m-k files in utf-8 encoding
enca -L ru -x koi8-r $target_document

$ALDCONV $target_document $create_document $params || Fatal "ALDConvert failed"

cat $create_document | fgrep charset | $SED 's/.*charset=\([^"]\+\)".*/\1/' | xargs -i iconv -c -f {} -t UTF-8 $create_document -o $create_document.utf || Fatal "iconv to UTF-8 failed"

$SUBST 's/charset=[^"]\+"/charset=UTF-8"/' $create_document.utf 
mv $create_document.utf $create_document

