#!/usr/bin/perl
# The Missing Textutils, Ondrej Bojar, obo@cuni.cz
# http://www.cuni.cz/~obo/textutils
#
# 'pastefiles' reads files specified as commandline arguments and then replaces
# all "#include LABEL" lines in stdin with the file content.
#
# $Id: pastefiles,v 1.2 2006/10/17 14:08:54 bojar Exp $
#

use strict;
use Getopt::Long qw(:config pass_through);

sub usage {
  print STDERR "pastefiles --label=filename --label2=filename < input > output
Options:
  --help ... this message
";
  exit 1;
}

my $usage = 0;
GetOptions(
  "help" => \$usage,
) or exit 1;

usage() if $usage;

my %data;
while (my $opt = shift) {
  die "Bad option: '$opt', use '--LABEL=FNAME'"
    if $opt !~ /^-?-([^=]*?)=(.*)$/;
  my $label = $1;
  my $fname = $2;
  open F, $fname or die "Can't read $fname";
  my $text = "";
  while (<F>) {
    $text .= $_;
  }
  close F;
  $data{$label} = $text;
}


my $error = 0;
my $nr = 0;
while (<>) {
  $nr++;
  if (/#include\s+(.*)/) {
    my $label = $1;
    if (!defined $data{$label}) {
      print STDERR "$nr:Undefined label $label\n";
      $error = 1;
      next;
    }
    print $data{$label};
  } else {
    print;
  }
}

exit 1 if $error;
