import sys, string, gts, subprocess
import scipy.spatial as sp
import numpy as np

def main(surf,offset):
    nsurf = string.replace(surf,'.stl','.gts')
    subprocess.call('stl2gts < '+surf+' > '+nsurf, shell=True)
    fid = open(nsurf,'r')
    s = gts.read(fid)
    fid.close()
    
    verts = s.vertices()
    qverts = np.zeros((len(verts),3),float)
    for i in xrange(len(verts)):
        v = verts[i]
        qverts[i,0] = v.x
        qverts[i,1] = v.y
        qverts[i,2] = v.z
    hull = sp.qhull.Delaunay(qverts).convex_hull
    write_stl(qverts,hull,string.replace(surf,'.stl','_hull.stl'))
    
def write_stl(v,f,output):
    fid = open(output,'w')
    fid.write('solid chull\n')
    
    N = np.shape(f)[0]
    for i in xrange(N):
        v1 = v[f[i,0],:]
        v2 = v[f[i,1],:]
        v3 = v[f[i,2],:]
        e1 = v2-v1
        e2 = v3-v1
        normal = np.cross(e1,e2)
        fid.write('\tfacet normal '+str(normal[0])+' '+str(normal[1])+' '+str(normal[2])+'\n')
        fid.write('\t\touter loop\n')
        fid.write('\t\t\tvertex '+str(v1[0])+' '+str(v1[1])+' '+str(v1[2])+'\n')
        fid.write('\t\t\tvertex '+str(v2[0])+' '+str(v2[1])+' '+str(v2[2])+'\n')
        fid.write('\t\t\tvertex '+str(v3[0])+' '+str(v3[1])+' '+str(v3[2])+'\n')
        fid.write('\t\tendloop\n\tendfacet\n')   
    fid.close()
    
    


if __name__ == '__main__':
    main(sys.argv[-2],sys.argv[-1])
