#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# 
# The MIT License (MIT)

# Copyright (c) 2015 Thomas Lovén

# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:

# The above copyright notice and this permission notice shall be included in all
# copies or substantial portions of the Software.

# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
# SOFTWARE.

'Columnize text with ANSI escape codes'

from __future__ import print_function
import getopt
from os import path
import re
import sys

try:
    # Python 3
    from itertools import zip_longest
except ImportError:
    # Python 2
    from itertools import izip_longest as zip_longest

progname = path.basename(sys.argv[0])

def getlength(s):
    'Find length of a string, ignoring escape sequences'
    s = re.sub('\x1b\[[0-9;]*m', '', s)
    return len(s)

def usage():
    print('Columnize text with ANSI escape codes')
    print('usage:', progname, '[-s sep]')


try:
    opts,args = getopt.getopt(sys.argv[1:], 'ts:')
    opts = dict(opts)
except getopt.GetoptError as err:
    print(progname, ':', str(err))
    usage()
    sys.exit(2)

splitchar = opts.get('-s', '\t')

lines = []
lengths = []
# Read each line from stdin
for line in sys.stdin:
    cols = line.strip().split(splitchar)
    lines.append(cols)
    # Calculate the widths of each column
    width = [getlength(col) for col in cols]
    # Save the longest columns' lengths
    lengths = map(max, zip_longest(lengths, width, fillvalue=0))

lengths = list(lengths)
for line in lines:
    thisline = ''
    for i,col in enumerate(line):
        spaces = ' '*(lengths[i]-getlength(col)+1)
        thisline += col + spaces
    print(thisline.rstrip())
