#!/usr/local/bin/perl -w

use strict;
use IO::Handle;

# Remove empty labels ("foo..bar" -> "foo.bar")
# Unescape backslashes ("\101" -> "A")
# Re-escape backslashes, dots, and non-ASCII or non-printable characters
sub normalize($ ) {
  my ($text)=@_;
  my @labels=split(/\./, $text);
  @labels=grep(($_ ne ''), @labels);
  @labels=('',) if not @labels;
  foreach my $label (@labels) {
    my $newlabel='';
    while ($label ne '') {
      my $i=index($label, '\\');
      if ($i==-1) {
        $newlabel.=$label;
        last;
      }
      # copy everything up to the backslash
      $newlabel.=substr($label, 0, $i);
      # skip everything up to and including the backslash
      $label=substr($label, $i+1);
      if ($label=~s/^([0-7]{1,3})//) {
        $newlabel.=chr(oct($1));
      } else {
        $newlabel.=substr($label, 0, 1);
        $label=substr($label, 1);
      }
    }
    $label=$newlabel;
    $label=~s/([\\.]|[^ -~])/'\\'.sprintf('%03o', ord($1))/ge;
  }
  return join('.', @labels);
}

my $stdin =*STDIN {'IO'};
my $stdout=*STDOUT{'IO'};
my %soa=();
my %ns=();

my $line;
while (defined($line=$stdin->getline())) {
  if ($line=~/^(.)([^:\n]*)[:\n]/) {
    my $domain=normalize($2);
    if ($1 eq '.' or $1 eq 'Z') { $soa{$domain}=undef; }
    if ($1 eq '.' or $1 eq '&') { $ns {$domain}=undef; }
  }
}

my $domain;
while (defined($domain=each(%soa))) {
  if (exists($ns{$domain})) {
    $stdout->print('.', $domain, "\n");
  }
}
