#! /usr/pkg/bin/perl
#                                                         -*- Perl -*-
# Copyright (c) 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::HalfUserChar;
use FreePWING::FPWUtils::FPWUtils;
use Getopt::Long;

#
# ޥɹԤϤ롣
#
if (!GetOptions('workdir=s' => \$work_directory)) {
    exit 1;
}

#
# fpwutils 롣
#
initialize_fpwutils();

#
# 줫Ϥե뤬ǤˤС롣
#
unlink($half_char_name_file_name);
unlink($half_char_bitmap_16_file_name);
unlink($half_char_bitmap_24_file_name);
unlink($half_char_bitmap_30_file_name);
unlink($half_char_bitmap_48_file_name);

$half = FreePWING::HalfUserChar->new();

foreach $file_name (@ARGV) {
    #
    # ե򳫤
    #
    $handle = FileHandle->new();
    if (!$handle->open($file_name, 'r')) {
	die "$PROGRAM_NAME: failed to open the file, $ERRNO: $file_name\n";
    }

    for (;;) {
	#
	# ɤ߹ࡣ
	#
	$line = $handle->getline();
	if (!defined($line)) {
	    last;
	}
	$line =~ s/\r?\n?$//;

	#
	# Ԥȥȹ (`#' ƬƤ) ̵뤹롣
	#
	next if ($line =~ /^\#/ || $line =~ /^$/);

	#
	# ɤ߹Ԥʬ򤹤롣
	#  2  (̾ 16ɥäȳ) ʤȥ顼
	#
	@line_arguments = split(/[ \t]+/, $line);
	if (@line_arguments <= 1) {
	    die "$PROGRAM_NAME: malformed line, at line $NR in $file_name\n";
	}

	#
	# ǽγȥ꤬褿ǡ¦ե򳫤
	#
	if ($half->character_count() == 0) {
	    #
	    # ¦ե򳫤
	    #
	    @half_char_bitmap_file_names = ();
	    push(@half_char_bitmap_file_names, $half_char_bitmap_16_file_name)
		if (2 <= @line_arguments);
	    push(@half_char_bitmap_file_names, $half_char_bitmap_24_file_name)
		if (3 <= @line_arguments);
	    push(@half_char_bitmap_file_names, $half_char_bitmap_30_file_name)
		if (4 <= @line_arguments);
	    push(@half_char_bitmap_file_names, $half_char_bitmap_48_file_name)
		if (5 <= @line_arguments);

	    if (!$half->open($half_char_name_file_name,
			     @half_char_bitmap_file_names)) {
		die "$PROGRAM_NAME: " . $half->error_message() . "\n";
	    }
	}

	#
	# ɤ߹Ԥ˵줿ɲä롣
	#
	if (!$half->add_character(@line_arguments)) {
	    die "$PROGRAM_NAME: " . $half->error_message() . "\n";
	}
    }

    #
    # 򵭽Ҥե򳫤
    #
    $handle->close();
}

#
# ¦եĤ롣
# 
if (!$half->close()) {
    die "$PROGRAM_NAME: " . $half->error_message() . "\n";
}

#
# fpwutils θ򤹤롣
#
finalize_fpwutils();

exit 0;
