import gts, sys, string, subprocess, os
import numpy as np

def main(cfile,offset):
    fid = open(cfile,'r')
    surf_files = map(string.rstrip,fid.readlines())
    fid.close()
    for surf_file in surf_files:
        nfile = string.replace(surf_file,'.stl','.gts')
        subprocess.call('stl2gts < '+surf_file+' > '+nfile, shell=True)
        fid = open(nfile,'r')
        s = gts.read(fid)
        fid.close()
        os.remove(nfile)
        vert = s.vertices()
        offsets = []
        for v in vert:
            tri = v.faces()
            an = np.zeros((1,3),float)
            cnt = 0
            for t in tri:
                n = np.array(t.normal())
                n = n/np.linalg.norm(n)
                an = an + n
                cnt += 1
            
            an = an/float(cnt)
            an = an/np.linalg.norm(an)
            offsets.append(float(offset)*an)
        cnt = 0
        for v in vert:
            v.translate(offsets[cnt][0,0],offsets[cnt][0,1],offsets[cnt][0,2])
            cnt += 1
        oname =  nfile.replace('.gts','_offset.gts')   
        fid = open(oname,'w')
        s.write(fid)
        fid.close()
        subprocess.call('gts2stl < '+oname+' > '+string.replace(oname,'.gts','.stl'),shell=True)
        os.remove(oname)
            
        
    
    
if __name__ == "__main__":
    main(sys.argv[-2],sys.argv[-1])
