#! /bin/sh
( . /sw/bin/init.sh
  PATH=$PATH:/usr/local/bin
  export PATH
  echo $PATH
  cd $HOME/projects/kanbun/mecab-kanbun
  git pull
  D=incoming/$USER
  mkdir -p $D/corpus
  git add $D
  git commit -am sync
  git push origin master
  for F
  do B=`basename $F .utf-8`
     G=$D/corpus/$B.mc.utf-8
     if [ ! -s $G ]
     then sed -e 's/　/ /g' -e 's/［/\[/g' -e 's/］/\]/g' -e 's/\[[^]]*\]//g' -e 's/（/(/g' -e 's/）/)/g' -e 's/([^)]*)//g' `ls -1t incoming/*/[th]*/$B.utf-8 | head -1` | tr '() \133\135' '\012\012\012\012\012' > $G
     elif [ $D/hakubun/$B.utf-8 -nt $G ]
     then ( sed -e 's/　/ /g' -e 's/［/\[/g' -e 's/］/\]/g' -e 's/\[[^]]*\]//g' -e 's/（/(/g' -e 's/）/)/g' -e 's/([^)]*)//g' $D/hakubun/$B.utf-8 | tr '() \133\135' '\012\012\012\012\012' ; echo '' ) | tr -s '\012' '\012' > $G.a~
          sed -n -e '/	/{' -e :loop -e N -e 's/	.*\n//' -e 's/EOS//' -e '/	/bloop' -e p -e '}' $G | tr -s '\012' '\012' > $G.b~
          X=`diff $G.a~ $G.b~ | sed -n -e 's/^\([0-9]*\).*$/\1/p' -e 1q`
          if [ 0$X -gt 0 ]
          then if [ $X -eq 1 ]
               then cp $D/hakubun/$B.utf-8 $G
               else awk '
BEGIN{
  x='$X';
}
{
  printf("%s\n",$0);
  if($0~/EOS/){
    x--;
    if(x<2){
      printf("\n");
      exit;
    }
  }
}' $G > $G.b~
                     tail +$X $G.a~ >> $G.b~
                     mv $G.b~ $G
                fi
          fi
     else :
     fi
     xemacs $G
     git pull
     git add $G
     git commit -am $G
     git push origin master
     rm -f $D/corpus/*~ $D/corpus/'#'*
  done
) > $HOME/corpus.log 2>&1
exit 0
