#! /bin/perl
#
#  gtb2l/gtl2b  : gtool データのエンディアン変換 (97/02/19 S.Takehiro)
#         usage : gtb2l filename 
#
open(STDIN,$ARGV[0]) || die "Can't open $ARGV[0]: $!\n"
      if $ARGV[0];
#
    if ( $0 =~ "l2b" ) { $convert = "Little -> Big"; }
    if ( $0 =~ "b2l" ) { $convert = "Big -> Little"; }
    printf STDERR "Endian conversion of gtool data, %s.\n", $convert;  
#
# 先頭 4 バイトをまず読んで, データの存在を判断
#
   while(  ( $len = read(STDIN,$data,4) ) == 4 ) {
       &conv_print;
#
#                     gtool ヘッダー部を読む
#
       for ( $i = 1; $i <= 64 ; $i++ ){
           read(STDIN,$gthead[$i],16);
           print $gthead[$i];
#           print $i, " ", $gthead[$i], "\n";
         }

       $dtitle = $gthead[3];
       $dfmt = $gthead[38];
       $size = $gthead[64];
       $size =~ s/  +//g;
       printf STDERR "### READ %s size = %s\n", $dtitle, $size;

       read(STDIN,$data,4);
       &conv_print;
#
#                     データ部を読む
#
       read(STDIN,$data,4);  
       &conv_print;
       for ( $i = 1; $i<= $size ; $i++ ) {
           if    ( $dfmt =~ 'UR4' ) { read(STDIN,$data,4);&conv_print; }
           elsif ( $dfmt =~ 'UR8' ) { read(STDIN,$data,8);&conv2_print; }
           else { print STDERR "DATA FORMAT INVALID\n"; exit(1); }
         }
       read(STDIN,$data,4);
       &conv_print;
   }
######################################################################
#               コマンド名によって変換を定義
# 単精度
#
  sub conv_print {
       if ( $0 =~ "l2b" ) { &l2ben_print; }
       if ( $0 =~ "b2l" ) { &b2len_print; }
   }

  sub l2ben_print {
       @array = unpack('V', $data );
       $data = pack('N', @array);
       print $data;
   }
  sub b2len_print {
       @array = unpack('N', $data );
       $data = pack('V', @array);
       print $data;
   }
#
# 倍精度
#
  sub conv2_print {
       if ( $0 =~ "l2b" ) { &l2ben2_print; }
       if ( $0 =~ "b2l" ) { &b2len2_print; }
   }

  sub l2ben2_print {
       @array = unpack('V2', $data );
       @array = ( $array[1], $array[0] );
       $data = pack('N2', @array);
       print $data;
   }
  sub b2len2_print {
       @array = unpack('N2', $data );
       @array = ( $array[1], $array[0] );
       $data = pack('V2', @array);
       print $data;
   }

