#! /usr/bin/perl -w

use strict;
use warnings;

my $source = shift @ARGV || die "usage: $0 source.html filtered.html";
my $dest = shift @ARGV || die "usage: $0 source.html filtered.html";
if (! -r $source) {
    die "$0: cannot read $source";
}
if (-e $dest) {
    die "$0: file exists! $dest";
}

open SOURCE, "<$source";
open DEST, ">$dest";

binmode(DEST);

my $inscript = 0;
my $startre = '<script\b[^>]*>';
my $endre = '</script>';

while (my $line = <SOURCE>) {
    while ($line =~ /$startre/) {
        $line =~ /^(.*?)$startre(.*)(\r?\n)$/;
        if ($inscript == 0) {
            print DEST "$1";
        }
        $inscript++;
        $line = "$2$3";
    }
    
    while ($line =~ /$endre/) {
        $line =~ /^(.*?)$endre(.*)(\r?\n)$/;
        if ($inscript <= 0) {
            warn "$0: something wrong";
        }
        $inscript--;
        $line = "$2$3";
    }
    
    if ($line && $inscript <= 0) {
        print DEST $line;
    }
}
