#!/usr/bin/perl -w
use strict;
use File::Basename;

my $eol = "";
my $last_num = -1;

print "#!/bin/sh\n";
print "set -e\n";
die "I need two arguments (number and file)\n" unless defined($ARGV[1]);
open FILE, "<$ARGV[1]" or die "Can't open $ARGV[1]\n";
while (<FILE>)
  {
    chomp;
    my ($number, $type, $line) = split /:/,$_,3;

    if (defined($number) and $number =~ m/^[0-9 ]+$/)
      {
        if (($number =~ m/^ +$/) and defined($line))
          {
            print " \\" if (($last_num == 0) or ($last_num == $ARGV[0]));
            $number = $last_num;
          }
        print $eol;
        if ($number == 0 or $number == $ARGV[0])
          {
            if ($type eq "TITLE")
              {
                if ($number == 0)
                  {
                    print "echo \"*** $line \${1:+(\$1) }***\"";
                  }
                else
                  {
                    print "echo '*** TEST$number: $line'";
                  }
              }
            elsif ($type eq "CMD")
              {
                my $dir = dirname($0);
                print `. $dir/functions.sh;if [ -r local_functions.sh ]; \
                       then . local_functions.sh;fi;printf "%s " $line`;
              }
            elsif ($type eq "RAW")
              {
                print $line;
              }
            elsif ($type eq "INC")
              {
                open INC, "<", $line or warn "Can't open include file\n";
                while (<INC>)
                  {
                    print;
                  }
              }
            $eol = "\n";
          }
        else
          {
            $eol = "";
          }
      }
    else
      {
        print $eol;
        $eol = "";
      }
    $last_num = $number;
  }
print "\n";
