#!/usr/bin/perl
#
# 中文點字版面重排程式
# 作者: 高生旺
# 版權: 公共版權(GPL)
#
$marg=32;
$j=1;
%brl=("a",2,"l",2,"o",2,"y",2,"1",0,"2",0,"3",2,"0",0,"`",0,"\"",0,";",0,
      "\'",0,",",2,"-",0," ",0,"\n",0,"\r",0);
%apt=(">",1,"<",1,"!",1,"w",1,"0",1,"%",1,"(",1,"u",1,":",1,"*",1,"/",1,")",1,"s",1,"+",1);
while(<@ARGV>) {
open(in,$_) || die "$_: $!\a\n";
$of="$_.brf";
open(out,">$of");
@src=<in>;
close(in);
for($k=0;$k<=$#src;$k++)
{
  $raw.=$src[$k];
}
for($i=0;$i<length $raw;$i++)
{
  $pos=substr($raw,$i,1);
  if(!exists $brl{$pos}){$brl{$pos}=1;}
  $aft=substr($raw,$i+1,1);
  if(!exists $brl{$aft}){$brl{$aft}=1;}
  if($pos eq "\r"){next;}
  if($pos eq "\n" && ($j>1 && $j<$marg))
  {
    if(($aft ne "\r") && ($aft ne "\n") && ($aft ne " "))
    {
      %ads=("-",1,"0",1);
      if(($brl{$trg[$#trg]} &&
        (($trg[$#trg] ne ",") &&
        !(($trg[$#trg] eq "a") && $apt{$trg[$#trg-1]}) &&
        ($trg[$#trg] ne "3"))) ||
        $ads{$trg[$#trg]} || (($trg[$#trg] eq "2") && ($trg[$#trg-1] eq "-")))
      {push @trg," ";$j++;}
      next;
    }
  }
  if($j==$marg && $pos eq " "){$pos="\n";}
  if($j>$marg)
  {
    until($pos eq "\n")
    {
      $bef=substr($raw,$i-1,1);
      if(($pos eq " ") || ($pos eq $bef && $pos eq $aft)){$pos="\n";$i--;last;}
      if((!$brl{$bef} && substr($raw,$i-2,1) ne " ") && ($bef ne "-" && substr($raw,$i-2,1) ne ";") || $bef eq "3" || ($bef eq "a" && $apt{substr($raw,$i-2,1)}) || ($bef eq "," && substr($raw,$i-2,1) ne " "))
      {
        if($brl{$pos}==1 || ($pos eq ";" && $aft eq "-") || ($pos eq "\"" && $aft eq "1")){$pos="\n";$i--;last;}
        if($brl{$pos}==2)
        {
          %ypt=("\'",1,"1",1,"`",1,"\"",1);
          if(($pos eq "a") ||
             (($pos eq "l" || $pos eq "o") && ($brl{$aft}==1)) ||
             ($pos eq "o" && ($aft eq "y" || ($aft eq "0" && substr($raw,$i+2,1) ne "0"))) ||
             (($pos eq "y") && (($brl{$aft}==1) || $ypt{$aft})) ||
             ($pos eq "3" && $ypt{$aft}))
          {$pos="\n";$i--;last;}
        }
      }
      $i--;
      $aft=$pos;
      $pos=($bef eq $trg[$#trg])?pop @trg:"\n";
    }
  }
  push @trg,$pos;
  if($pos eq "\n"){$j=0;}
  $j++;
}
print out @trg;
close out;
@trg=undef;
$raw=undef;
print "$of created\n";
}
