#!/usr/bin/perl --
use strict;
use warnings;

#ThbgmExtractor to FBPlay V.03 (C) Rem under Creative Commons CC0
#Usage: thex_to_fbplay.pl ThbgmExtractor_file [path] > FBPlay_file
#Example(on Unix): thex_to_fbplay.pl titles_th07.txt youmu | perl -pe 's/\n/\r\n/g' > th07.plw

my $in;

sub parsecore{
  my $file=shift;
  while(<$in>){
    my($begin,$intro,$loop,$song)=split(/,/);
    if($begin=~/^#/){next;} #kill 22.5KHz data...
    $begin=hex($begin);
    $intro=hex($intro);
    $loop=hex($loop);
    $song=~s/\n$//;
    $song=~s/\r$//;
    my $time=($intro+$loop)/176400;
    printf "WAV,\\".$file."#%08X/%08X!,".$song.",%.15f,0,%.15f,%.15f,,0\n",$begin,$intro+$loop,$time,$intro/176400,$time;
  }
}

unless($ARGV[0]){print "Please specify filename.\n";exit;}
unless($ARGV[0] =~ /^titles_([a-zA-Z]+[0-9]*(tr)*)\.txt/){print "Input has to be titles_*.txt.\n";exit;}
my $num=uc($1);
unless(open($in,"<",$ARGV[0])){print "Cannot open file.\n";exit;}

while(<$in>){
  last if(substr($_,0,1) ne "#");
}

my($name,$title)=split(/,/,substr($_,1));
my @f=split(/\\/,$name);
my $file=pop(@f);
my $dir=join("\\",@f);
@f=undef;
$title=~s/\n$//;
$title=~s/\r$//;
my $p="";
$p="\\$ARGV[1];0;" if($ARGV[1]);

print <<"EOM";
#FORMAT_VERSION 4.05
#TITLE $title
#MEMO1 WAVE/44.1KHz
#MEMO2 上海アリス幻樂団
#MEMO3 設定データ作成: ThbgmExtractor to FBPlay
#PATHFLAG OFF
#PATH $p\\$dir;0;\\Program Files\\$dir;0
#CODE $num
#LISTTYPE WAVE_44
EOM
parsecore($file);
close($in);
exit;
