#!/usr/bin/env python

"""
Refine a shape by subdividing the polygons
"""

import argparse
import time
import sys
import re

from icqsol.tools.geometry.icqShape import Shape
import vtk

# time stamp
tid = re.sub(r'\.', '', str(time.time()))

parser = argparse.ArgumentParser(description='Refine a shape.')

parser.add_argument('--input', dest='input', default='',
                    help='Input file (PLY or VTK)')

parser.add_argument('--refine', dest='refine', type=int,
                    help='Number of subdivisions')

parser.add_argument('--ascii', dest='ascii', action='store_true',
                    help='Save data in ASCII format (default is binary)')

parser.add_argument('--output', dest='output',
                    default='createCompositeShape-{0}.vtk'.format(tid),
                    help='Output file.')

args = parser.parse_args()

if args.refine <= 0:
    print 'ERROR: refine must be a positive, integer number: --refine #'
    sys.exit(2)

if not args.input:
    print 'ERROR: must specify input file: --input <file>'
    sys.exit(3)

shp = Shape.load(args.input)
pdata = shp.toVTKPolyData()
densifyFilter = vtk.vtkDensifyPolyData()
densifyFilter.SetNumberOfSubdivisions(args.refine)
if vtk.VTK_MAJOR_VERSION >= 6:
    densifyFilter.SetInputData(pdata)
else:
    densifyFilter.SetInput(pdata)
densifyFilter.Update()

outShape = Shape.fromVTKPolyData(densifyFilter.GetOutput())

if args.output:
    fileFormat = 'vtk'
    fileType = 'binary'
    if args.ascii:
        fileType = 'ascii'
    if args.output.lower().find('.ply') >= 0:
        fileFormat = 'ply'
    outShape.save(args.output, file_format=fileFormat,
                file_type=fileType)

@@ -1344,38 +1344,16 @@
 %0Aout
-Shape = Shape.fromVTKPolyData(
+Pdata = 
 dens
@@ -1373,17 +1373,16 @@
 Output()
-)
 %0A%0Aif arg
@@ -1399,257 +1399,404 @@
     
-fileFormat
+writer
  = 
-'
 vtk
-'%0A    fileType = 'binary'%0A    if args.ascii:%0A        fileType = 'ascii'%0A    if args.output.lower().find('.ply') %3E= 0:%0A        fileFormat = 'ply'%0A    outShape.save(args.output, file_format=fileFormat,%0A                file_type=fileType)%0A
+.vtkPolyDataWriter()%0A    if args.output.lower().find('.ply') %3E= 0:%0A        writer = vtk.vtk.PolyDataWriter()%0A    writer.SetFileName(args.output)%0A    writer.SetFileTypeToBinary()%0A    if args.ascii:%0A        writer.SetFileTypeToASCII()%0A    if vtk.VTK_MAJOR_VERSION %3E= 6:%0A        writer.SetInputData(outPdata)%0A    else:%0A        writer.SetInput(outPdata)%0A    writer.Write()%0A    writer.Update()

save geometry and field