# CCHE2D mesh to SSIIM mesh --Clemens Dorfmann--

#----------------------------------------------------------------------
# Give here the filenames for Input and Output files:

Input_file = 'Fisching_aus_BK_400p_498x20.geo'
Output_file = 'koordina'

#----------------------------------------------------------------------

# Write SSIIM control file?:

control_file = True         # control_file  = True: write control file
                            #               = False: do not write control file

ZL = 6                      # Number of vertical layers (grid lines)
Roughness = 50              # Strickler roughness value [m^1/3/s]
Q = 120                     # Discharge [m^3/s]
WaterLevel = 685            # Water surface elevation [m]

#----------------------------------------------------------------------

# read CCHE2D geo mesh file
CCHE2D_file = open(Input_file, 'r')
CC_text = CCHE2D_file.readlines()
CCHE2D_file.close()

# initialisation of some empty lists
line_ij = []
liste_x_CC = []
liste_y_CC = []
liste_z_CC = []
liste_x_SS = []
liste_y_SS = []
liste_z_SS = []
liste_i = []
liste_j = []

# get i (streamwise node number) and j (crosswise node number) from first line
line_ij.append(CC_text[0].split())
i = int(line_ij[0][1])
j = int(line_ij[0][0])

CC_text.pop(0)

# read x y z values into lists and sort
for lines in CC_text:
    CC_text = lines.split()
    liste_x_CC.append(float(CC_text[0]))
    liste_y_CC.append(float(CC_text[1]))
    liste_z_CC.append(float(CC_text[3]))

for k in range(j, i*j+j, j):
    liste_x_SS += reversed(liste_x_CC[k-j:k])
    liste_y_SS += reversed(liste_y_CC[k-j:k])
    liste_z_SS += reversed(liste_z_CC[k-j:k])

# i and j node numbering for SSIIM
for k in range(1, i+1):
	liste_i += [k] * j

liste_j += range(1, j+1) * i

# write to SSIIM koordina file
SSIIM_file= open(Output_file, 'w')

for k in range(i*j):
    SSIIM_file.write(str(liste_i[k]) + ' ' + str(liste_j[k]) + ' ' + str(liste_x_SS[k]) + \
            ' ' + str(liste_y_SS[k]) + ' ' + str(liste_z_SS[k]) + '\n')

SSIIM_file.close()

# write SSIIM control file
if control_file == True:
    liste_zl =[]
    for k in range(0, ZL):
        liste_zl += [round(k * 100.0/(ZL-1), 6)]
    liste_zl = str(liste_zl).replace(',', '').strip('[' ']')

    SSIIM_control_f= open('control', 'w')
    SSIIM_control_f.write('T                                title field' + '\n' \
                    + 'G 1 ' + str(i) + ' ' + str(j) + ' ' + str(ZL) + ' 1     grid and array sizes' + '\n' \
                    + 'G 3 ' + liste_zl + '      vertical grid distribution' + '\n' \
                    + 'W 1 ' + str(float(Roughness)) + ' ' + str(float(Q)) + ' ' + str(float(WaterLevel)) + '\n' \
                    + 'W 2 3 1 ' + str(int(i/2)) + ' ' + str(i) + '\n' \
                    + 'K 1 40000 60000' + '\n' \
                    + 'K 2 0 1' + '\n')
    SSIIM_control_f.close()



