#!/usr/bin/perl

my %names = qw(debug Debug
	       debug_msg DebugMsg
	       iohandle IOHandle
	       io_handler IOHandler
	       timer Timer
	       io_event_loop IOEventLoop
	       mutex Mutex
	       guard Guard
	       condition Condition
	       address Address
	       inet_address InetAddress
	       socket Socket
	       tcpsocket TCPSocket
	       tcp_acceptor TCPAcceptor
	       length_header LengthHeader
	       ntime Time
	       oserial OSerial
	       oserialstream OSerialStream
               oserialstring OSerialString
               omessage OMessage
	       iserial ISerial
	       iserialdata ISerialData
	       iserialstream ISerialStream
               iserialstring ISerialString
               imessage IMessage
	       thread Thread
	       threaded Threaded
	       tqueue TQueue
	       seda_stage SEDAStage
	       simple_seda_Stage SimpleSEDAStage
               callback Callback
               listeners Listeners
               atomic Atomic
	       term_handler TermHandler
	       status Status
               net_handler NetHandler
               msg_handler MsgHandler
               ::nmstl:: ::NMSTL::);

$names{"namespace nmstl"} = "namespace NMSTL";
$names{"#include <nmstl/"} = "#include <NMSTL/";
my $repl = join("|", keys %names);

if (@ARGV && $ARGV[0] eq "-") {
    while (<>) {
        s/($repl)\b/$names{$1}/esg;
        print;
    }
    exit;
}

sub process {
    my $file = shift;
    my $outfile = shift;

    open(IN, "<$file") || die "Unable to open $file: $!";
    my $data = join("", <IN>);
    close(IN);

    print STDERR "$file => $outfile\n";

    $data =~ s/(--nosub--.+?--endnosub--)|(?<![\/A-Za-z_])(::nmstl::)?($repl)\b/$1 || (uc($2).$names{$3})/esg;

    open(OUT, ">$outfile") || die "Unable to open $outfile: $!";
    print OUT $data;
    close OUT;
}

system "mkdir -p NMSTL SRC EXAMPLE" and die "Unable to mkdir NMSTL: $!";
foreach my $file (<nmstl/*[a-z]>, <src/*.cc>, <example/*.cc>, <example/*.h>) {
    my $outfile = $file;
    $outfile =~ s~^([^/]+)~uc $1~e;
    process($file, $outfile);
}
