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

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

#
# fpwutils 롣
#
initialize_fpwutils();

#
# 줫Ϥե뤬ǤˤС롣
#
unlink($color_graphic_file_name);
unlink($color_graphic_tag_file_name);

$graphic = FreePWING::ColorGraphic->new();

#
# ¦ե򳫤
#
if (!$graphic->open($color_graphic_file_name, $color_graphic_tag_file_name)) {
    die "$PROGRAM_NAME: " . $graphic->error_message() . "\n";
}

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  (ե̾ȥ̾) ʤȥ顼
	#
	@line_arguments = split(/[ \t]+/, $line);
	if (@line_arguments != 2) {
	    die "$PROGRAM_NAME: malformed line, at line $NR in $file_name\n";
	}

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

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

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

#
# fpwutils θ򤹤롣
#
finalize_fpwutils();

exit 0;
