#                                                         -*- Perl -*-
# Copyright (c) 2000  Motoyuki Kasahara
# Copyright (c) 2005  Satomi I.
#
# 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.
#

#
# 音声形式ファイルを参照する。
#
package FreePWING::RefSound;

require 5.005;
require Exporter;
use English;
use FileHandle;
use strict;
use integer;

use vars qw(@ISA
	    @EXPORT
	    @EXPORT_OK);

@ISA = qw(Exporter);

#
# 書式:
#	new()
# メソッドの区分:
#	public クラスメソッド。
# 説明:
#	新しいオブジェクトを作る。
# 戻り値:
#	作成したオブジェクトへのリファレンスを返す。
#
sub new {
    my $type = shift;
    my $new = {
	'format' => {},
	'error_message' => '',
    };
    return bless($new, $type);
}

#
# 書式:
#	add_sounds_in_file(file_name)
#           file_name
#		読み込む音声形式ファイルの名前。
# メソッドの区分:
#	public インスタンスメソッド。
# 説明:
#	音声形式ファイルを読み込む。
# 戻り値:
#	成功すれば 1 を返す。失敗すれば 0 を返す。
#
sub add_sounds_in_file {
    my $self = shift;
    my ($file_name) = @ARG;

    #
    # ファイルを開く。
    #
    my $handle = FileHandle->new();
    if (!$handle->open($file_name, 'r')) {
	$self->{'error_message'} =
	    "failed to open the file, $ERRNO: $file_name";
	return 0;
    }

    #
    # 各行を読み込んでハッシュに格納する。
    #
    my ($line, @fields);

    while (1) {
	$line = $handle->getline();
	last if (!defined($line));
	chomp($line);

	@fields = split(/\t/, $line);
	if (defined($self->{'sounds'}->{$fields[0]})) {
	    $self->{'error_message'} =
		"redefined sound name, $fields[0]: line $NR, $file_name";
	    $self->close();
	    return 0;
	}

	$self->{'sounds'}->{$fields[0]} = [ map(hex, splice(@fields, 1)) ];
    }

    #
    # ファイルを閉じる。
    #
    $handle->close();
    1;
}

######################################################################
# <インスタンス変数の値を返すメソッド群>
#
# 書式:
#	インスタンス変数名()
# メソッドの区分:
#	public インスタンスメソッド。
# 戻り値:
#	インスタンス変数の値を返す。
#
sub sound_type {
    my $self = shift;
    my ($tag) = @ARG;

    if (defined($self->{'sounds'}->{$tag})) {
	$self->{'sounds'}->{$tag}[0];
    }
}

sub sound_format {
    my $self = shift;
    my ($tag) = @ARG;

    if (defined($self->{'sounds'}->{$tag})) {
	$self->{'sounds'}->{$tag}[1];
    }
}

sub error_message {
    my $self = shift;
    $self->{'error_message'};
}

1;
