#!/usr/bin/perl
#
# Generates pointsegment.
# written by Stas Mishchenkov 2:460/58
#
#@CHRS: CP866

use strict;
use warnings;

use Getopt::Long;
use LWP::Simple;
use Cwd 'abs_path';
use Archive::Zip qw(:ERROR_CODES);
use Time::HiRes;
use File::Spec::Functions;
use File::Copy;
use Time::Local;
use Digest::CRC qw( crc16 );
use File::Path qw(make_path remove_tree);
use Time::TZOffset qw/tzoffset/;

my $vers = 'v.0.0.0.7';
my $url = 'http://brorabbit.g0x.ru/files/perl/';

my ( %config, %nodelist, $needhelp, $prinver, $whatsnew, $errorsonly, $export,
	$check_updates, $logfile, $config, %globals );

abs_path($0) =~ /^(.*?)[\\\/]([^\\\/]+)$/;
my ( $curpath, $programfile ) = ( $1, $2 );

my $tz = tzoffset( localtime() );
$tz =~ /(\d{2})(\d{2})/;
$tz = $1*3600+$2*60;

use constant PVT => 0x0001;
use constant CRA => 0x0002;
use constant RCD => 0x0004;
use constant SNT => 0x0008;
use constant ATT => 0x0010;
use constant TRS => 0x0020;
use constant K_S => 0x0080;
use constant LOC => 0x0100;
use constant HLD => 0x0200;
use constant REQ => 0x0800;
use constant RRQ => 0x1000;
use constant RRD => 0x2000;
use constant AUD => 0x4000;
use constant UPD => 0x8000;

sub usage()
{
	printf <<USAGE;

                        \"New Point Keeper.\".
   A tool for creating pointlists to Point Keepers of different levels, based
on FTS-5002 rev.2, FTS-5000 rev.5 and FTS-5001 rev.6.
                                         Written by Stas Mishchenkov 2:460/58.

Usage: $programfile options
~~~~~~
       Options:

   --config,-c[=]filename  Name of config file. Required.
   --export,-e             Export configuration and exit.
   --ver,-V                Print version and exit.
   --whatsnew,-w           Print whats new in new version and exit. Internet
                           connection requierd.
   --update,-u             How to update the program. Optional.
                                  =d - download. Check for a new version and
                                       download the update to a new file.
                                  =f - Force download $programfile end exit
                                       even if no new version is found.
                                  =w - warn. Check for a new version and warn
                                       the sysop. Default.
                                  =n - no. Do nothing. 

    --log,-l[=]filename    The name of log file. No logging if not defined.
    --help,-h              This text.

USAGE
	exit;
}

sub readcfg($)
{

	my ($cfgfile) = @_;
	my ($line, $keyword, $rest);
	
	writelog("Reading config file $cfgfile.");
	if ( open( my $CFG, '<', $cfgfile ) ) {
		while ( $line = <$CFG> ) {
			$line =~ s/	/ /gs;
			$line =~ s/\r?\n$//s;
			$line =~ s/[ ]+$//s;
			next if $line =~ /^[ ]*\#.*/i;
			if ( $line =~ /^[ ]*([a-z_]+)[ ]+([^ ]+.*)/i ) {
				( $keyword, $rest ) = ( lc( $1 ), $2 );
#				$keyword = lc( $keyword );
				$config{$keyword} = $rest;
			}
		}
		close( $CFG );

	} else {
		print STDERR "Can't open $config{segfilename} ($!).\n";
	}
	checkconf();
}


sub mktree( $ )
{
	my ( $msgbasefile ) = @_;
	my ( $err );
		make_path( $msgbasefile, { mode => 0777, error => \$err } ) unless -d $msgbasefile;
		if ( $err && @$err ) {
			for my $diag ( @$err ){
				my ($file, $message) = %$diag;
				if ($file eq '') {
					writelog( "General error: $message");
				} else {
            		writelog( "Problem making $file: $message");
        		}
    		}
			return 0 ;
		}
	return 1;
}

sub checkconf()
{
		$logfile = $config{logfilename} if defined $config{logfilename};
		unless( defined( $config{segfilename} ) ) {
			print STDERR "Segfilename must be defined!\n";
			exit;
		}
		$config{segfilename} =~ s/\./\\\./;
		$config{segfilename} =~ s/\*/\.\*/g;
		$config{segfilename} =~ s/\?/\./g;
		$globals{segmentname} = "the whole world";
		$globals{segmentname} = "Zone $config{zone}" if defined $config{zone};
		$globals{segmentname} = "Region $config{region}" if defined $config{region};
		$globals{segmentname} = "Net $config{net}" if defined $config{net};
		if ( defined( $config{workdir} ) ) {
			mktree( $config{workdir} ) unless -d $config{workdir};
			$config{uue} = catdir( $config{workdir}, 'uue');
			mktree( $config{uue} ) unless -d $config{uue};
			$config{unzipto} = catdir( $config{workdir}, 'unzip');
			mktree( $config{unzipto} ) unless -d $config{unzipto};
		} else {
			print STDERR "Workdir must be defined!\n";
			exit;
		}
		if ( defined( $config{backupdir} ) ) {
			mktree( $config{backupdir} ) unless -d $config{backupdir};
		} else {
			print STDERR "Backupdir must be defined!\n";
			exit;
		}
		$config{sendwarnings} = 'no' unless defined $config{sendwarnings};
		$config{scannetmail} = 'no' unless defined $config{scannetmail};
		if ( defined( $config{netmail} ) ) {
			mktree( $config{netmail} ) unless -d $config{netmail};
		} else {
			$config{sendwarnings} = 'no';
			$config{scannetmail} = 'no';
		}
		$config{chrs} = 'CP866' unless defined $config{chrs};
		$config{sysopname} = 'Point Keeper' unless defined $config{sysopname};
		$config{sendpoinlistby} = lc($config{sendpoinlistby}) if defined( $config{sendpoinlistby} );
		if ( defined( $config{delzip} ) ) {
			$config{delzip} = lc( $config{delzip} );
		} else {
			$config{delzip} = 'yes';
		}
		$config{pointlistformat} = 'boss' unless defined $config{pointlistformat};
		$config{pointlistformat} = lc( $config{pointlistformat} );
}

sub writelog
{
    my ( $str ) = @_;
    my ($sec,$min,$hour,$mday,$mon,$year,$wday,$yday,$isdst) = localtime();
	$globals{backdir} = sprintf("%04d-%02d-%02d",
			       ($year+1900), $mon+1, $mday );
    return unless defined( $logfile );
    $str =~ s/([\r\n])$//;
	my $startstr = sprintf("%04d-%02d-%02d %02d:%02d:%02d ",
			       ($year+1900), $mon+1, $mday, $hour, $min, $sec );
    $str =~ s/([\r\n]+)/$1$startstr/g;
	
        if ( open( my $FLOG, '>>', $logfile ) ) {
			print( $FLOG "${startstr}$str\n" );
			close( $FLOG );
        } else {
            print( STDERR "Can't open $logfile. ($!)\n" );
        }
}

sub writemsg
{
    my ( $msgpath, $fromUserName,$toUserName,$subject,$DateTime,
    $timesread,$destnode,$orignode,$cost,$orignet,$destnet,
    $date_written16,$time_written16,$date_arrived,$time_arrived,$replyto,
    $attr,$nextmsg ) = @_;
    
    if( open( my $FL, '>', $msgpath ) ) {
        binmode( $FL );
        print( $FL pack( "Z36Z36Z72Z20S13Z".(length($globals{msgtext})),
        $fromUserName,$toUserName,$subject,$DateTime,
        $timesread,$destnode,$orignode,$cost,$orignet,$destnet,
        $date_written16,$time_written16,$date_arrived,$time_arrived,
        $replyto,$attr,$nextmsg,$globals{msgtext} ) );
        close( $FL );
	} else {
        print( STDERR "Can't open \"$msgpath\".($!)\n" );
        writelog( "Can't open \"$msgpath\".($!)" );
    }
}

sub sendmsg
{
	my ( $fromname, $toname, $fromaddress, $toaddress, $subj, $attr ) = @_;
	my ( $maxmsgnum, $dirhandle, $msgfilename, $destnode, $orignode,
		$orignet, $destnet );
	return unless defined( $config{netmail} );
	return unless defined( $fromaddress );
	
	unless( opendir( $dirhandle, $config{netmail} ) ) {
		writelog( "Can't open $config{netmail} ($!)." );
		return;
	}
	$maxmsgnum = 0;
	while ( readdir( $dirhandle ) ) {
		if ( $_ =~ /(\d+)\.msg$/i ) {
			$maxmsgnum = $1 if $1 > $maxmsgnum;
		}
	}
	closedir( $dirhandle );
	$maxmsgnum++;
	$msgfilename = catfile( $config{netmail}, "$maxmsgnum\.msg" );

    localtime =~ /[a-z]+ ([a-z]+)[ ]+(\d+) (\d+)\:(\d+)\:(\d+) \d\d(\d\d)/i;
    my $DateTime = sprintf("%02s", $2)." $1 $6  $3:$4:$5\000";

    $toaddress =~ /^(\d+)\:(\d+)\/(\d+)$/;
	( $destnet, $destnode ) = ( $2, $3 );

    $fromaddress =~ /^(\d+)\:(\d+)\/(\d+)$/;
	( $orignet, $orignode ) = ( $2, $3 );

	$globals{msgtext} =~ s/\n/\r/g;

    my $TZUTC = sprintf( "%04d", tzoffset( localtime() ) );

	$globals{msgtext} = "\001MSGID: $fromaddress " . sprintf( "%08x", time() ).
						"\r\001TZUTC: $TZUTC\r" .
						"\001INTL $toaddress $fromaddress\r" .
						"\001CHRS: ".uc($config{chrs})." 2\r" .
						$globals{msgtext} .
						"\r--- $programfile $vers\r" .
						" \* Origin: New Point Keeper ($fromaddress)\r\x00";

	writemsg( $msgfilename, $fromname, $toname, $subj, $DateTime,
			0,$destnode,$orignode,0,$orignet,$destnet, 0,0,0,0,0,
			$attr, 0 );

}

sub uu_decode($;$)
{
	my ( $mtext, $uuedir ) = @_;
	my $uudecoded_data;

	if ( !defined($uuedir) ){
		$uuedir = catdir( $config{workdir}, 'uue');
		mktree $uuedir unless -d $uuedir;
	}

	my $i = 0;
	while ( $mtext =~ /\r\n?begin \d+[ ]+([^\r\n?]+)\r\n?([^ ]*?\r\n?)end\r\n?/i ){
		writelog( "UUencoded file $1 found." ); 
	    my @uuelines = split(/\r\n?/,$2);
#	    local $decdir = $uuedir . $slash . uc($marea);
	    my $ofile = catfile( $uuedir, $1 );
#	    $ofile = find_free_filename($ofile) if !$overwrite;
#	    mkdir $decdir if !-e $decdir;
	    if ( open( my $F, '>', $ofile ) ){
			binmode( $F );
			foreach my $val ( @uuelines ){
				$uudecoded_data = unpack("u", $val);
				print( $F $uudecoded_data ) if defined $uudecoded_data;
			}
			close( $F );
			undef @uuelines;
			$i = 1;
		} else {
			writelog("Can't open \"$ofile\"\: $!\.");
			print STDERR "Can't open \"$ofile\" ($!).\n";
	    }
		$mtext =~ s/\r\n?begin \d+[ ]+[^\r\n?]+\r\n?[^ ]*?\r\n?end\r\n?/\r\n/i;
	}
return $i;
}

sub scannetmail()
{
	my ( $DN, $msgpath, $msgsize, $FM, $msgheader );

	return unless defined( $config{netmail} );

	unless ( opendir( $DN, $config{netmail} ) ) {
		print(STDERR "Can't open $config{netmail} directory ($!).\n");
	    writelog( "Can't open $config{netmail} directory ($!)." );
        return;
    }
    printf("Reading NetMail area...\n");
    writelog("Reading NetMail area...");

    while( readdir( $DN ) ) {
		if( $_ =~ /^(\d+)\.msg/i) {
            $msgpath = catfile( $config{netmail}, $_ );
			$msgsize = -s $msgpath;
            unless ( open( $FM, '+<', $msgpath ) ) {
				print STDERR "Can't open $msgpath ($!).\n";
				writelog( "Can't open $msgpath ($!)." );
				return;
			}
			binmode( $FM );
            unless ( read( $FM, $msgheader, 190 ) == 190 ) {
				print STDERR "Can't read $msgpath ($!).\n";
				writelog( "Can't read $msgpath ($!)." );
				close( $FM );
				next;
			}
			my ($fromUserName,$toUserName,$subject,$DateTime,
				$timesread,$destnode,$orignode,$cost,$orignet,$destnet,
				$date_written16,$time_written16,$date_arrived16,$time_arrived16,
				$replyto,$attr, $nextmsg) = unpack("Z36Z36Z72Z20S12",$msgheader);
			if ( $attr & RCD ) {
				close( $FM );
				next;
			} elsif ( $toUserName !~ /$config{sysopname}/i ) {
				close( $FM );
				next;
			}
            unless ( read( $FM, $globals{msgtext}, $msgsize - 190 ) == ( $msgsize - 190 ) ) {
				print STDERR "Can't read $msgpath ($!).\n";
				writelog( "Can't read $msgpath ($!)." );
				close( $FM );
				next;
			}
			unless( $globals{msgtext} =~ /begin[ ]+\d+[ ]+$config{segfilename}/i ) {
				close( $FM );
				next;
			}
# -- uudecode -->
			readinbound( $config{uue} ) if uu_decode( $globals{msgtext}, $config{uue} );
			if ( seek( $FM, 0, 0 ) ) {
				$attr += RCD;
				print $FM pack("Z36Z36Z72Z20S12",$fromUserName,$toUserName,$subject,$DateTime,
				$timesread,$destnode,$orignode,$cost,$orignet,$destnet,
				$date_written16,$time_written16,$date_arrived16,$time_arrived16,
				$replyto,$attr, $nextmsg);
			}
			close( $FM );
			
		}
	
	}
    closedir( $DN );
}

sub update()
{
    return if $check_updates eq 'n';
    return unless $check_updates =~ /^[nwdf]$/;

    my ( $ver_s, $upd, $of, $progname );
	if ( $programfile =~ /^(.*?)\..*$/ ) {
		$progname = $1;
	} else { $progname = 'npk'; }

    $ver_s = get( $url . "$progname.v");
    if (defined ($ver_s) ) {
	if ( $check_updates eq 'f' ) {
	    $of = catfile( $curpath,"${progname}_${ver_s}\.pl" );
		print "Latest version is $ver_s\!\n";
		writelog("Latest version is $ver_s\! Downloaded filename is \'$of\'.\n");
	} elsif ( $vers lt $ver_s ) {
	    if ( $check_updates eq 'w' ) {
			print " \*\*\* You should update to $ver_s\! \*\*\* \n";
			writelog(" \*\*\* You should update to $ver_s\! \*\*\* \n");
			return;
	    } elsif ( $check_updates eq 'd' ) {
			$of = catfile( $curpath,"${progname}_${ver_s}\.pl" );
		} else {
			$of = catfile( $curpath,"${progname}_${ver_s}\.pl" );
		}
		print "You should update to $ver_s\!\n";
		writelog(" \*\*\* You should update to $ver_s\! Update filename is \'$of\'.\n");
	} else {
	    print "You have actual version.\n";
	    return;
	}
	$upd = get( $url . "$progname.pl" );
	unless( defined $upd ) {
	    print STDERR "Can't get update.\n";
	    writelog("Can't get update. ${url}${progname}.pl\n");
	    return;
	}
	my $OF;
	if ( open ( $OF, '>', $of ) ) {
	    binmode( $OF );
	    print( $OF $upd );
	    close( $OF );
	    chmod 0755, $of if $^O eq 'linux';
	    print "$of saved.\n\n";
	} else {
	    print STDERR "Can't open $of ($!).\n";
	}
    } else {
		print STDERR "Can't connect to $url\n";
		writelog("Can't connect to $url\n");
    }
    exit if $check_updates eq 'f';
}

sub whats_new()
{
		my $wn = get( $url . 'npk.w');
		if( defined( $wn) ) {
			if ( $wn =~ /^$vers/i ) {
	    		print $wn;
			} elsif ( $wn =~ /$vers/i ) {
				print $`;
			} else { print $wn; }
    	} else {
			print "Can't get what's new.\n";
    	}
    	exit;
}


sub read_pnt_time($)
{
   my ( $filename ) = @_;
   my ( $FH, $ndlstr, $line, $nltime, %month );

   if ( open( $FH, '<', $filename ) ) {
	$line = readline( $FH ); 
	close( $FH );
	if ( $line =~ /\;.*?(\d+) \-\- Day number (\d+)/i ) {
		return "$1$2";
	} else {
		return 0;
	}
   } else {
	print STDERR "Cant read $filename ($!).\n";
	writelog( "Cant read $filename ($!)." );
	return 0;
   }
}



sub read_ndl_time($)
{
   my ( $filename ) = @_;
   my ( $FH, $ndlstr, $line, $nltime, %month );

   $month{January} = 0;
   $month{February} = 1;
   $month{March} = 2;
   $month{April} = 3;
   $month{May} = 4;
   $month{June} = 5;
   $month{July} = 6;
   $month{August} = 7;
   $month{September} = 8;
   $month{October} = 9;
   $month{November} = 10;
   $month{December} = 11;
   
   if ( open( $FH, '<', $filename ) ) {
	$line = readline( $FH ); 
	close( $FH );
	if ( $line =~ /\;A FidoNet Nodelist for \S+, (\S+) (\d+), (\d+) -- Day number \d+ : \d+/i ) {
		$nltime = timelocal( 0, 0, 0, $2, $month{$1}, $3 - 1900 );
		return $nltime;
	} else {
		print STDERR "Probably not a nodelist file $filename.\n";
		return 0;
	}
   } else {
	print STDERR "Cant read $filename ($!).";
	return 0;
   }
}


sub findndl($)
{
    my ( $filemask ) = @_;
    my $start = Time::HiRes::time();
    
    writelog("Finding last nodelist file from $filemask.");
    $filemask =~ /(.*?)([^\\\/]+)$/;
    my ( $ndlpath, $ndlfn ) = ( $1, $2 );
    my ( $nldate, $lastdate, $lastnl );
    $ndlpath = './' if !defined( $ndlpath ) || $ndlpath eq '';
#    print abs_path($ndlpath) . "\n";
    unless( -e $ndlpath ){
	print STDERR "\'$ndlpath\' does not exist!\n";
	exit;
    }
    $ndlfn =~ s/\./\\\./g;
    $ndlfn =~ s/\*/\.\*/g;
    $ndlfn =~ s/\?/\./g;
    $lastdate = 0;
    if ( opendir( DH, $ndlpath ) ) {
	while( readdir(DH) ) {
	    if( $_ =~ /^${ndlfn}$/i) {
		$nldate = read_ndl_time( catfile( $ndlpath, $_ ) );
		if ( $nldate > $lastdate ) {
		    $lastdate = $nldate;
		    $lastnl = $_;
		}
	    }
        }
    } else {
	print STDERR "Can't open $ndlpath. ($!)\n";
	exit;
    }
    unless( defined( $lastnl ) ) {
	print STDERR "Nodelist not found.\n";
	writelog( 'Nodelist not found.' );
	exit;
    }
    writelog( 'Last nodelist found at ' . sprintf( "%.3f" , ( Time::HiRes::time() - $start ) ) . ' seconds.' );
    return catfile( $ndlpath, $lastnl );
}

my ( %regions, %nets );

sub readndl($)
{
    my ($nlist) = @_;
    my ($zone, $net, $node, $region, $dom, $ird, $domain, $start, $nldate );
    my ($line, $keyword, $name, $phone, $flags, $port, $lport, %port,
        $F, %lport, $nodes, $i, $addr);
    my (%flags, $uflag, %addr, @addr, $domzone, $domreg, $domnet, $domflag );

    unless ( -e $nlist ) {
	print( "No nodelist found!\n");
	writelog('ERROR! No nodelist found!');
	exit;
    }
    unless ( open ( $F, "<", $nlist ) ) {
	print( "Cannot read nodelist $nlist: $!\n");
	writelog("ERROR! Cannot read nodelist $nlist: $!");
	exit;
    }

    print("Parsing nodelist file $nlist \n");
#    $start = time();
    $start = Time::HiRes::time;
    $zone = $net = $node = 0;
#    $domzone = $domreg = $domnet = $ird = "";
#    $domain = 'binkp.net';
    $nodes = 0;
    while (defined($line = <$F>)) {
	if( $line =~ /Nodelist ([a-zA-Z]+ [a-zA-Z]+\, [a-zA-Z]+ \d+\, \d+ \-\- Day number \d+)/i) {
	    $nldate = $1;
		$globals{nodelistldate} = $nldate;
	    next;
	}
	$line =~ s/\r?\n$//s;
	next unless $line =~ /^([a-z]*),(\d+),[^,]*,[^,]*,([^,]*),([^,]*),\d+(?:,(.*))?\s*$/i;
	($keyword, $node, $name, $phone, $flags) = ($1, $2, $3, $4, $5);
#	next if $keyword eq "Down";
#	next if $keyword eq "Hold";
#	next if $keyword eq "Pvt";
#	next unless defined $flags;
	$uflag = "";
	%flags = ();
#	%addr = ();
	@addr = ();
	if ($keyword eq "Zone") {
	    $zone = $region = $net = $node;
	    $node = 0;
	    $domzone = $domreg = $domnet = "";
	    foreach $i (qw(M 1 2 3 4)) {
		$domzone = $domreg = $domnet = "DO$i:" . $flags{"UDO$i"} if $flags{"UDO$i"};
	    }
	} elsif ($keyword eq "Region") {
	    $region = $net = $node;
	    $node = 0;
		$regions{$region} = '' if defined( $config{zone} ) && $zone == $config{zone};
	} elsif ($keyword eq "Host") {
	    $net = $node;
	    $node = 0;
	    $domnet = '';
		$nets{$net} = '' if defined( $config{region} ) && $region == $config{region};
	}
	if ( defined( $config{zone} ) ) {
		next unless $zone == $config{zone};
	}
	if ( defined( $config{region} ) ) {
		next unless $region == $config{region};
	}
	if ( defined( $config{net} ) ) {
		next unless $net == $config{net};
	}
#	$sortednodes{"$zone\:$net\/$node"} = $region;
#	if ( $flags =~ /,PING/i ) {
#	if ( $flags =~ /,NPK/i ) {
#		$nets{$net} = "$name $zone\:$net\/$node";
#		$nets{$net} =~ s/_/ /;
#	} elsif ( $flags =~ /,RPK/i ) {
#		$regions{$region} = "$name $zone\:$net\/$node";
#		$regions{$region} =~ s/_/ /;
#	}

		$nodes++;
#		print sprintf( "%4s ", $nodes ) . "$zone\:$net\/$node\n";
		$name =~ s/_/ /g;
		$nodelist{"$zone\:$net\/$node"} = $name;
#	}
   }
    close($F);
    my $lstr = "Nodelist $nldate parsed, $nodes nodes processed (" . sprintf( "%.3f" ,(Time::HiRes::time() - $start) ) . " sec)";
    print( "$lstr\n" );
    writelog( $lstr );
}

sub readfile($)
{
	my ( $filename ) = @_;
	my ( $HANDLE, $size, $buff );

	$size = -s $filename;
	if ( open ( $HANDLE, '<', $filename ) ) {
	    binmode($HANDLE);
	    unless( read( $HANDLE, $buff, $size ) == $size ) {
	    	print STDERR "Can't read $filename ($!).\n";
	    	writelog( "Can't read $filename ($!)." );
			close( $HANDLE );
			return 0;
		}
	    close( $HANDLE );
	} else {
	    print STDERR "Can't open $filename ($!).\n";
	    writelog( "Can't open $filename ($!)." );
	}
	return $buff;
}


my ( %bossnodes );
my %modemflags = ( V22 => '', V29 => '', V32 => 'V22', V32B => 'V32,V22',
                   V32T => 'V32B,V32,V22', V34 => 'V22,V32,V32B', V42 => 'MNP',
                   V42B => 'V42,MNP', MNP => '', H96 => '', HST => 'MNP',
                   H14 => 'HST,MNP', H16 => 'H14,HST,MNP,V42,V42B', MAX => '',
                   PEP => '', CSP => '', VFC => 'V32B,V32,V22',
                   ZYX => 'V22,V32B,V32,V42B,V42,MNP',
                   V90C => 'V34,V22,V32,V32B', V90S => 'V34,V22,V32,V32B',
                   X2C => 'V22,V32,V32B,V34', X2S => 'V22,V32,V32B,V34',
                   Z19 => 'ZYX,V32B,V32,V42B,V42,MNP,V22'
                 );

sub knownflag( $ )
{
	my ( $flag ) = @_;
	my %knownflags = ( 'CM' => '', 'ICM' => '', 'MO' => '', 'LO' => '',
						'MN' => '', 'IBN' => '', 'IFC' => '', 'IFT' => '',
						'ITN' => '', 'IVM' => '', 'GUUCP' => '', 'XA' => '',
						'XB' => '', 'XC' => '', 'XP' => '', 'XR' => '',
						'XW' => '', 'XX' => '', 'INO4' => '', 'ITX' => '',
						'IUC' => '', 'IMI' => '', 'ISE' => '', 'EVY' => '',
						'EMA' => '', 'IEM' => '', 'U' => '', 'V110L' => '',
						'V110H' => '', 'V120L' => '', 'V120H' => '',
						'X75' => '', 'ISDN' => '', 'PING' => '', 'TRACE' => '',
						'ZEC' => '', 'REC' => '', 'NEC' => '', 'NC' => '',
						'SDS' => '', , 'SMH' => '', 'RPK' => '', 'NPK' => '',
						'ENC' => '', 'CDP' => '', 'INA' => ''
					 );
	my ( $f );

	return 1 if defined $modemflags{$flag};
	return 1 if $flag =~ /^T[a-x][a-x]$/i;

	if ( $flag =~ /([\#\!])\d\d/ ) {
		foreach $f ( split( /$1/, $flag ) ) {
			if ( $f eq '02' || $f eq '08' || $f eq '09' || $f eq '17' ) {
				return 1;
			} else {
				return 0 if defined$f && $f ne '';
			}
		}
		return 1;
	}
	if ( $flag =~ /^(I[BFTVN][NCTMA])\:.*/i ) {
		$flag =~ s/^(I[BFTVN][NCTMA])\:.*/$1/i;
	} elsif ( $flag =~ /[IE][TUMSVE][XCIEYAM]\:.*/ ) {
		$flag =~ s/([IE][TUMSVE][XCIEYAM])\:.*/$1/;
	}
	return 1 if defined $knownflags{$flag};
	return 0;
}

sub readseg( $ )
{
	my ( $filename ) = @_;
	my ( $FH, $line, $boss, $point, $system, $location, $sysop, $phone, $baud,
		$flags, $errstr, $fl, $keyword );
	my @ipflags = ( 'IBN', 'IFC', 'IFT', 'ITN', 'IVM' );
	my @nomeaningflags = ( 'CM', 'ICM', 'MO', 'LO', 'MN' );
	my %baudrate = ( '300' => 1, '1200' => 1, '2400' => 1, '4800' => 1,
					'9600' => 1, '14400' => 1, '16800' => 1, '19200' => 1,
					'28800' => 1, '33600' =>1, '38400' => 1 );

	if ( open( $FH, $filename ) ) {
		$errstr = '';
		while( $line = <$FH> ) {
			if( $line =~ /\;A (.*? \-\- Day number \d+).*/i ) {
				writelog( "Found $1." );
			}
			next if $line =~ /\s*\;/;
			$line =~ s/[\r\n]//g;
			if ( $line =~ /^Boss\,(\d+\:\d+\/\d+)\,?.*$/i ) {
				my $newboss = $1;
				if ( defined( $boss ) && defined( $nodelist{$boss} ) ) {
					if ( $bossnodes{$boss}{errors} ne '' ) {
						writelog( $bossnodes{$boss}{errors} );
						$globals{msgtext} = $bossnodes{$boss}{errors};

						sendmsg( $config{sysopname}, $nodelist{$boss},
								$config{address}, $boss,
								'Errors in your point segment.',
								PVT+K_S+LOC ) if $config{sendwarnings} eq 'yes';

						$bossnodes{$boss}{errors} = '';
					} else {
						writelog( " No errors found." );
					}
				}
				$boss = $newboss;
				$bossnodes{$boss}{errors} = '';
				$bossnodes{$boss}{points} = '';
				writelog( "Boss $boss" );
				writelog( "~~~~ WARNING! Unknown node!" ) unless defined( $nodelist{$boss} );

#				if ( $line =~ /\s/ ) {
#					$bossnodes{$boss}{errors} = 1;
#				}
			} elsif ( $line =~ /^(.*?)\,(\d+)\,(.*?)\,(.*?)\,(.*?)\,(.*?)\,(\d+)(.*)$/i ) {
				( $keyword, $point, $system, $location, $sysop, $phone, $baud,
				 $flags ) = ( $1, $2, $3, $4, $5, $6, $7, $8 );

				if ( $keyword eq 'Point' && $config{pointlistformat} eq 'boss' ) {
					if ( $line ne $errstr ) {
						$bossnodes{$boss}{errors} .= "$line\r";
						$errstr = $line;
					}
					$bossnodes{$boss}{errors} .= "The \"Poss\" (pointplus) format is deprecated.\r";
				} elsif ( $keyword ne '' && $keyword ne 'Point' ) {
					if ( $line ne $errstr ) {
						$bossnodes{$boss}{errors} .= "$line\r";
						$errstr = $line;
					}
					$bossnodes{$boss}{errors} .= "Meaningless keyword \'$keyword\' must not be used.\r";
				}
				if ( $point > 32767 ) {
					if ( $line ne $errstr ) {
						$bossnodes{$boss}{errors} .= "$line\r";
						$errstr = $line;
					}
					$bossnodes{$boss}{errors} .= "Point number must be in the range of 1 to 32767.\r";
					undef $point;
#					next;
				}
				if ( $sysop !~ /(UUCP)|(_)/i ) {
					$sysop = "Named_as_$sysop";
					if ( $line ne $errstr ) {
						$bossnodes{$boss}{errors} .= "$line\r";
						$errstr = $line;
					}
					$bossnodes{$boss}{errors} .= "Starting \#037/09 one word sysop names are no longer permitted except the keyword \'UUCP\'.\r";
				}
				if ( length($sysop) > 36 ) {
					$sysop = substr($sysop, 0, 36);
					if ( $line ne $errstr ) {
						$bossnodes{$boss}{errors} .= "$line\r";
						$errstr = $line;
					}
					$bossnodes{$boss}{errors} .= "SysOp name can not be longer then 36 letters include space. The result is: \"$sysop\"\r";
				}
				if ( $sysop =~ /[^\x20-\x7E]/ ) {
					$sysop =~ s/([^\x20-\x7E])/\#/g;
					if ( $line ne $errstr ) {
						$bossnodes{$boss}{errors} .= "$line\r";
						$errstr = $line;
					}
					$bossnodes{$boss}{errors} .= "Not permitted letters in SysOp name replaced by \'\#\'. The result is: \"$sysop\"\r";
				}
				if ( $location =~ /[^\x20-\x7E]/ ) {
					$location =~ s/([^\x20-\x7E])/\#/g;
					if ( $line ne $errstr ) {
						$bossnodes{$boss}{errors} .= "$line\r";
						$errstr = $line;
					}
					$bossnodes{$boss}{errors} .= "Not permitted letters in location name replaced by '#'. The result is: \"$location\"\r";
				}
				if ( $system =~ /[^\x20-\x7E]/ ) {
					$system =~ s/([^\x20-\x7E])/\#/g;
					if ( $line ne $errstr ) {
						$bossnodes{$boss}{errors} .= "$line\r";
						$errstr = $line;
					}
					$bossnodes{$boss}{errors} .= "Not permitted letters in System name replaced by '#'. The result is: \"$system\"\r";
				}
# --- flags --->
				if ( $phone =~ /\-Unpublished\-/i ) {
					if ( $baud ne '300' ) {
						$baud = '300';
						if ( $line ne $errstr ) {
							$bossnodes{$boss}{errors} .= "$line\r";
							$errstr = $line;
						}
						$bossnodes{$boss}{errors} .= "Baud must be 300 if phone is -Unpublished-.\r";
					}
					foreach  $fl ( keys %modemflags ) {
						if ( $flags =~ /\,($fl)\b/i ) {
							$flags =~ s/\,($fl)\b//i;
							if ( $line ne $errstr ) {
								$bossnodes{$boss}{errors} .= "$line\r";
								$errstr = $line;
							}
							$bossnodes{$boss}{errors} .= "Flag \'$1\' has no meaning  if phone is -Unpublished-.\r";
						}
					}
					if ( $flags !~ /\,INA/i && 
						$flags !~ /\,I[BFTV][NCTM]\:.*/i) {
						if ( $flags =~ /\,(X[ABCPRWX])/i ) {
							$flags =~ s/\,(X[ABCPRWX])//i;
							if ( $line ne $errstr ) {
								$bossnodes{$boss}{errors} .= "$line\r";
								$errstr = $line;
							}
							$bossnodes{$boss}{errors} .= "Flag \'$1\' has no meaning if no connection info.\r";
						}
						foreach $fl ( @nomeaningflags ){
							if ( $flags =~ /\,($fl)/i ) {
								$flags =~ s/\,($fl)//i;
								if ( $line ne $errstr ) {
									$bossnodes{$boss}{errors} .= "$line\r";
									$errstr = $line;
								}
								$bossnodes{$boss}{errors} .= "Flag \'$1\' has no meaning if no connection info.\r";
							}
						}
						if ( $flags =~ /\,(T[a-x][a-x])\b/i ) {
							$flags =~ s/\,(T[a-x][a-x])\b//ig;
							if ( $line ne $errstr ) {
								$bossnodes{$boss}{errors} .= "$line\r";
								$errstr = $line;
							}
							$bossnodes{$boss}{errors} .= "Flag \'$1\' has no meaning if no connection info.\r";
						}
					} else {
						if ( $flags =~ /\,ICM/i ) {
							$flags =~ s/\,ICM/\,CM/i;
							if ( $line ne $errstr ) {
								$bossnodes{$boss}{errors} .= "$line\r";
								$errstr = $line;
							}
							$bossnodes{$boss}{errors} .= "Flag \'ICM\' not for ip only systems. It must be \'CM\' flag instead.\r";
						}
					}
				} else {
					foreach my $key ( keys %modemflags ) {
						if ( $flags =~ /\,$key\b/i && $modemflags{$key} ne '' ) {
							foreach my $impl ( split( /,/, $modemflags{$key} ) ) {
								if ( $flags =~ /\,$impl\b/i  ) {
									$flags =~ s/(\,$impl)\b//i;
									if ( $line ne $errstr ) {
										$bossnodes{$boss}{errors} .= "$line\r";
										$errstr = $line;
									}
									$bossnodes{$boss}{errors} .= "Flag $key implies \'$1\'.\r";
								}
							}
						}
					}
					unless ( defined( $baudrate{$baud} ) ) {
						if ( $line ne $errstr ) {
							$bossnodes{$boss}{errors} .= "$line\r";
							$errstr = $line;
						}
						$bossnodes{$boss}{errors} .= "Illegal baud rate \'$baud\'.\r";
						foreach my $br ( sort { $b <=> $a } keys %baudrate ) {
							if ( $baud > $br ) {
								$baud = $br;
								last;
							}
						}
						if ( $baud < 300 ) {
							$baud = 300;
						}
					}
					if ( $phone !~ /[\d\-]{3,29}/ ) {
						if ( $line ne $errstr ) {
							$bossnodes{$boss}{errors} .= "$line\r";
							$errstr = $line;
						}
						$bossnodes{$boss}{errors} .= "The phone number must be from 3 up to 29 digits and dashes, or the exact string \"-Unpublished-\".\rThe line is dropped!\r";
						undef $point;
					}
				}
				if ( $flags =~ /\,(T[a-x][a-x])\b/i && $flags =~ /\,CM\b/i ) {
					$flags =~ s/\,(T[a-x][a-x])\b//ig;
						if ( $line ne $errstr ) {
							$bossnodes{$boss}{errors} .= "$line\r";
							$errstr = $line;
						}
					$bossnodes{$boss}{errors} .= "Flag CM implies \'$1\'.\r";
				}
				if ( $flags =~ /\,([\!\#]\d\d)\b/ && $flags =~ /\,CM\b/i ) {
					$flags =~ s/\,([\!\#]\d\d)\b//g;
						if ( $line ne $errstr ) {
							$bossnodes{$boss}{errors} .= "$line\r";
							$errstr = $line;
						}
					$bossnodes{$boss}{errors} .= "Flag CM implies \'$1\'.\r";
				}
				if ( $flags =~ /\,(ICM)\b/ && $flags =~ /\,CM\b/i ) {
					$flags =~ s/\,(ICM)\b//g;
						if ( $line ne $errstr ) {
							$bossnodes{$boss}{errors} .= "$line\r";
							$errstr = $line;
						}
					$bossnodes{$boss}{errors} .= "Flag CM implies \'$1\'.\r";
				}
				foreach my $ipfl ( @ipflags ) {
					if ( $flags =~ /\,$ipfl\:?\d*/i && 
						$flags !~ /\,$ipfl\:[^\.]+[\.]+[^\.]+/i) {

						$flags =~ s/\,($ipfl\:?\d*)//i;
						if ( $line ne $errstr ) {
							$bossnodes{$boss}{errors} .= "$line\r";
							$errstr = $line;
						}
						$bossnodes{$boss}{errors} .= "Flag \'$1\' has no meaning if no INA flag.\r";
				    }
				}
				if ( $flags =~ /\,TCP\b/ ) {
					$flags =~ s/\,TCP\b/\,TCo/;
					if ( $line ne $errstr ) {
						$bossnodes{$boss}{errors} .= "$line\r";
						$errstr = $line;
					}
					$bossnodes{$boss}{errors} .= "Starting #169/21 the irregular use of a TCP flag Starting #169/21 the use of a TCP flag is prohibited.\r";
				}
				if ( $flags =~ /(.*?)\,U(\,.*)$/ ) {
					my ( $regflags, $uflags ) = ( $1, $2 );
					while ( $uflags =~ /(\,T[a-x][a-x])\b/i ){
						$regflags .= $1;
						if ( $line ne $errstr ) {
							$bossnodes{$boss}{errors} .= "$line\r";
							$errstr = $line;
						}
						$bossnodes{$boss}{errors} .= "Starting \#251/12 the System open hours flag Txy moves from userflag to a regular flag.\r";
						$uflags =~ s/$1//;
					}
					$flags = "$regflags\,U$uflags";
				}
				if ( $flags =~  /\,IP\b/ ) {
						if ( $line ne $errstr ) {
							$bossnodes{$boss}{errors} .= "$line\r";
							$errstr = $line;
						}
						$bossnodes{$boss}{errors} .= "IP flag denotes an unspecified protocol. Deprecated.\r";
					$flags =~  s/\,IP\b//;
				}
				foreach my $flg ( split( /,/, $flags ) ) {
					next if $flg eq '';
					unless ( knownflag( $flg ) ) {
						$flags =~ s/\,$flg//;
						if ( $line ne $errstr ) {
							$bossnodes{$boss}{errors} .= "$line\r";
							$errstr = $line;
						}
						$bossnodes{$boss}{errors} .= "Unknown flag \'$flg\'. Removed.\r";
					}
				}
				if ( $flags =~ /\,V90C/ && $flags =~ /\,V90S/ ) {
						$flags =~ s/\,V90C//;
						$flags =~ s/\,V90S//;
						if ( $line ne $errstr ) {
							$bossnodes{$boss}{errors} .= "$line\r";
							$errstr = $line;
						}
						$bossnodes{$boss}{errors} .= "Error: the V90C and V90S flags are mutually exclusive. Removed.\r";
				}
				if ( $flags =~ /\,X2C/ && $flags =~ /\,X2S/ ) {
						$flags =~ s/\,X2C//;
						$flags =~ s/\,X2S//;
						if ( $line ne $errstr ) {
							$bossnodes{$boss}{errors} .= "$line\r";
							$errstr = $line;
						}
						$bossnodes{$boss}{errors} .= "Error: the X2C and X2S flags are mutually exclusive. Removed.\r";
				}
				if ( $flags =~ /\,HST/ || $flags =~ /\,H14/ ||
						$flags =~ /\,H16/ || $flags =~ /\,X2S/ ||
						$flags =~ /\,X2C/ ) {
						if ( $flags =~ /\,ZYX/ || $flags =~ /\,Z19/ ) {
							$flags =~ s/\,Z[Y1][X9]//;
							$flags =~ s/\,H[S1][T46]//;
							$flags =~ s/\,X2[CS]//;
							if ( $line ne $errstr ) {
								$bossnodes{$boss}{errors} .= "$line\r";
								$errstr = $line;
							}
							$bossnodes{$boss}{errors} .= "Error: no modem has at the same time the US Robotics proprietary protocols and the ZyXEL ones. Removed.\r";
						}
				}
				if ( $flags =~ /\,X[ABCPRWX].*?\,X[ABCPRWX]/i ) {
					$flags =~ s/\,X[ABCPRWX]//gi;
					if ( $line ne $errstr ) {
						$bossnodes{$boss}{errors} .= "$line\r";
						$errstr = $line;
					}
					$bossnodes{$boss}{errors} .= "Error: File/Update Request Flags are mutually exclusive. Removed.\r";
				}
				$flags =~ s/\,$// if $flags  =~ /\,$/;
				$flags =~ s/\,U$// if $flags  =~ /\,U$/;
# --- flags --->
			} else {
				if ( defined( $boss ) ) {
					$bossnodes{$boss}{errors} .= "Invalid line: \'$line\'.\r";
#					writelog( "Invalid line: \'$line\'." );
				}
				next;
			}
			if ( defined( $boss ) && defined( $point ) ) {
				if ( $config{pointlistformat} eq 'pointplus' ) {
					$bossnodes{$boss}{points} .= "Point,$point,$system,".
												"$location,$sysop,".
								                "$phone,$baud$flags\n";
				} else {
 					$bossnodes{$boss}{points} .= ",$point,$system,$location," .
												"$sysop,$phone,$baud$flags\n";
				}
				undef $point;
			}
		}
		close( $FH );
		if ( defined( $boss ) && defined( $nodelist{$boss} ) ) {
			if ( $bossnodes{$boss}{errors} ne '' ) {
				writelog( $bossnodes{$boss}{errors} );
				$globals{msgtext} = $bossnodes{$boss}{errors};
				sendmsg( $config{sysopname}, $nodelist{$boss},
						$config{address}, $boss,
						'Errors in your point segment.',
						PVT+K_S+LOC ) if $config{sendwarnings} eq 'yes';
				$bossnodes{$boss}{errors} = '';
			} else {
				writelog( " No errors found." );
			}
		}
	} else {
		writelog( "Can't open $filename ($!)." );
		print STDERR "Can't open $filename ($!).\n";
	}
	
}

sub uu_encode($;$)
{

    my ( $filename, $mode ) = @_;
    my ( $uuestr, $bindata, $FUU );

    $mode ||= "644";
    if ( $filename =~ /.*[\\\/]([^\\\/]+)$/ ) {
       $uuestr = "\rbegin $mode $1\r";
    } else {
        writelog("Full path MUST be specified. $filename has no path.");
		print STDERR "Full path MUST be specified. $filename has no path.\n";
        return '';
    }
    if ( open( $FUU, $filename ) ) {
        binmode( $FUU, ':raw' );
        while ( read( $FUU, $bindata, 45 ) ) {
            $uuestr .= pack("u", $bindata);
#."\r";
        }
        close($FUU);
        $uuestr .= "end\r\r";
        return($uuestr);
    }
    else {
        writelog("Can't open \"$filename\"\: $!");
		print STDERR "Can't open \"$filename\"\: $!\n";
        return('');
    }
}

sub sendpointlist( $ )
{
	my ( $filename ) = @_;
	my ( $toname, $toaddress, $boxname );
	
	writelog( "Sending $filename by $config{sendpoinlistby}." );
	unless( defined( $config{sendpoinlistto} ) ) {
		writelog( "SendPoinlistTo not defined." );
		return;
	}
	if ( $config{sendpoinlistto} =~ /(.*?)\s+(\d+\:\d+\/\d+)/ ) {
		( $toname, $toaddress ) = ( $1, $2 );
		if ( $config{sendpoinlistby} eq 'netmail' ) {
			unless ( defined( $config{address} ) ) {
				writelog( "ERROR: your address must be defined." );
				return;
			}
			unless ( defined( $config{netmail} ) ) {
				writelog( "ERROR: netmail area must be defined." );
				return;
			}
			$globals{msgtext} = "\r   Pointlist of $globals{segmentname}\r";
			sendmsg( $config{sysopname}, $toname,$config{address}, $toaddress,
						$filename, PVT+K_S+LOC+ATT );
		} elsif ( $config{sendpoinlistby} eq 'uue' ) {
			unless ( defined( $config{address} ) ) {
				writelog( "ERROR: your address must be defined." );
				return;
			}
			unless ( defined( $config{netmail} ) ) {
				writelog( "ERROR: netmail area must be defined." );
				return;
			}
			$globals{msgtext} = uu_encode( $filename );
			unless( $globals{msgtext} eq '' ) {
				sendmsg( $config{sysopname}, $toname,$config{address}, 
						$toaddress, "pointlist $globals{segmentname}", 
						PVT+K_S+LOC );
			}
		} elsif ( $config{sendpoinlistby} eq 'brakebox' ) {
			unless( defined( $config{brakeboxes} ) ) {
				writelog( "BrakeBoxes must be defined." );
				return;
			}
			$boxname = $toaddress;
			$boxname =~ s/[\:\/]/\./g;
			$boxname = catdir( $config{brakeboxes}, "fidonet.$boxname.0.direct" );
			mktree( $boxname ) unless -e $boxname;
			copy( $filename, $boxname );
		}
		writelog( "Sending done." );
	} else {
		writelog( "ERROR: sendpoinlistto must be the Name and the 3D fidonet address." );
		return;
	}
}

sub nodesort
{   my ($az, $an, $af, $ap, $bz, $bn, $bf, $bp);
    if ($a =~ /(\d+):(\d+)\/(\d+)(?:\.(\d+))?$/)
    {
        ($az, $an, $af, $ap) = ($1, $2, $3, $4);
    }
    if ($b =~ /(\d+):(\d+)\/(\d+)(?:\.(\d+))?$/)
    {
        ($bz, $bn, $bf, $bp) = ($1, $2, $3, $4);
    }
    return ($az<=>$bz) || ( $an cmp $bn ) || ($af<=>$bf) || ($ap<=>$bp);
}

sub pointsort
{
	my ( $ap, $bp );
	if ( $a =~ /^.*?,(\d+),.*/i) {
		$ap = $1;
	}
	if ( $b =~ /^.*?,(\d+),.*/i) {
		$bp = $1;
	}
	return ( $ap <=> $bp );
}

sub createpntlist()
{
	my ( $FH, $pntlsttext, $crc );
	my @abbr = qw(January February March April May June July August September October November December);
	my @wdaray = qw(Sunday Monday Tuesday Wednesday Thursday Friday Saturday);
	my ($sec,$min,$hour,$mday,$mon,$year,$wday,$yday,$isdst) = localtime();
	$year = $year + 1900;
	$yday++;
	my $daynumber = sprintf("%03d", $yday );

	writelog( "Building pointlist $globals{segmentname} for $wdaray[$wday], $abbr[$mon] $mday, $year -- Day number $daynumber." );
	if ( open( $FH, '>', "$config{pointlist}.$daynumber"  ) ) {
		$pntlsttext = ";S Created by New Point Keeper $vers.\n".
					  ";S Checked against nodelist $globals{nodelistldate}\n";
		$pntlsttext .= readfile( $config{header} ) if defined $config{header};
		foreach my $boss ( sort nodesort keys %bossnodes ) {
			next unless defined $nodelist{$boss};
			next if $bossnodes{$boss}{points} eq '';
			$pntlsttext .= "\;\nBoss,$boss\n";
			foreach my $pnt ( sort pointsort split( /\n/, $bossnodes{$boss}{points} ) ) {
				$pntlsttext .= "$pnt\n";
			}
		}
		$crc = sprintf( "%05d", crc16( $pntlsttext ) );
		$pntlsttext = ";A Poinlist of $globals{segmentname} for $wdaray[$wday], $abbr[$mon] $mday, $year -- Day number $daynumber : $crc\n$pntlsttext";
		print $FH $pntlsttext;
		close( $FH )
	} else {
		print STDERR "Can't open $config{pointlist} ($!).\n";
		writelog( "Can't open $config{pointlist} ($!)." );
	}
	writelog( "Building pointlist $config{pointlist}\.$daynumber done." );
	sendpointlist( "$config{pointlist}\.$daynumber" ) if defined $config{sendpoinlistby};
}

sub readworkdir()
{
	my ( $DH, $workfile );

	if ( opendir( $DH, $config{workdir} ) ) {
		writelog( "Reading work dir $config{workdir}" );
		while( readdir( $DH ) ) {
			if ( $_ =~ /^$config{segfilename}$/i ) {
				$workfile = catfile( $config{workdir}, $_ );
				readseg( $workfile );
			}
		}
		close( $DH );
		writelog( "Reading work dir done." );
		createpntlist();
# -- writeout seg ---
	}
}

sub readinbound( $ )
{
	my ( $inbound ) = @_;
	my ( $DH, $workfile, $inbfile, $backup, $found, $name, $ext, $workfiletime,
		$zip, $status, @fnames, $fname, $inbfiletime, $archname, $dirpos, $tic );

	if ( opendir( $DH, $inbound ) ) {
		$dirpos = telldir( $DH );
		writelog( "Reading protected inbound $inbound" );
		print "Reading protected inbound $inbound...\n";
		while( readdir( $DH ) ) {
			next unless $_ =~ /\.tic$/i;
			$tic = readfile( catfile( $inbound, $_ ) );
			$config{delzip} = 'no' if $tic =~ /$config{segfilename}/i;
		}
		seekdir( $DH, $dirpos );
		while( readdir( $DH ) ) {
			if ( $_ =~ /^$config{segfilename}$/i ) {
				writelog( "File $_ found." );
				next unless $_ =~ /(.+?)\.(.{3})/;
				( $name, $ext ) = ( $1, $2 );

				$workfile = catfile( $config{workdir}, "$name\.999" );
				$inbfile = catfile( $inbound, $_ );
				if ( $ext =~ /zip/i || $ext =~ /z\d\d/i ) {
					$archname = $inbfile;
					writelog( "   Unzip $_." );
					$zip = Archive::Zip->new();
					if ( -s $archname == 0 ) {
						writelog( "Deleting zero sized \'$archname\'." );
						writelog( "Error! Can't delete \'$archname\'." ) unless unlink $archname;
						next;
					}
					$status  = $zip->read( $archname );
					if ( $status != AZ_OK ) {
						move( $archname, "$archname\.bad" );
						writelog( "Read of $archname failed.");
						next;
					}
#					( @fnames ) = $zip->membersMatching( "\.[Pp][Kk][Tt]" );
					@fnames = $zip->memberNames();
					foreach $fname ( @fnames ) {
						if ( $fname =~ /^$config{segfilename}$/i ) {
							writelog( "Extracting $fname" );
							$inbfile = catfile( $config{unzipto}, $fname );
							$zip->extractMemberWithoutPaths( $fname, $inbfile );
							last;
						}
					}
					unlink $archname unless $config{delzip} eq 'no';
#					$inbfile = catfile( $inbound, $fname );
					writelog( "Now processing $inbfile." );
				}
				if ( -e $workfile ) {
					$workfiletime = read_pnt_time( $workfile );
					$inbfiletime = read_pnt_time( $inbfile );
					if( $workfiletime <= $inbfiletime || $inbfiletime == 0 ) {
						$backup = catdir( $config{backupdir}, $globals{backdir} );
						mkdir( $backup ) unless -e $backup;
						copy( $workfile, $backup );
						copy( $inbfile, $workfile );
						writelog( "File $inbfile copied to $config{workdir}." );
					}
				} else {
					copy( $inbfile, $workfile );
					writelog( "File $inbfile copied to $config{workdir}." );
				}
				if( unlink( $inbfile ) ) {
					writelog( "File $inbfile deleted." );
				} else {
					writelog( "Can't delete $inbfile ($!)." );
				}
				$found = 1;
			}
		}
		closedir( $DH );
	} else {
		writelog( "Can't open $inbound ($!)." );
		print STDERR "Can't open $inbound ($!).\n";
		exit;
	}
#	readworkdir() if $found;
}

sub exportcfg()
{
	my ( $key );
#	print "----------config------------\n";
	foreach $key ( keys %config ) {
		print "$key = $config{$key}\n";
	}
#	print "----------regions------------\n";
#	foreach $key ( keys %regions ) {
#		print "$key = $regions{$key}\n";
#	}
#	print "----------nets------------\n";
#	foreach $key ( keys %nets ) {
#		print "$key = $nets{$key}\n";
#	}
	exit;
}

# --- MAIN ---

GetOptions (
            "config=s"    => \$config,
            "help"        => \$needhelp,
            "ver"         => \$prinver,
            "whatsnew"    => \$whatsnew,
            "only-errors"  => \$errorsonly,
            "export"      => \$export,
            "update=s"    => \$check_updates,
            "log=s"       => \$logfile)  # string
or die("Error in command line arguments\n");

	$check_updates = 'w' unless defined $check_updates;
	$check_updates = lc( $check_updates );

	if( $prinver ) {
		print "$0 $vers\n";
		update();
		exit;
	}

	whats_new() if $whatsnew;

	if ( $check_updates ne 'f' ) {
		usage() if $needhelp;
		usage() unless( defined( $config ) );
	}

	update();

	readcfg( $config );

	readndl( findndl( $config{nodelist} ) );

	exportcfg() if $export;

	readinbound( $config{inbound} ) if defined $config{inbound};

	scannetmail() if $config{scannetmail} eq 'yes';

	readworkdir();

