#!/usr/bin/env python3
import argparse
import xlsxwriter
import os
import re
import math

def get_number_or_not(s):
	# PEP-515
	if '_' in s:
		return s
	try:
		val = int(s)
		return val
	except ValueError:
		pass
	try:
		val = float(s)
		if math.isnan(val) or math.isinf(val):
			return s
		else:
			return val
	except ValueError:
		return s

parser = argparse.ArgumentParser(description='table2xlsx')
parser.add_argument('-t','--header', help='file with a header line')
parser.add_argument('-s','--separator', help='column separator', default='\t')
parser.add_argument('-o','--output', help='output xlsx', required=True)
parser.add_argument('inputs', metavar='file', help='input tables', nargs='+')
args = parser.parse_args()

header = None
if args.header:
	header = open(args.header).read().rstrip().split(args.separator)

workbook = xlsxwriter.Workbook(args.output)

for f in args.inputs:

	ws_name = os.path.basename(f)
	ws_name = re.sub(r'[\[\]:*?\/\\]+', '_', ws_name)
	ws_name = re.sub(r'\.[^\.]+$', '', ws_name) # remove extension if any
	ws_name = ws_name[:31] # truncate to 31 char max
	worksheet = workbook.add_worksheet(ws_name)

	row = 0
	if header:
		for col,d in enumerate(header):
			worksheet.write_string(row, col, d)
		row = 1
	for line in open(f):
		cols = line.rstrip().split(args.separator)
		for col,d in enumerate(cols):
			d = get_number_or_not(d)
			if isinstance(d, str):
				worksheet.write_string(row, col, d)
			else:
				worksheet.write(row, col, d)
		row += 1
workbook.close()
