#!/usr/bin/perl
# The Missing Textutils, Ondrej Bojar, obo@cuni.cz
# http://www.cuni.cz/~obo/textutils
#
# 'headline "something"' is like '(echo "something"; cat)' but with some extra
# options. Useful in Makefiles, as it expands \t and \n.
#
# $Id: headline,v 1.8 2010-07-25 20:14:44 bojar Exp $

use strict;
use Getopt::Long;

my $append = 0;  # make the headline longer
my $prepend = 0;  # make the headline longer by adding a prefix
my $tail = 0;  # append at the tail
my $skip = 0;  # skip n lines before putting the headline
GetOptions(
  "append"=>\$append,
  "prepend"=>\$prepend,
  "skip=i"=>\$skip,
  "tail" => \$tail
) or exit 1;
my $headline = shift;
die "usage: headline <headline>  < infile   > outfile" if !$headline;

if ($skip) {
  while (<>) {
    $skip--;
    print;
    last if $skip == 0;
  }
}

$headline =~ s/(?<!\\)\\t/\t/g;
$headline =~ s/(?<!\\)\\n/\n/g;
$headline =~ s/\\\\/\\/g;
if ($tail) {
  while (<>) {
    print;
  }
  print $headline."\n";
} else {
  if ($append) {
    my $l = <>;
    chomp $l;
    print $l.$headline."\n";
  } elsif ($prepend) {
    my $l = <>;
    chomp $l;
    print $headline.$l."\n";
  } else {
    print $headline."\n";
  }
  while (<>) {
    print;
  }
}
