#!/usr/local/bin/perl

# orbt.pl
#
#  2005/08/12  H. Murakami  
#                つくばから送られてくるorbt fileを相模原形式にあわせて出力
#  2005/08/22  H. Murakami  
#  2006/07/02  M. Kubo  SOLAR-B用にマイナーチェンジ
#                 
#
# usage: orbt.pl  orbt#### > orbit.data.tmp
#

$tksc_dir = "orbit-i";
$orbit_dir = "orbit";
$orbit_fil = "$orbit_dir/orbit.data";

$tksc_fil = "$tksc_dir/$ARGV[0]";

# 新しい軌道要素の読み込み

open(TKSCFIL,"$tksc_fil") or die("can't open $tksc_fil\n");
while (<TKSCFIL>) {
    # 軌道要素の時刻 (初期値軌道元期) 
    if (/^EMF-TIM\s+(\d+)\s+(\d+)/) {
	$Y = substr($1,0,4);
	$M = substr($1,4,2);
	$D = substr($1,6,2);
	$h = substr($2,0,2);
	$m = substr($2,2,2);
	$s = substr($2,4,2);
	# printf "## %4d %2d %2d  %2d %02d %02d  ", $Y, $M, $D, $h, $m, $s;
    }
    # 平均軌道要素
    if (/^EMF-MEN\s+(\S+)\s+(\S+)\s+(\S+)\s+(\S+)\s+(\S+)\s+(\S+)/) {
	$A = $1;
	$E = $2;
	$I = $3;
	$AN = $4;
	$AP = $5;
	$MA = $6;
	# printf "%.9f %.9f %14.9f %.9f %.9f %.9f ", $1, $2, $3, $4, $5, $6;
    }
    # 平均軌道要素一次変化率
    if (/^EMF-DOT\s+(\S+)\s+\S+\s+\S+\s+(\S+)\s+(\S+)/) {
	$A_DOT = $1;
	$AN_DOT = $2;
	$AP_DOT = $3;
	# printf "%.10E %.10f %.10f ", $1, $2, $3;
    }
    # 周期関連
    # 元々は.10Eで書かれているので、桁が変わると(周期が100分を越えるなど？)
    # .8fなどに変更するべきかも
    if (/^EMF-PER\s+(\S+)\s+\S+\s+(\S+)\s+\S+/) {
	$N = $1;
	$P = $2;
	# printf "%.9f %.9f\n", $1, $2;
    }
}

close(TKSCFIL);

open(ORGORB,"$orbit_fil") or die("can't open $orbit_fil\n");  

while (<ORGORB>) {
    if (/\s*(\d+)\s+(\d+)\s+(\d+)\s+(\d+)\s+/) {
	$num = $1;
	$year = $2;
	$month = $3;
	$day = $4;
	print "$_";
    } elsif (/=+/) {
	$num = $num + 1;
	printf "%2d %4d %2d %2d  %2d %02d %02d  ", $num, $Y, $M, $D, $h, $m, $s;
	printf "%.9f %.9f %14.9f %.9f %.9f %.9f ", $A, $E, $I, $AN, $AP, $MA;
	printf "%.10E %.10f %.10f ", $A_DOT, $AN_DOT, $AP_DOT;
	printf "%.9f  %.12g\n", $N, $P;
	print "$_";
    } else {
	print "$_";
    }
}

close(ORGORB);
