#!/usr/bin/perl

eval 'exec /usr/bin/perl  -S $0 ${1+"$@"}'
    if 0; # not running under some shell

eval 'exec /usr/bin/perl  -S $0 ${1+"$@"}'
    if 0; # not running under some shell
#
#  This code was developped by SECIOSS (http://www.secioss.co.jp/).
#
#                 Copyright (C) 2007 SECIOSS CORPORATION
#
#  This program is free software; you can redistribute it and/or
#  modify it under the terms of the GNU Lesser General Public License
#  as published by the Free Software Foundation.

use strict;
use Time::Local;
use Time::HiRes qw(gettimeofday);
use POSIX;
use Encode;
use Data::Dumper;

sub date2time
{
    my ($date) = @_;

    if (!defined($date)) {
        return time;
    }

    my ($year, $mon, $day, $hour, $min, $sec) = ($date =~ /^([0-9]{4})([0-9]{2})([0-9]{2})([0-9]{2})([0-9]{2})([0-9]{2})Z/);

    my $time = timelocal($sec, $min, $hour, $day, $mon - 1, $year);

    return $time;
}

sub time2date
{
    my ($time) = @_;

    if (!defined($time)) {
        $time = time;
    }

    return strftime("%Y%m%d%H%M%S", localtime($time))."Z";
}

sub getValue
{
    my ($entryStr, $attr, $default) = @_;

    my $value = ($entryStr =~ /^$attr:\:? (.*)$/mi)[0];
    if (!defined($value) && $default) {
        $value = $default;
    }

    return $value;
}

sub getSureName
{
    my ($entryStr, $attr) = @_;
    my $regexp = "^$attr: ([^ 　,，\n]+)";
    $regexp = decode('utf8', $regexp);
    my $value = ($entryStr =~ /$regexp/mi)[0];

    return $value;
}

sub getGivenName
{
    my ($entryStr, $attr, $default) = @_;
    my $regexp = "^$attr: [^ 　,，\n]+[ 　,，]+([^\n]+)".'$';
    $regexp = decode('utf8', $regexp);
    my $value = ($entryStr =~ /$regexp/mi)[0];

    if ($value) {
        return $value;
    } else {
        return $default;
    }
}

sub getFileContents
{
    my ($file) = @_;
    my $contents = '';

    if (!-f $file) {
        return '';
    }

    open(FILE, "<$file") || return '';

    while (<FILE>) {
        $contents .= $_;
    }

    return $contents;
}

sub randString
{
    my $num = shift;
    my $string;
    my @chars;

    if ($num !~ /[0-9]/) {
        return undef;
    }

    foreach my $arg (@_) {
        if (my ($ch1, $ch2) = ($arg =~ /^['"]?(.?)['"]?\.\.['"]?(.?)['"]?/)) {
            push(@chars,($ch1..$ch2));
        } elsif (length($arg) == 1) {
            push(@chars, $arg);
        }
    }

    my ($sec, $microsec) = gettimeofday();
    srand($microsec);

    for (my $i = 0; $i < $num; $i++) {
        $string .= $chars[int(rand() * @chars)];
    }

    return $string;
}

sub regmatch
{
    my ($match, $str) = @_;

    my (@vals) = ($str =~ /$match/gi);
    if (!@vals) {
        $vals[0] = '';
    }

    return @vals;
}

1;
