#
#	$Date: 2001/02/04 13:33:12 $
#	$Revision: 1.10 $
#
package romakana;

sub main'kana2roma {
	local($s) = @_;
	local(@result);
	unless(defined(%kr)){
		print STDERR "kana-roma table not defined\n";
	}
	@result = ();
	&krexpand('',$s);
	join(',',@result);
}

sub krexpand {
	local($a,$b,$t) = @_;
	local($k,$k1,$r,$c,$rs,$rs1);
#print "kreexpand($a,$b,$t)\n";

	if($t){ # 「ッ」の処理
		if($b eq ''){
			for $r (split(/,/,$kr{$str_tsu})){
				push(@result,$a.$r);
			}
		}
		if(($k,$c) = ($b =~ /^(....)(.*)$/)){
			if($kr{$k}){
				$rs = $kr{$k};
				for $r (split(/,/,$kr{$k})){
					$kr{$k} = $r;
					if($r =~ /^([bcdfghjklmpqrstvwxyz])/){
						&krexpand($a.$1.$r,$c);
					}
				}
				$kr{$k} = $rs;
			}
		}
		if(($k,$c) = ($b =~ /^(..)(.*)$/)){
			if($kr{$k}){
				$rs = $kr{$k};
				for $r (split(/,/,$kr{$k})){
					$kr{$k} = $r;
					if($r =~ /^([bcdfghjklmpqrstvwxyz])/){
						&krexpand($a.$1.$r,$c);
					}
				}
				$kr{$k} = $rs;
			}
		}
		return;
	}

	if($b eq ''){
		1 while $a =~ s/n'([bcdfghjklmnpqrstvwxz])/n\1/;
		$a =~ s/n'$/n/;
		push(@result,$a);
	}
	else {
		if(($k,$k1) = ($b =~ /^([a-z])(.*)$/)){
			&krexpand($a.$k,$k1);
			return;
		}

#print "kr(キ) = ",$kr{'キ'},"\n";
		if(($k,$k1,$c) = ($b =~ /^((..)..)(.*)$/)){
			if($kr{$k}){
#print " {{ kr(キ) = ",$kr{'キ'},"\n";
				$rs1 = $kr{$k1};
#	??????			undef $kr{$k1};
				$rs = $kr{$k};
				for $r (split(/,/,$kr{$k})){
#print "r = ($r)\n";
					$kr{$k} = $r;
					&krexpand($a.$r,$c);
				}
				$kr{$k} = $rs;
				$kr{$k1} = $rs1;
#print " }} kr(キ) = ",$kr{'キ'},"\n";
			}
		}
		if(($k,$c) = ($b =~ /^(..)(.*)$/)){
#print "--\n";
			$rs = $kr{$k};
			if($k eq $str_tsu){ # 'ッ'
#				&krexpand($a.$r,$c,1);
				&krexpand($a,$c,1);
			}
			elsif($kr{$k}){
				for $r (split(/,/,$kr{$k})){
					$kr{$k} = $r;
					&krexpand($a.$r,$c);
				}
			}
			$kr{$k} = $rs;
		}
	}
}

sub main'roma2kana {
	local($_) = @_;
	local($k);
	unless(defined(%rk)){
		print STDERR "roma-kana table not defined\n";
	}
	$_ = "\L$_";
	while($_ ne ''){
		if(/^..../ && $rk{$&}){
			s/^....//;
			$k .= $rk{$&};
		}
		elsif(/^.../ && $rk{$&}){
			s/^...//;
			$k .= $rk{$&};
		}
		elsif(/^../ && $rk{$&}){
			s/^..//;
			$k .= $rk{$&};
		}
		elsif(/^./ && $rk{$&}){
			s/^.//;
			$k .= $rk{$&};
		}
		elsif(/^n(.)/ && ($1 =~ /[bcdfghjklmnpqrstvwxz]/)){
			s/^.//;
			$k .= $str_n;
		}
		elsif(/^([bcdfghjklmpqrstvwxyz])(.)/ && ($1 eq $2)){
			s/^.//;
			$k .= $str_tsu;
		}
		elsif(/^n$/){
			s/^.//;
			$k .= $str_n;
		}
		else {
			s/^.//;
		}
	}
	$k;
}

1;
