#! /usr/bin/perl

## @file
##
## $Id: cedict2kvtml.pl,v 1.1 2005/05/18 12:34:52 marc Exp $
##
## $Date: 2005/05/18 12:34:52 $
## $Author: marc $
##
## @copy &copy; Marc W&auml;ckerlin
## @license LGPL, see file <a href="license.html">COPYING</a>
##
## This program reads an UTF-8 CEDICT file from
## http://www.mandarintools.com/cedict.html on STDIN and writes a
## KVTML XML file for use e.g. in Linux KDE KWordQuiz to STDOUT.
##
## $Log: cedict2kvtml.pl,v $
## Revision 1.1  2005/05/18 12:34:52  marc
## initial release
##
##
##       1         2         3         4         5         6         7         8
## 45678901234567890123456789012345678901234567890123456789012345678901234567890

print '<?xml version="1.0"?>
<!DOCTYPE kvtml SYSTEM "kvoctrain.dtd">
<kvtml
    encoding="UTF-8"
    generator="xedict2kvtml.pl"
    title="中英辞典 CEDICT"
    author="http://www.mandarintools.com/cedict.html">
  <lesson>
    <desc no="1">中英辞典 CEDICT</desc>
  </lesson>
';
%pymap = (
          'a1' => 'ā',
          'a2' => 'á',
          'a3' => 'ǎ',
          'a4' => 'à',
          'a5' => 'a',
          'e1' => 'ē',
          'e2' => 'é',
          'e3' => 'ě',
          'e4' => 'è',
          'e5' => 'e',
          'i1' => 'ī',
          'i2' => 'í',
          'i3' => 'ǐ',
          'i4' => 'ì',
          'i5' => 'i',
          'o1' => 'ō',
          'o2' => 'ó',
          'o3' => 'ǒ',
          'o4' => 'ò',
          'o5' => 'o',
          'u1' => 'ū',
          'u2' => 'ú',
          'u3' => 'ǔ',
          'u4' => 'ù',
          'u5' => 'u',
          'ü1' => 'ǖ',
          'ü2' => 'ǘ',
          'ü3' => 'ǚ',
          'ü4' => 'ǜ',
          'ü5' => 'ü',
         );
while (<>) {
  s/&/&amp;/g;
  s/</&lt;/g;
  s/>/&gt;/g;
  if (/^\s*(\S+) (\S+) \[(\w*)\] \/(.+)\/\s*$/) {
    my ($traditional, $simplified, $pinyin, @english) =
      ($1, $2, $3, split(/\//, $4));
    if ($pinyin =~ m/([^aeiouü]*)([aeiouü])(\D*)(\d)/) {
      $pinyin = $1.$pymap{$2.$4}.$3;
    }
    print '
  <e m="1" s="1">
    <o l="中文" p="'.$pinyin.'">'.$simplified.($simplified ne $traditional ? " ($traditional)":"").'</o>
    <t l="English" p="'.$pinyin.'">['.$pinyin.'] '.join('; ', @english).'</t>
  </e>
    ';
  }
}
print ''.$pinyin.'
</kvtml>
';
