#!/usr/bin/env python
#
from __future__ import print_function
from vedo.io import load, write
from vedo.utils import humansort
from vedo import printc
import sys, argparse

allowedexts = ['vtk', 'vtp', 'vtu', 'vts', 'npy', 'ply', 'stl', 'obj',
               'byu', 'xml', 'vti','tif','mhd','xml']

pr = argparse.ArgumentParser(description="Allowed targets: "+str(allowedexts))
pr.add_argument('files', nargs='*', help="Input filename(s)")
pr.add_argument("-n", "--normalize",help="normalize target size", action="store_true")
pr.add_argument("-c", "--clean",    help="remove coincident points", action="store_true")
pr.add_argument("-m", "--mirror",   help="mirror along the x-axis", action="store_true")
pr.add_argument("-b", "--binary",   help="whether output is binary or not", action="store_true")
pr.add_argument("-t", "--triangle", help="Convert polygons to triangles", action="store_true")
pr.add_argument("-to", type=str,    help="target format [vtk]", default='vtk', metavar='')
args = pr.parse_args()

humansort(args.files)
nfiles = len(args.files)
if nfiles == 0:
    sys.exit()

target_ext = args.to.lower()

if target_ext not in allowedexts:
    printc('Sorry target cannot be', target_ext, '\nMust be', allowedexts, c=1)
    sys.exit()

for f in args.files:
    source_ext = f.split('.')[-1]

    if target_ext == source_ext:
        continue

    a = load(f)
    if args.normalize:
        a.normalize()
    if args.triangle:
        a.triangle()
    if args.clean:
        a.clean()
    if args.mirror:
        a.mirror()

    newf = f.replace("."+source_ext,"")+"."+target_ext
    write(a, newf, binary=args.binary)
