#! /usr/local/bin/perl
#                                                         -*- Perl -*-
# Copyright (c) 1999, 2000  Motoyuki Kasahara
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2, or (at your option)
# any later version.
# 
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#

require 5.005;

use English;
use FreePWING::Sort;
use FreePWING::FPWUtils::FPWUtils;
use Getopt::Long;

#
# コマンド行を解析する。
#
if (!GetOptions('workdir=s' => \$work_directory)) {
    exit 1;
}

#
# 環境変数 TMPDIR を設定する。
#
$ENV{'TMPDIR'} = $work_directory;

#
# fpwutils を初期化する。
#
initialize_fpwutils();

#
# これから出力するファイルがすでにあれば、削除する。
#
unlink($sort_file_name);
unlink($endsort_file_name);
unlink($keysort_file_name);

#
# sort コマンドでソートを行う。
#
if (-f $word_file_name) {
    $sort = FreePWING::Sort->new();
    if (!$sort->open($sort_file_name)) {
        die "$PROGRAM_NAME: " . $sort->error_message() . "\n";
    }
    if (!$sort->add_entries_in_file($word_file_name)) {
        die "$PROGRAM_NAME: " . $sort->error_message() . "\n";
    }
    if (!$sort->close()) {
        die "$PROGRAM_NAME: " . $sort->error_message() . "\n";
    }
}

if (-f $endword_file_name) {
    $endsort = FreePWING::Sort->new();
    if (!$endsort->open($endsort_file_name)) {
        die "$PROGRAM_NAME: " . $endsort->error_message() . "\n";
    }
    if (!$endsort->add_entries_in_file($endword_file_name)) {
        die "$PROGRAM_NAME: " . $endsort->error_message() . "\n";
    }
    if (!$endsort->close()) {
        die "$PROGRAM_NAME: " . $endsort->error_message() . "\n";
    }
}

if (-f $keyword_file_name) {
    $keysort = FreePWING::Sort->new();
    if (!$keysort->open($keysort_file_name)) {
        die "$PROGRAM_NAME: " . $keysort->error_message() . "\n";
    }
    if (!$keysort->add_entries_in_file($keyword_file_name)) {
        die "$PROGRAM_NAME: " . $keysort->error_message() . "\n";
    }
    if (!$keysort->close()) {
        die "$PROGRAM_NAME: " . $keysort->error_message() . "\n";
    }
}

#
# fpwutils の後始末をする。
#
finalize_fpwutils();

exit 0;
