#!/usr/bin/python
"""2dreantrantcorner-generator.py -- generate a mesh for the reentrant corner

SYNOPSIS:
./2dreantrantcorner-generator.py [-s] [-t TRIANGLE_OPTS] NODES OPENING  

PARAMETERS:
-s  Call showme on the generated mesh

NODES Number of nodes on the circumference

OPENING the opening angle in degrees
"""

from math import pi, cos, sin
from os import system, chdir
from shutil import rmtree
from sys import argv, stderr, stdout
from tempfile import mkdtemp


showme = False
triangle_opts = ""
params = []
i = 1
while i < len(argv):
    if argv[i] == "-s":
        showme = True
    elif argv[i] == "-t":
        i+=1
        triangle_opts = argv[i]
    elif argv[i][0:2] == "-t":
        triangle_opts = argv[i][2:]
    elif argv[i][0] == "-":
        print __doc__
        exit(1)
    else:
        params += [argv[i]]
    i+=1

if(len(params) != 2):
    print __doc__
    exit(1)

nodes = int(params[0])
angle = float(params[1])/360*2*pi

dir = mkdtemp()
chdir(dir)
stderr.write("Using Temporary directory %s\n" % dir)

poly = file("mesh.poly", "w")
#First line:  <# of vertices> <dimension (must be 2)> <# of attributes> <# of boundary markers (0 or 1)>
poly.write("%d 2 0 0\n" % (nodes+1))
#Following lines:  <vertex #> <x> <y> [attributes] [boundary marker]
for i in range(nodes):
    used = 2*pi - angle
    piece_angle = used / (nodes-1)
    my_theta = piece_angle * i
    x = cos(my_theta)
    y = sin(my_theta)
    poly.write("%d %.17g %.17g\n" % (i, x, y))
poly.write("%d 0 0\n" % nodes)
#One line:  <# of segments> <# of boundary markers (0 or 1)>
poly.write("%d 0\n" % (nodes+1))
#Following lines:  <segment #> <endpoint> <endpoint> [boundary marker]
for i in range(nodes+1):
    poly.write("%d %g %g\n" % (i, i, (i+1)%(nodes+1)))
#One line:  <# of holes>
poly.write("0\n")
#Following lines:  <hole #> <x> <y>
#Optional line:  <# of regional attributes and/or area constraints>
#Optional following lines:  <region #> <x> <y> <attribute> <max area>
poly.close()

system("triangle -p %s mesh.poly 1>&2" % triangle_opts)

if showme:
    system("showme mesh.1.ele 1>&2")

stdout.write("DGF\n")
stdout.write("%% generated by %s\n" % " ".join(argv))

node = file("mesh.1.node")
nodes = node.readline().split()[0];
stdout.write("Vertex\n")
for i in range(int(nodes)):
    (x, y) = node.readline().split()[1:3]
    stdout.write("%s\t%s\n" % (x, y))
node.close()
stdout.write("#\n")

ele = file("mesh.1.ele")
elems = ele.readline().split()[0]
stdout.write("Simplex\n")
for i in range(int(elems)):
    nodes = ele.readline().split()[1:4]
    stdout.write("\t".join(nodes)+"\n")
ele.close()
stdout.write("#\n")

stdout.write("Boundarydomain\n")
stdout.write("default 1\n")
stdout.write("#\n")

rmtree(dir)
