#!/usr/bin/perl
use strict;

# Глобальные переменные
my $fileName;
my $isRemoveDuplicates = 0;
my $isSplitByDomens = 0;
my $excludeDomen;

parseCommandLine();
processFile();
exit 0;

# Парсер параметров командной строки
sub parseCommandLine {
	my $arg = shift(@ARGV);
	my $isHasArgs = 0;
	until ($arg eq '') {
		$isHasArgs = 1;
		if($arg =~ /^-{1,2}.+$/){
			if ($arg =~ /^-{1,2}version$/){
				about();
				exit 0;
			} elsif ($arg =~ /^-{1,2}help$/){
				help();
				exit 0;
			} elsif ($arg eq '--remove-duplicates'){
				$isRemoveDuplicates = 1;
			} elsif ($arg eq '--split-by-domens'){
				$isSplitByDomens = 1;
			} elsif ($arg =~ /--exclude-domen[=]{0,1}(\w*)/){
				$excludeDomen = $1;
				illegalUse() if $excludeDomen ne '' && $arg !~ /--exclude-domen=\w*/;
				$excludeDomen = shift(@ARGV) if $excludeDomen eq '';
				illegalUse() if $excludeDomen eq '';
			} else {
				illegalUse();
			}
		} else {
			illegalUse() if $fileName ne '';
			$fileName = $arg;
		}
		$arg = shift(@ARGV);
	};
	if (!$isHasArgs) {
		about();
		exit 0;
	}
}

# Вывод информации о программе
sub about {
	my $about = q {
E-mail filter tool for Aptech
version 0.1

Copyright 2011, David Veliev (gotoindvdum@gmail.com).

This program may be used under Apache License 2.0.
};
	
	print $about;
}

# Вывод доступных параметров командной строки
sub help {
	my $help = q {usage: }.$0. q { [KEYS] FILENAME [KEYS]

Parse for e-mails file FILENAME with arguments KEYS and print result to standart output stream.

Arguments:
    --help                      print this help
    --version                   print version and information about this script
    --remove-duplicates         remove e-mail duplicates
    --split-by-domens           split e-mails by domens
    --exclude-domen[=]DOMEN     exclude e-mails with domen DOMEN
};
	print $help;
}

# Неправильный формат параметров командной строки
sub illegalUse {
	print "Illegal use!\n\n";
	help();
	exit 1;	
}

# Обработка файла
sub processFile {
	open FILE, $fileName or die "Failed to open $fileName: $!\n";
	my @emails;
	while(<FILE>){
		my (@test) = $_ =~ /.*(\w@\w\.\w)*.*/;
		print @test; 
	}
	close FILE;
}