#!/usr/bin/perl
use strict;
use warnings;
use utf8;
use Encode qw(decode_utf8);
use File::Basename qw(basename);                                             
use Getopt::Long qw(:config posix_default gnu_compat permute bundling no_ignore_case);
use Unicode::UCD qw(charprop);                                               

use open IO => ":encoding(UTF-8)";
binmode STDIN, ":encoding(UTF-8)";
binmode STDOUT, ":encoding(UTF-8)";
binmode STDERR, ":encoding(UTF-8)";

my $cmd_name  = basename($0);
my $cmd_usage = <<EOL;
usage: $cmd_name [<option(s)>] [<file(s)>]
line up text.

options:
  -c, --count=COUNT     separate lines only COUNT times
  -i, --keep-indent     keep the first indent as indents
  -m, --margin=N        put N spaces between cells
  -p, --pack-separator  pack separator cells and non-separator cells
  -s, --separator=SEP   separate lines by SEP
      --help            print usage and exit
EOL

sub print_error_and_abort {
    my ($error) = @_;
    chomp $error;
    print STDERR "$cmd_name: $error\n";
    exit 1;
}

sub read_lines_from_argf {
    my $lines = [];
    while (my $line = <>) {
        chomp $line;
        push @$lines, $line;
    }
    return $lines;
}

my $eawidth_ch_memo = {};
sub eawidth_ch {
    my ($ch) = @_;
    if (exists($eawidth_ch_memo->{$ch})) {
        return $eawidth_ch_memo->{$ch};
    }
    my $width;
    my $type = charprop(ord($ch), "East_Asian_Width");
    if ($type eq "Fullwidth" || $type eq "Wide" || $type eq "Ambiguous") {
        $width = 2;
    } else {
        $width = 1;
    }
    $eawidth_ch_memo->{$ch} = $width;
    return $width;
}

sub eawidth {
    my ($text) = @_;
    my $width = 0;
    for my $ch (split(//, $text)) {
        $width += eawidth_ch($ch);
    }
    return $width;
}

sub line_up_lines {
    my ($lines, $count, $keep_indent, $margin, $pack_separator, $separator) = @_;
    my $margin_spaces     = " " x $margin;
    my $separator_pattern = qr/\s+/;
    if (defined($separator)) {
        $separator_pattern = qr/\s*(?=@{[quotemeta($separator)]})|(?<=@{[quotemeta($separator)]})\s*/;
    }

    my $cells              = [];
    my $first_indent       = "";
    my $first_indent_found = 0;
    for my $line (@$lines) {
        my $line_trimed = $line =~ s/^\s+|\s+$//gr;
        my $row         = [split($separator_pattern, $line_trimed, $count+1)];
        if ($pack_separator && defined($separator)) {
            my $row_packed = [];
            for my $cell (@$row) {
                if ($cell =~ $separator_pattern && @$row_packed >= 1) {
                    $row_packed->[$#$row_packed] .= $cell;
                } else {
                    push @$row_packed, $cell;
                }
            }
            push @$cells, $row_packed;
        } else {
            push @$cells, $row;
        }
        if ($keep_indent && !$first_indent_found) {
            $first_indent       = $line =~ s/^(\s*).*/$1/r;
            $first_indent_found = 1;
        }
    }

    my $widthes     = {};
    my $max_widthes = {};
    for (my $y = 0; $y < @$cells; $y++) {
        $widthes->{$y} = {};
        for (my $x = 0; $x < @{$cells->[$y]}; $x++) {
            my $cell  = $cells->[$y][$x];
            my $width = eawidth($cell);
            $widthes->{$y}{$x} = $width;
            if (!exists($max_widthes->{$x}) || $width > $max_widthes->{$x}) {
                $max_widthes->{$x} = $width;
            }
        }
    }

    my $cells2 = [];
    for (my $y = 0; $y < @$cells; $y++) {
        push @$cells2, [];
        for (my $x = 0; $x < @{$cells->[$y]}; $x++) {
            my $cell      = $cells->[$y][$x];
            my $width     = $widthes->{$y}{$x};
            my $max_width = $max_widthes->{$x};
            my $cell2     = $cell . " " x ($max_width - $width);
            push @{$cells2->[$y]}, $cell2;
        }
    }

    my $lines2 = [];
    for my $row2 (@$cells2) {
        my $line2 = join($margin_spaces, @$row2) =~ s/\s*$//r;
        if ($keep_indent) {
            $line2 = $first_indent . $line2;
        }
        push @$lines2, $line2;
    }

    return $lines2;
}

sub dump_lines {
    my ($lines) = @_;
    for my $line (@$lines) {
        print "$line\n";
    }
}

sub main {
    local $SIG{__WARN__} = \&print_error_and_abort;

    my $count          = -1;
    my $keep_indent    = 0;
    my $margin         = 1;
    my $pack_separator = 0;
    my $separator      = undef;
    my $is_help        = 0;
    foreach (@ARGV) {
        $_ = decode_utf8($_);
    }
    GetOptions(
        "c|count=i"        => \$count,
        "i|keep-indent"    => \$keep_indent,
        "m|margin=i"       => \$margin,
        "p|pack-separator" => \$pack_separator,
        "s|separator=s"    => \$separator,
        "help"             => \$is_help,
    );
    if ($is_help) {
        print $cmd_usage;
        return;
    }

    eval {
        my $lines  = read_lines_from_argf();
        my $lines2 = line_up_lines($lines, $count, $keep_indent, $margin, $pack_separator, $separator);
        dump_lines($lines2);
    };
    if ($@) {
        print_error_and_abort($@);
    }
}
main;
