#!/bin/perl

# Script to convert pp-fields into text for outside processing
#
# Note that we don't do byte-reordering
#
# Use: pp2txt.pl [options] ppfile > textfile
#  or: cat ppfile | pp2txt.pl [options] > textfile
#
# Author: wmc 2001/01/10

# Options
$D=0;		# Debug
$PH=1;		# Print header
$PD=1;		# Print data. Set to 1 for just data; 
                #                    2 for la,lo,data
                #                    3 for i,j,data

# Override options, eg "pp2txt.pl PD=1"
eval "\$$1=\$2" while $ARGV[0] =~ /^(\w+)=(.*)/ && shift;

if ($File = shift) { open STDIN,$File };

# Read in the length of the first header. Expect 256.
while (read(STDIN,$IN,4)) {

  $rl=unpack("i",$IN);
  if ($rl != 256) { die "Record length is $rl not 256 as I expected" };
  if ($D) { print "Read in header record length $rl\n" };

# Read in the integer part of the header (45 integers) and the real part (19 reals)
  read(STDIN,$IN,4*45);
  @ih=unpack("i45",$IN);
  read(STDIN,$IN,4*19);
  @rh=unpack("f19",$IN);

# Read in the trailer for the header and throw it away
  read(STDIN,$IN,4);

# Print the header
  if ($PH) { print_header() };

# Read the length of the data record
  read(STDIN,$IN,4); $rl=unpack("i",$IN);
  if ($D) { print "Read in data record length $rl\n" };

# Read the data and unpack it
  read(STDIN,$IN,$rl);
  @da=unpack("f*",$IN);

# Read in the length of the record again, in case its a multi-field file
  read(STDIN,$IN,4); 

# Print the data
  if ($PD) { print_data() };

};

sub print_header {

  print <<EOF;
lbyr  : $ih[0]
lbmon : $ih[1]
lbdat : $ih[2]
lbhr  : $ih[3]
lbmin : $ih[4]
lbday : $ih[5]
lbyrd : $ih[6]
lbmond: $ih[7]
lbdatd: $ih[8]
lbhrd : $ih[9]
lbmind: $ih[10]
lbdayd: $ih[11]
lbtim : $ih[12]
lbft  : $ih[13]
lblrec: $ih[14]
lbcode: $ih[15]
lbhem : $ih[16]
lbrow : $ih[17]
lbnpt : $ih[18]
lbext : $ih[19]
lbpack: $ih[20]
lbrel : $ih[21]
lbfc  : $ih[22]
lbcfc : $ih[23]
lbproc: $ih[24]
lbvc  : $ih[25]
lbrvc : $ih[26]
lbexp : $ih[27]
lbegin: $ih[28]
lbnrec: $ih[29]
lbproj: $ih[30]
lbtyp : $ih[31]
lblev : $ih[32]
lbrsvd: $ih[33]
lbrsvd: $ih[34]
lbrsvd: $ih[35]
lbrsvd: $ih[36]
lbsrce: $ih[37]
lbuser: $ih[38]
lbuser: $ih[39]
lbuser: $ih[40]
lbuser: $ih[41]
lbuser: $ih[42]
lbuser: $ih[43]
lbuser: $ih[44]
brsvd : $rh[0]
brsvd : $rh[1]
brsvd : $rh[2]
brsvd : $rh[3]
bdatum: $rh[4]
bacc  : $rh[5]
blev  : $rh[6]
brlev : $rh[7]
bhlev : $rh[8]
bhrlev: $rh[9]
bplat : $rh[10]
bplon : $rh[11]
bgor  : $rh[12]
bzy   : $rh[13]
bdy   : $rh[14]
bzx   : $rh[15]
bdx   : $rh[16]
bmdi  : $rh[17]
bmks  : $rh[18]
EOF


};

sub print_data {

  my $k=0;
  for ($i=0; $i<$ih[17]; $i++) { for ($j=0; $j<$ih[18]; $j++) {
    if ($PD == 3) { 
      print " ",$i+1, " ", $j+1, " $da[$k]\n" 
    } elsif ($PD == 2) { 
      print " ",($i+1)*$rh[14]+$rh[13], " ", ($j+1)*$rh[16]+$rh[15], " $da[$k]\n" 
    } else {
      print "$da[$k]\n"
    };
    $k++;
  } }

};
