#!/usr/bin/env nqp
# Copyright (C) 2014, The Perl Foundation


sub MAIN(*@ARGS) {
    my $program := @ARGS.shift;
    my $backend := @ARGS.shift;
    say("# This file automatically generated by $program\n");
    if @ARGS[0] eq '-f' && nqp::elems(@ARGS) >= 2 {
        nqp::shift(@ARGS);
        my $file := nqp::shift(@ARGS);
        my $fh   := open($file, :r, :!chomp);
        while $fh.get -> $line {
            if $line ~~ /\S/ {
                $line := subst($line, /\s+/, '', :global);
                nqp::push(@ARGS, $line);
            }
        }
        close($fh);
    }
    my $stderr := nqp::getstderr();
    for @ARGS -> $file {
        say("#line 1 SETTING::$file");
        my $fh := open($file, :r, :!chomp);
        my int $in_cond := 0;
        my int $in_omit := 0;
        my int $line    := 1;
        while $fh.get -> $_ {
            if my $x := $_ ~~ / ^ '#?if' \s+ ('!')? \s* (\w+) \s* $ / {
                nqp::die("Nested conditionals not supported, line $line") if $in_cond;
                $in_cond := 1;
                $in_omit := $x[0] && $x[1] eq $backend || !$x[0] && $x[1] ne $backend;
                print("\n");
            } elsif $_ ~~ /^ '#?endif' / {
                unless $in_cond {
                    stderr().say(
                        "#?endif without matching #?if in file $file, line $line"
                    );
                }
                $in_cond := 0;
                $in_omit := 0;
                print("\n");
            } elsif $in_omit {
                print("\n");
            } else {
                if $backend eq 'js' && $_ ~~ /'#?js: NFG'/ {
                    print(subst($_, /nqp\:\:[chars|substr|iseq_s|iscclass]/,
                        -> $op {$op ~ 'nfg'}, :global));
                } else {
                    print($_) unless nqp::eqat($_,"# vim:",0);
                }
            }
            $line++;
        }
        close($fh);
    }
    say("\n# vim: set ft=perl6 nomodifiable :");
}

# vim: expandtab sw=4
