#!/bin/perl

# Script to convert text into pp fields
#
# Note that we don't do byte-reordering
# We accept PD=1,2 or 3 format from pp2txt.pl
#
# Use: txt2pp.pl [options] textfile > ppfield
#  or: cat textfile | txt2pp.pl [options] > ppfield
#
# Author: wmc 2001/01/10

# Options
$D=0;		# Debug. Note that this is only useful
                # for the first field, as after that you get the
                # pp-field printed at you raw!

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

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

while (!eof(STDIN)) {

# Read in the integer header elements
  for $i (0 .. 44) {
    $_ = <STDIN>;
    ($ih[$i]) = (/:\s*(.*)/);
    if ($D > 1) { print "$i: $ih[$i]\n" }
  };
# Read in the real header elements
  for $i (0 .. 18) {
    $_ = <STDIN>;
    ($rh[$i]) = (/:\s*(.*)/);
    if ($D > 1) { print "$i: $rh[$i]\n" }
  } 
# Pack the header 
  $h=pack("i i45 f19 i",256,@ih,@rh,256);

# Work out how many data lines we now expect
  $nd = $ih[17] * $ih[18];

# Read in the data
  for $i (0 .. $nd-1) {
    $_ = <STDIN>;
    ($da[$i]) = (/([^ ]+)\n/);
    if ($D > 1) { print "$i: $da[$i]: $_" }
  };

# Pack the data and print the header and data
  $d=pack("i f$nd i",$nd*4,@da,$nd*4);
  print $h,$d;

};
