#!/usr/local/perl/bin/perl

$tmp_file = "/tmp/make_sphere_$$.ul";
$prompt_text_file = "$ENV{SWB_DCOL}/prompts/AAREADME.text";
$sphere_extension = "sphere";

foreach $file (@ARGV) {

    $pnr_name = $file;
    $pnr_name =~ s/^(.*)\..*$/$1/;
    $ext = $file;
    $ext =~ s/^.*\.(.*)$/$1/;

    $sphere_file = "$pnr_name.$sphere_extension";

    printf "converting $file -> $sphere_file\n";

    open(FP,"sox -t .$ext $file -U -r 8000 $tmp_file stat 2>&1|cat|") 
	or die "cannot run sox: $!";
    read(FP, $data, 8192);
    close FP;
    chop $data;
#    printf "data = >$data<\n";
    
    open(FP,"wc $tmp_file|") or die "cannot run wc: $!";
    $sample_count = <FP>;
    chop $sample_count;
    close FP;
    $sample_count =~ s/^\s+\d+\s+\d+\s+(\d+).*$/$1/;
    print "\tsample_count = >$sample_count<\n";

  #  sox -V $TMP_FILE -e stat
    
    open(FP,"basename $file|");
    $basename=<FP>;
    chop $basename;
    $basename=~ s/^(.*)\..*$/$1/;
    
 #   printf "basename = >$basename<\n";

    open (FP, $prompt_text_file) or die "cannot open prompt text file:$!";
    $cont_flag=0;
    
    while(<FP>) {
	chop;
	if ($cont_flag == 1) {
	    if ((/^\d\d\d\d\.\s+/) || (!$_)) {
		$cont_flag = 0;
	    } else {
		$prompt_text = "$prompt_text $_";
	    }
	}
	if ($cont_flag == 0) {

#	    printf "checking $basename against $_\n";
	    if (/^[mM]\.$basename\s+(.*)/) {

		$prompt_text = $1;
		
	    } elsif (/$basename\.\s+(.*)$/) {
		$prompt_text = $1;
		$cont_flag = 1;
	    }
	}
    } 
    close <FP>;
    #  translate all newlines into spaces
    #
    $prompt_text =~ tr/\012/ /;

    # trim spaces from the begining and end of line
    #
    $prompt_text =~ s/^\s*(.*)\s*$/$1/;
    
    # replace all complex white-space with single spaces
    #
    $prompt_text =~ s/\s+/ /g;
    
    print "\tprompt_text = >$prompt_text<\n";

    `h_add $tmp_file $sphere_file` or die "cannot run h_add: $!";
    `rm $tmp_file`;
    
#    h_add $TMP_FILE $SPHERE_FILE;

    `h_edit -Isample_count=$sample_count $sphere_file`;
    `h_edit -Isample_rate=8000 $sphere_file`;
    `h_edit -Isample_n_bytes=1 $sphere_file`;
    `h_edit -Ichannel_count=1 $sphere_file`;
    `h_edit -Isample_max=255 $sphere_file`;
    `h_edit -Isample_min=0 $sphere_file`;
    `h_edit -Ssample_byte_format="1" $sphere_file`;
    `h_edit -Ssample_coding="ulaw" $sphere_file`;
    `h_edit -Sprompt_text="$prompt_text" $sphere_file`;

#    rm $TMP_FILE;
    
}
