#
# Copyright © 2020 MSC.Software Corporation
#  
# Permission to use Scripts
#  
# Permission is granted to MSC.Software customers with valid licenses of the MSC Apex™ software 
# to use script files posted on this page (collectively “Scripts”) solely for customers’ own authorized 
# internal use in conjunction with licensed use of the MSC Apex software.  
# No other use is permitted.  No license to MSC Apex or other software is granted under this Permission.
#  
# SCRIPTS ARE PROVIDED ON AN "AS-IS" BASIS, WITH NO WARRANTIES OF ANY KIND.  USE OF THE SCRIPTS IS AT CUSTOMER'S SOLE RISK.
#  
# IN NO EVENT SHALL MSC.SOFTWARE CORPORATION, ITS AFFILIATES, SUBSIDIARIES, SUPPLIERS, AGENTS, REPRESENTATIVES OR EMPLOYEES BE LIABLE FOR ANY 
# DIRECT, INDIRECT, INCIDENTAL, SPECIAL OR CONSEQUENTIAL DAMAGES HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, TORT, 
# STRICT LIABILITY, OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION USE OF THE SCRIPTS, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.  
#  
# Customer shall indemnify, defend and hold MSC.Software Corporation, its affiliates, subsidiaries, suppliers, agents, 
# employees or representatives (collectively, “Indemnified Parties”) harmless from and against any third-party claims 
# brought against Indemnified Parties rising out of or in connection with Customer’s use of the Scripts.
#
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# process: external
# 
# Macro Name =Apex 2 Aba 
# 
# Macro Description = Write Apaqus inout file by translating bdf from Apex Jaguar
# 
# Macro Hot Key =  
# 
# This script is not comeplte and not tested. DO not use for production
#

# !/usr/bin/env python
# -*- coding: utf-8 -*-

# ---------------------------------------------------------------------------
# TODO
# - support cbeam/pbeaml: Done
# - support more cross sections for pbarl/pbeaml: rod,tube,tube2,and bar supported
# - Find a way to support different element formulations, prototype done
# - support HEX20, PENTA15
# - support more loads, like PLOAD and SPCD: SPCD done
#
# Stefan Tynelius July 2020
# 
# - Added PBEAML T,L,I sections- offset "l" on T and I is assumed to be height and zero respeectively. Need to fix!!
# - Added support for real numbers without e
# - Adding flag eflaghex = 0 for CHEXA elements where parameter eflaghex to previously set
# - Return 0.0 from convert_real2 if a blank is passed as input (typically a material without density)
# 
# Magnus Andreasson, September 2020
#
# - Support for PLOAD on shells and solid elements
#
# Magnus Andreasson, December 2020
#
# - updated for python3.8
#
import time
import os
import shutil
from math import *
import traceback

import sys
# sys.path.append("./modules")

#
from utils import OccuranceCounter, convert_real2, process_ctetra, process_chexa, process_cquad4


def chunkstring(string, length):
    aa = []
    for i in range(0, len(string), length):
        if string[0 + i:length + i] != '        ':
            aa.append(string[0 + i:length + i])
    return aa


def Xprod(g1, g2, o):
    xAx = g2[0] - g1[0]
    xAy = g2[1] - g1[1]
    xAz = g2[2] - g1[2]

    #    xAx=g1[0]-g2[0]
    #    xAy=g1[1]-g2[1]
    #    xAz=g1[2]-g2[2]

    o1nA = xAy * o[2] - xAz * o[1]
    o2nA = xAz * o[0] - xAx * o[2]
    o3nA = xAx * o[1] - xAy * o[0]

    vlen = sqrt(o1nA * o1nA + o2nA * o2nA + o3nA * o3nA)
    o1n = o1nA / vlen
    o2n = o2nA / vlen
    o3n = o3nA / vlen

    return [o1n, o2n, o3n]


def freepen(pen, penFace, nod1, nod2, nod3, nod4, nod5, nod6, nod7, nod8, hexFace):
    nr_free = 0
    nr_found = 0
    face = 1
    freeFace = []
    while face < 6:
        found1 = 0
        found2 = 0
        nodes = penFace[pen, face]
        conEl1 = uniq3(
            nod1[nodes[0]] + nod2[nodes[0]] + nod3[nodes[0]] + nod4[nodes[0]] + nod5[nodes[0]] + nod6[nodes[0]] +
            nod1[nodes[1]] + nod2[nodes[1]] + nod3[nodes[1]] + nod4[nodes[1]] + nod5[nodes[1]] + nod6[nodes[1]] +
            nod1[nodes[2]] + nod2[nodes[2]] + nod3[nodes[2]] + nod4[nodes[2]] + nod5[nodes[2]] + nod6[nodes[2]] +
            nod1[nodes[3]] + nod2[nodes[3]] + nod3[nodes[3]] + nod4[nodes[3]] + nod5[nodes[3]] + nod6[nodes[3]])
        for connEl in conEl1:
            if connEl != pen:
                face2 = 1
                while face2 < 6:
                    try:
                        node1 = penFace[connEl, face2]
                        if node1[0] in nodes:
                            if node1[1] in nodes:
                                if node1[2] in nodes:
                                    if node1[3] in nodes:
                                        found1 = 1
                                        nr_found += 1
                                        break
                        face2 += 1
                    except:
                        break
                if found1 == 1:
                    break
                face2 = 1
                while face2 < 7:
                    try:
                        node2 = hexFace[connEl, face2]
                        if node2[0] in nodes:
                            if node2[1] in nodes:
                                if node2[2] in nodes:
                                    if node2[3] in nodes:
                                        found2 = 1
                                        nr_found += 1
                                        break
                        face2 += 1
                    except:
                        break
                if found2 == 1:
                    break
        if found1 == 0 and found2 == 0:
            #           print face
            freeFace.append(face)
            nr_free += 1
        face += 1
    return freeFace


def freetet(tet, tetFace, nod1, nod2, nod3, nod4):
    nr_free = 0
    nr_found = 0
    face = 1
    freeFace = []
    while face < 5:
        found = 0
        nodes = tetFace[tet, face]
        conEl1 = uniq3(
            nod1[nodes[0]] + nod2[nodes[0]] + nod3[nodes[0]] + nod4[nodes[0]] + nod1[nodes[1]] + nod2[nodes[1]] + nod3[
                nodes[1]] + nod4[nodes[1]] +
            nod1[nodes[2]] + nod2[nodes[2]] + nod3[nodes[2]] + nod4[nodes[2]])
        for connEl in conEl1:
            if connEl != tet:
                face2 = 1
                while face2 < 5:
                    try:
                        node1 = tetFace[connEl, face2]
                        if node1[0] in nodes:
                            if node1[1] in nodes:
                                if node1[2] in nodes:
                                    found = 1
                                    nr_found += 1
                                    break
                        face2 += 1
                    except:
                        break
                if found == 1:
                    break
        if found == 0:
            freeFace.append(face)
            nr_free += 1
        face += 1

    return freeFace


def freehex(hex1, hexFace, nod1, nod2, nod3, nod4, nod5, nod6, nod7, nod8, penFace):
    nr_free = 0
    nr_found = 0
    face = 1
    freeFace = []
    while face < 7:
        found1 = 0
        found2 = 0
        nodes = hexFace[hex1, face]
        conEl1 = uniq3(
            nod1[nodes[0]] + nod2[nodes[0]] + nod3[nodes[0]] + nod4[nodes[0]] + nod5[nodes[0]] + nod6[nodes[0]] + nod7[
                nodes[0]] + nod8[nodes[0]] +
            nod1[nodes[1]] + nod2[nodes[1]] + nod3[nodes[1]] + nod4[nodes[1]] + nod5[nodes[1]] + nod6[nodes[1]] + nod7[
                nodes[1]] + nod8[nodes[1]] +
            nod1[nodes[2]] + nod2[nodes[2]] + nod3[nodes[2]] + nod4[nodes[2]] + nod5[nodes[2]] + nod6[nodes[2]] + nod7[
                nodes[2]] + nod8[nodes[2]] +
            nod1[nodes[3]] + nod2[nodes[3]] + nod3[nodes[3]] + nod4[nodes[3]] + nod5[nodes[3]] + nod6[nodes[3]] + nod7[
                nodes[3]] + nod8[nodes[3]])
        for connEl in conEl1:
            if connEl != hex1:
                face2 = 1
                while face2 < 7:
                    try:
                        node1 = hexFace[connEl, face2]
                        if node1[0] in nodes:
                            if node1[1] in nodes:
                                if node1[2] in nodes:
                                    if node1[3] in nodes:
                                        found1 = 1
                                        nr_found += 1
                                        break
                        face2 += 1
                    except:
                        break
                if found1 == 1:
                    break
                face2 = 1
                while face2 < 6:
                    try:
                        node2 = penFace[connEl, face2]
                        if node2[0] in nodes:
                            if node2[1] in nodes:
                                if node2[2] in nodes:
                                    if node2[3] in nodes:
                                        found2 = 1
                                        nr_found += 1
                                        break
                        face2 += 1
                    except:
                        break
                if found2 == 1:
                    break
        if found1 == 0 and found2 == 0:
            #           print face
            freeFace.append(face)
            nr_free += 1
        face += 1
    return freeFace


def freeBolt(hex1, hexFace, botNodes):
    nr_free = 0
    nr_found = 0
    face = 1
    freeFace = []
    while face < 7:
        found1 = 0
        nodes = hexFace[hex1, face]
        for nod in nodes:
            if nod in botNodes:
                nr_found = nr_found + 1
        if nr_found == 4:
            freeFace.append(face)
            nr_free += 1
        face += 1
    return freeFace


def HexPress(hex1, hexFace, botNodes):
    nr_free = 0
    face = 1
    freeFace = []
    while face < 7:
        nr_found = 0
        nodes = hexFace[hex1, face]
        for nod in nodes:
            if nod in botNodes:
                nr_found = nr_found + 1
        if nr_found == 2:
            freeFace.append(face)
            nr_free += 1
        face += 1
    return freeFace


def PenPress(hex1, hexFace, botNodes):
    nr_free = 0
    face = 1
    freeFace = []
    while face < 6:
        nr_found = 0
        nodes = hexFace[hex1, face]
        if nodes[3] == nodes[0]:
            nodes[3] = 0
        for nod in nodes:
            if nod in botNodes:
                nr_found = nr_found + 1
        if nr_found == 1 and nodes[3] == 0 and (botNodes[0] == botNodes[1]):
            freeFace.append(face)
            nr_free += 1
        elif nr_found == 2:
            freeFace.append(face)
            nr_free += 1
        face += 1
    return freeFace


def TetPress(tet1, tetFace, botNodes):
    nr_free = 0
    face = 1
    freeFace = []
    while face < 5:
        nr_found = 0
        nodes = tetFace[tet1, face]
        if botNodes[0] in nodes and (botNodes[1] not in nodes):
            nr_found = 1
        if nr_found == 1:
            freeFace.append(face)
            nr_free += 1
        face += 1
    return freeFace


def uniq(inlist):
    # order preserving
    uniques = []
    for item in inlist:
        if item not in uniques:
            uniques.append(item)
    return uniques


def uniq3(seq):
    # Not order preserving
    set1 = set(seq)
    return list(set1)


def convert_real(val):
    # Makes sure that real values have an E in them where necessary before attempting float
    if '+' in val and 'E' not in val:
        tokens = val.split('+')
        valout = tokens[0] + 'E' + tokens[1]
    elif '-' in val and 'E' not in val:
        # -xxxx-xx
        if val.count('-') > 1:
            tokens = val.split('-')
            #            print(tokens)
            valout = '-' + tokens[1] + 'E-' + tokens[2]
        # -xxxx
        elif val.startswith('-'):
            valout = val
        # xxxx-xx
        else:
            tokens = val.split('-')
            valout = tokens[0] + 'E-' + tokens[1]
    else:
        valout = val

    return valout

def process_bdf_inp(bdf_file, SettingsD=None):
    try:
        if SettingsD['ABAQUS_EXPORT']['AbaqusSmallSliding'].upper() == "TRUE":
            small_sliding = 1
        else:
            small_sliding = 0
    except:
        small_sliding = 0

    try:
        if SettingsD['ABAQUS_EXPORT']['AbaqusBoltExist'].upper() == "TRUE":
            preStep = 1
            preOverLap = 0.01
            existBolt = 1
        else:
            preStep = 0
            preOverLap = 0.01
            existBolt = 0
    except:
        preStep = 0
        preOverLap = 0.01
        existBolt = 0

    sTime = time.time()
    # Abaqus small sliding, set this to 1
    # try read from settings
    # small_sliding=1
    # if bolt present, create initial overlap step
    # try read from settings
    # preStep=1
    # preOverLap=0.01
    # existBolt=0
    #
    nlgeom = 'NO'
    tieAll = 0
    gravflg = 0
    inf = open(bdf_file, 'r')
    # inl = inf.readlines()
    inl = inf.read().splitlines()
    inf.close()

    out_inp_file = bdf_file[:-3] + 'inp'
    outf = open(out_inp_file, 'w')
    outf.write('*HEADING\n')
    outf.write(' \n')
    cnt1 = 0
    bcb2p = {}
    midname = {}
    midEPname = {}
    # new dicts to allow reaqding all data before processing
    NodeDict = {}
    BoltDict = {}
    eqDict = {}
    TopList = set()
    BotList = []
    pBarDict = {}
    pSolDict = {}
    pShlDict = {}
    matDict = {}
    BoltCNlist = []
    stepList = []
    loadList = []
    spcList = []
    begBulk = 0
    LoadDict = {}
    SpcDict = {}
    tabDict = {}
    matInteg = {}
    spcAddFlg=0
    loadBlkFlg=0
    face_counter = OccuranceCounter()
    while cnt1 < len(inl):
        lin = inl[cnt1]
        if lin == '':
            lin = '$'
        cnt1 = cnt1 + 1
        if lin[0:7] == '$ Part ':
            partName = lin.split('\n')[0][7:].split('.')[0]
            if partName == '':
                partName = 'Anonymous'
        if 'BEGIN BULK' in lin:
            begBulk = 1
        elif lin[0:4] == 'GRID':
            xx1 = convert_real2(lin[24:32])
            yy1 = convert_real2(lin[32:40])
            zz1 = convert_real2(lin[40:48])
            NodeDict[int(lin[8:16])] = [xx1, yy1, zz1]
        elif lin[0:7] == 'BCBODY1':
            cbid = int(lin[8:16])
            bcb2p[cbid] = int(lin[40:48])
        elif lin[0:4] == 'BOLT':
            boId = int(lin[8:16])
            cnodId = int(lin[16:24])
            BoltCNlist.append(cnodId)
            tmp_str = inl[cnt1][16:72].replace('+', '')
            l8 = chunkstring(tmp_str, 8)
            while "BOTTOM" not in inl[cnt1 + 1]:
                l8.extend(chunkstring(inl[cnt1 + 1].replace('+       ', '').replace('+', ''), 8))
                cnt1 += 1
            topNodes = [int(i) for i in l8]
            cnt1 += 1
            tmp_str = inl[cnt1][16:72].replace('+', '')
            l8 = chunkstring(tmp_str, 8)
            while inl[cnt1 + 1].find("+") == 0:
                l8.extend(chunkstring(inl[cnt1 + 1].replace('+       ', '').replace('+', ''), 8))
                cnt1 += 1
            botNodes = [int(i) for i in l8]
            #            print(botNodes)
            for i in range(len(topNodes)):
                eqDict[topNodes[i]] = botNodes[i]
            BoltDict[boId] = [cnodId, topNodes, botNodes]
            TopList.update(topNodes)
            # BotList.extend(botNodes)
        elif lin.replace(' ', '')[0:4] == 'STEP' and begBulk == 0:
            currStep = int(lin.split()[1])
            stepList.append(currStep)
        elif lin.replace(' ', '')[0:4] == 'LOAD' and begBulk == 0:
            #print(lin)
            currLoad = int(lin.split('=')[1].strip())
            loadList.append(currLoad)
        elif lin.replace(' ','').find('SPC') == 0 and lin.find('SPCFORCES') < 0 and begBulk == 0:
            currSpc = int(lin.split('=')[1].strip())
            spcList.append(currSpc)
        elif 'LGDISP' in lin:
            if int(lin.replace(',', ' ').split()[2]) < 0:
                nlgeom = 'NO'
            else:
                nlgeom = 'YES'
        #            print('lgdisp',nlgeom)
        elif lin[0:4] == 'LOAD' and begBulk == 1:
            lid = int(lin[8:16])
            lList = []
            lsList = []
            loadBlkFlg=1
            oaScale = float(lin[16:24])
            tmp_str = lin[24:].replace('+', '')
            while inl[cnt1].find("+") == 0:
                tmp_str = tmp_str + inl[cnt1].replace('+       ', '').replace('+', '')
                cnt1 += 1
            tabStr = [tmp_str[i:i + 16] for i in range(0, len(tmp_str), 16)]
            #            print(tabStr)
            for item in tabStr:
                lsList.append(float(item[0:8]))
                lList.append(int(item[8:16]))
            LoadDict[lid] = [oaScale, lsList, lList]
        elif lin[0:6] == 'SPCADD' and begBulk == 1:
            lid = int(lin[8:16])
            sList = []
            spcAddFlg=1
            tmp_str = lin[16:].replace('+', '')
            while inl[cnt1].find("+") == 0:
                tmp_str = tmp_str + inl[cnt1].replace('+       ', '').replace('+', '')
                cnt1 += 1
            tabStr = [tmp_str[i:i + 8] for i in range(0, len(tmp_str), 8)]
            for item in tabStr:
                item = item.replace(' ', '')
                if item != '':
                    sList.append(int(item[0:8]))
            SpcDict[lid] = sList

        elif lin[0:4] == 'MAT1':
            descr = inl[cnt1 - 2]
            if 'Description' in descr:
                try:
                    intAba = descr.split('=')[1]
                except:
                    intAba = 'std'
            else:
                intAba = 'std'
            mName = 'MAT1_ID' + str(int(lin[8:16]))
            matInteg[int(lin[8:16])] = intAba
            midname[int(lin[8:16])] = mName
            # Stefan: change convert_real2 to return "0.0" if an emtpy string is passed (typically MAT w/o density)
            matDict[int(lin[8:16])] = [mName, convert_real2(lin[40:48]), convert_real2(lin[16:24]),
                                       convert_real2(lin[32:40])]

        elif lin[0:5] == 'MATEP':
            # Stefan: added try/except to catch issue with Perfectly Plastic Material
            mName = 'MAT1_ID' + str(int(lin[8:16]))
            try:
                midEPname[int(lin[8:16])] = [mName, int(lin[32:40])]
            except:
                midEPname[int(lin[8:16])] = [mName, ""]
        elif lin[0:7] == 'TABLES1':
            tabid = int(lin[8:16])
            lin = inl[cnt1]
            ListA = []
            ListB = []
            tmp_str = ''
            cnt1 = cnt1 - 1
            while inl[cnt1 + 1].find("+") == 0:
                tmp_str = tmp_str + inl[cnt1 + 1].replace('+       ', '').replace('+', '')
                cnt1 += 1
            tabStr = [tmp_str[i:i + 16] for i in range(0, len(tmp_str), 16)]
            for item in tabStr:
                if 'ENDT' not in item:
                    ListA.append(float(item[0:8]))
                    ListB.append(float(item[8:16]))
            tabDict[tabid] = ListA, ListB
        elif lin[0:5] == 'PBARL':
            outf.write('** ' + lin + '\n')
            cpid2 = int(lin[8:16])
            mpid = int(lin[16:24])
            sec = lin[32:40].replace(' ', '')
            lin = inl[cnt1]
            cnt1 = cnt1 + 1
            Dim1 = Dim2 = Dim3 = Dim4 = Dim5 = Dim6 = 0.0
            if sec == 'ROD':
                Dim1 = convert_real2(lin[8:16])
            elif sec == 'TUBE':
                Dim1 = convert_real2(lin[8:16])
                Dim2 = Dim1 - convert_real2(lin[16:24])
            elif sec == 'TUBE2':
                Dim1 = convert_real2(lin[8:16])
                Dim2 = convert_real2(lin[16:24])
            elif sec == 'BAR':
                Dim1 = convert_real2(lin[8:16])
                Dim2 = convert_real2(lin[16:24])
            # addded by Stefan T
            elif sec == 'I':
                Dim1 = convert_real2(lin[8:16])
                Dim2 = convert_real2(lin[16:24])
                Dim3 = convert_real2(lin[24:32])
                Dim4 = convert_real2(lin[32:40])
                Dim5 = convert_real2(lin[40:48])
                Dim6 = convert_real2(lin[48:56])
            elif sec == 'T':
                Dim1 = convert_real2(lin[8:16])
                Dim2 = convert_real2(lin[16:24])
                Dim3 = convert_real2(lin[24:32])
                Dim4 = convert_real2(lin[32:40])
            elif sec == 'L':
                Dim1 = convert_real2(lin[8:16])
                Dim2 = convert_real2(lin[16:24])
                Dim3 = convert_real2(lin[24:32])
                Dim4 = convert_real2(lin[32:40])

            pBarDict[cpid2] = [mpid, Dim1, Dim2, sec, Dim3, Dim4, Dim5, Dim6]
        elif lin[0:6] == 'PBEAML':
            outf.write('** ' + lin + '\n')
            cpid2 = int(lin[8:16])
            mpid = int(lin[16:24])
            sec = lin[32:40].replace(' ', '')
            lin = inl[cnt1]
            cnt1 = cnt1 + 1
            Dim1 = Dim2 = Dim3 = Dim4 = Dim5 = Dim6 = 0.0
            if sec == 'ROD':
                Dim1 = convert_real2(lin[8:16])
            elif sec == 'TUBE':
                Dim1 = convert_real2(lin[8:16])
                Dim2 = Dim1 - convert_real2(lin[16:24])
            elif sec == 'TUBE2':
                Dim1 = convert_real2(lin[8:16])
                Dim2 = convert_real2(lin[16:24])
            elif sec == 'BAR':
                Dim1 = convert_real2(lin[8:16])
                Dim2 = convert_real2(lin[16:24])
            # addded by Stefan T				
            elif sec == 'I':
                Dim1 = convert_real2(lin[8:16])
                Dim2 = convert_real2(lin[16:24])
                Dim3 = convert_real2(lin[24:32])
                Dim4 = convert_real2(lin[32:40])
                Dim5 = convert_real2(lin[40:48])
                Dim6 = convert_real2(lin[48:56])
            elif sec == 'T':
                Dim1 = convert_real2(lin[8:16])
                Dim2 = convert_real2(lin[16:24])
                Dim3 = convert_real2(lin[24:32])
                Dim4 = convert_real2(lin[32:40])
            elif sec == 'L':
                Dim1 = convert_real2(lin[8:16])
                Dim2 = convert_real2(lin[16:24])
                Dim3 = convert_real2(lin[24:32])
                Dim4 = convert_real2(lin[32:40])

            else:
                print(sec, " is not supported")
            pBarDict[cpid2] = [mpid, Dim1, Dim2, sec, Dim3, Dim4, Dim5, Dim6]
        #            print(pBarDict)
        elif lin[0:6] == 'PSHELL':
            outf.write('** ' + lin + '\n')
            cpid2 = int(lin[8:16])
            mpid = int(lin[16:24])
            psthick = convert_real2(lin[24:32])
            pShlDict[cpid2] = [mpid, psthick]
        elif lin[0:6] == 'PSOLID':
            outf.write('** ' + lin + '\n')
            cpid2 = int(lin[8:16])
            mpid = int(lin[16:24])
            pSolDict[cpid2] = [mpid]
    print('Time after pre-reading:' + str(time.time() - sTime) + '\n')
    #    print(matInteg)
    #    print(pSolDict)
    #    print(pShlDict)
    #    print(SpcDict)
    if spcAddFlg == 0 :
        for spId in spcList :
            SpcDict[spId]=[spId]
    if loadBlkFlg == 0 :
        for loId in loadList :
            LoadDict[loId]=[1.0,[1.0],[loId]]
    gflag = 0
    spcflg = 0
    spc1flg = 0
    spccnt = 0
    hexId = []
    hexFace = {}
    tetFace = {}
    tetId = []
    penFace = {}
    penId = []
    bcprg = {}
    bcong2p = {}
    load = {}
    spcs = {}
    eltype = {}
    pidname = {}
    pidOri = {}
    beamOri = {}
    BsurfDict = {}
    BoltElList = set()
    forceId = {}
    ploadId = {}
    spcdId = {}
    spcId = {}
    cnt1 = 0
    spcid = 0
    cpid = 0
    pressCnt = 0
    partName = 'Anonymous'
    sTime2 = time.time()
    printflag=1.0
    while cnt1 < len(inl):
        ratio=1.0*cnt1/len(inl)
        if ratio*20 >= (printflag-1.0E-20) :
          print('Translation: %i %% done, Time: %s , Delta Time: %s\n' %(int(ratio*100.0),str(time.time() - sTime),str(time.time() - sTime2)))
          sTime2 = time.time()
          printflag=printflag+1      
        lin = inl[cnt1]
        cnt1 = cnt1 + 1
        if (spcflg == 1 or spc1flg == 1) and spccnt != 0 and (lin[0:4] != 'SPC ' or lin[0:4] != 'SPC1'):
            outf.write('\n')
            spcflg = 0
            spc1flg = 0
        if lin[0:7] == '$ Part ':
            partName = 'P_' + lin.split('\n')[0][7:].split('.')[0]
            if partName == '':
                partName = 'Anonymous'
            outf.write('** ' + lin + '\n')
            gflag = 1
            eflagq = 1
            eflagbar = 1
            eflagbeam = 1
            eflagtri = 1
            eflagtet = 1
            eflagpen = 1
            eflaghex = 1
            eflagq8 = 1
            eflagt6 = 1
            spcid = 0
            cpid = 0
        elif lin[0:4] == 'GRID':
            gflag=process_grid(cnt1, gflag, inl, lin, outf)
        elif lin[0:4] == 'CBAR':
            cpid, eflagbar = process_cbar(NodeDict, beamOri, cpid, eflagbar, eltype, lin, outf, partName, pidOri,
                                          pidname)
        elif lin[0:5] == 'CBEAM':
            cpid, eflagbeam = process_cbeam(NodeDict, beamOri, cpid, eflagbeam, eltype, lin, outf, partName, pidOri,
                                            pidname)
        elif lin[0:6] == 'CQUAD4':
            cpid, eflagq ,out_strs = process_cquad4(cpid, eflagq, eltype, lin, matInteg, pShlDict, partName, pidname)
            for tmp in out_strs:
                outf.write(tmp)
        elif lin[0:6] == 'CQUAD8':
            cpid, eflagq8 = process_cquad8(cpid, eflagq8, eltype, lin, inl, matInteg, outf, pShlDict, partName, pidname, cnt1)
        elif lin[0:6] == 'CTRIA3':
            cpid, eflagtri = process_ctria3(cpid, eflagtri, eltype, lin, matInteg, outf, pShlDict, partName, pidname)
        elif lin[0:6] == 'CTRIA6':
            cpid, eflagt6 = process_ctria6(cpid, eflagt6, eltype, lin, matInteg, outf, pShlDict, partName, pidname)
        elif lin[0:6] == 'CTETRA':
            cnt1, cpid, eflagtet,out_strs, tId, nl = process_ctetra(BoltElList, TopList, cnt1, cpid, eflagtet, eltype, eqDict,
                                                  inl, lin, matInteg, pSolDict, partName, pidname, tetFace, tetId)

            face_counter.add(tId, 1, [nl[0], nl[2], nl[1]])
            face_counter.add(tId, 2, [nl[0], nl[1], nl[3]])
            face_counter.add(tId, 4, [nl[0], nl[3], nl[2]])
            face_counter.add(tId, 3, [nl[1], nl[2], nl[3]])
            for tmp in out_strs:
                outf.write(tmp)
        elif lin[0:6] == 'CPENTA':
            cpid, eflagpen = process_cpenta(BoltElList, TopList, cpid, eflagpen, eltype, eqDict, face_counter, lin, inl,
                                            outf,
                                            partName, penFace, penId, pidname, cnt1)
        elif lin[0:5] == 'CHEXA':
            cnt1, cpid, hId, out_strs, eflaghex, nl = process_chexa(BoltElList, TopList, cnt1, cpid, eflaghex, eltype, eqDict,
                                                      hexFace, hexId, inl, lin, matInteg, pSolDict, partName, pidname)
            face_counter.add(hId, 1, [nl[0], nl[3], nl[2], nl[1]])
            face_counter.add(hId, 3, [nl[0], nl[1], nl[5], nl[4]])
            face_counter.add(hId, 6, [nl[0], nl[4], nl[7], nl[3]])
            face_counter.add(hId, 4, [nl[1], nl[2], nl[6], nl[5]])
            face_counter.add(hId, 5, [nl[2], nl[3], nl[6], nl[7]])
            face_counter.add(hId, 2, [nl[4], nl[5], nl[6], nl[7]])
            for tmp in out_strs:
                outf.write(tmp)


        elif lin[0:4] == 'SPC ':
            spccnt, spcflg, spcid = process_spc(lin, outf, partName, spcId, spccnt, spcflg, spcid, spcs)
        elif lin[0:4] == 'SPC1':
            spc1flg, spccnt, spcid = process_spc1(BoltCNlist, lin, outf, partName, spc1flg, spcId, spccnt, spcid, spcs)
        #         print spccnt,spcflg
        elif lin[0:4] == 'RBE2':
            cnt1 = process_rbe2(cnt1, inl, lin, outf, partName)

        elif lin[0:5] == 'BSURF':
            cnt1 = process_bsurf(BsurfDict, cnt1, inl, lin)

        #      elif lin[0:5] == 'BSURF' :
        #    #      outf.write('** '+ lin)
        #           csid=int(lin[8:16])
        #           csList=[]
        #           cntbs=2
        #
        #           while (cntbs+1)*8 < len(lin) :
        #               tmp_cel=lin[(cntbs*8):((cntbs+1)*8)].replace('\n','').replace('+','')
        #               if tmp_cel.find("THRU") < 0:
        #                   # old format
        #                   try:
        #                       cel=int(tmp_cel)
        #                       csList.append(cel)
        #                   except:
        #                       #print("###",tmp_cel,"###")
        #                       #print(lin)
        #                       #print(csList[-1])
        #                       #return
        #                       pass
        #                   
        #               else:
        #                   print('new format')
        #                   print(lin)
        #                   start_id=csList[-1]
        #                   cntbs=cntbs+1
        #                   end_id=int(lin[(cntbs*8):((cntbs+1)*8)].replace('\n','').replace('+',''))
        #                   cntbs=cntbs+1
        #                   print(start_id,end_id)
        #                   # check if BY is used
        #                   if 1==1:
        #                       tmp_cel=lin[(cntbs*8):((cntbs+1)*8)].replace('\n','').replace('+','')
        #                       if tmp_cel.find("BY") > -1:
        #                           cntbs=cntbs+1
        #                           step=int(lin[(cntbs*8):((cntbs+1)*8)].replace('\n','').replace('+',''))
        #                       else:
        #                           step=1
        #                       for thru_id in range(start_id + 1,end_id + 1,step):
        #                           csList.append(thru_id)
        #
        #               cntbs=cntbs+1
        #           lin=inl[cnt1]
        #           cnt1=cnt1+1
        #           cntbs=1
        #
        #           while (lin[0:1] == '+') :
        #               cel=(lin[(cntbs*8):((cntbs+1)*8)]).replace('\n','')
        #               if cel != '' :
        #                   cel=int(cel)
        #                   csList.append(cel)
        #                   cntbs=cntbs+1
        #               else :
        #                   lin=inl[cnt1]
        #               if cntbs==9 :
        #                   cntbs=1
        #                   lin=inl[cnt1]
        #    #            outf.write('** '+ lin)
        #                   cnt1=cnt1+1
        #           cnt1=cnt1-1
        #           BsurfDict[csid]= csList
        elif lin[0:7] == 'BCONECT':
            #      outf.write('** '+ lin)
            cbsid = int(lin[32:40])
            cbmid = int(lin[40:48])
            bcprg[int(lin[16:24])] = [cbsid, cbmid]
            if lin[24:32] != '        ':
                bcong2p[int(lin[16:24])] = int(lin[24:32])
            else:
                bcong2p[int(lin[16:24])] = 0

        elif lin[0:7] == 'BCONPRG':
            cnt1 = process_bconprg(bcb2p, bcong2p, bcprg, cnt1, inl, lin, outf, small_sliding, tieAll)
        elif lin[0:7] == 'BCONPRP':
            process_bconprp(lin, outf)

        elif lin[0:6] == 'PLOAD4':
            process_pload4(lin, outf, ploadId, pressCnt)
            pressCnt += 1

        elif lin[0:5] == 'FORCE':
            process_force(BoltCNlist, forceId, lin, load, outf)
        elif lin[0:4] == 'SPCD':
            outf.write('** ' + lin + '\n')
            fname = 'SPCD_ID_%i_GRID_%i' % (int(lin[8:16]), int(lin[16:24]))
            spcdId[int(lin[8:16]), int(lin[16:24])] = fname
            outf.write('*NSET, NSET=%s\n' % fname)
            outf.write(' %i,\n' % int(lin[16:24]))
            spcdDof = int(lin[24:32])
            coeff = convert_real2(lin[32:40])
            load[fname] = [spcdDof, float(coeff)]
        elif lin[0:4] == 'RBE3':
            cnt1 = process_rbe3(cnt1, inl, lin, outf, partName)

        # added by Jim He to support RBAR
        elif lin[0:4] == 'RBAR':
            rbarid = int(lin[8:16])
            refnod = int(lin[16:24])
            rbardof = int(lin[32:40])
            tmp = '*NSET, NSET=%s_RBAR_ID_%i_REFNODE_%i_DOF_%i \n' % (partName, rbarid, refnod, rbardof)
            outf.write(tmp)
            tmp = ' %i \n' % int(lin[24:32])
            tmp = '*KINEMATIC COUPLING, REF NODE=%i\n %s_RBAR_ID_%i_REFNODE_%i_DOF_%i ,1,6 \n' % (
                refnod, partName, rbarid, refnod, rbardof)
            outf.write(tmp)

        # added by Jim He to support GRAV       
        elif lin[0:4] == 'GRAV':
            gravflg = 1
            gravid = int(lin[8:16])
            gravval = convert_real2(lin[24:32])
            gravdirx = convert_real2(lin[32:40])
            gravdiry = convert_real2(lin[40:48])
            gravdirz = convert_real2(lin[48:56])


        # added by Jim He to support CONM2
        elif lin[0:5] == 'CONM2':
            comn2id = int(lin[8:16])
            comn2node = int(lin[16:24])
            comn2mass = convert_real2(lin[32:40])
            tmp = '*ELEMENT, TYPE=MASS, ELSET=%s_CONM2_ID_%i_NODE_ID_%i \n' % (partName, comn2id, comn2node)
            outf.write(tmp)
            tmp = ' %i, %i \n' % (comn2id, comn2node)
            outf.write(tmp)
            tmp = '*MASS, ELSET=%s_CONM2_ID_%i_NODE_ID_%i \n' % (partName, comn2id, comn2node)
            outf.write(tmp)
            tmp = ' %f \n' % comn2mass
            outf.write(tmp)
        else:
            outf.write('** ' + lin + '\n')
    print('Done processing input file')
    print('Time after reading:' + str(time.time() - sTime) + '\n')

    #    outf.write('*NODE \n')
    #    for nid in NodeDict :
    #       tmp='%8i,%f,%f,%f\n' %(nid,NodeDict[nid][0],NodeDict[nid][1],NodeDict[nid][2])
    #       outf.write(tmp)
    #    print(ploadId)   

    print('time before writing bolt surfaces:' + str(time.time() - sTime) + '\n\n')

    if len(BoltCNlist) > 0:
        existBolt = 1
        #list_set = set(BoltElList)
        #BoltElListU = (list(list_set))
        #
        for bolt in BoltDict:
            outf.write('*PRE-TENSION SECTION, NODE=%i, SURFACE=SURFACE_BOLT_%i\n' % (BoltDict[bolt][0], bolt))
            outf.write('*SURFACE, NAME = SURFACE_BOLT_%i, TYPE = ELEMENT\n' % (bolt))

            for cel in BoltElList:
                fl = freeBolt(cel, hexFace, BoltDict[bolt][2])
                if len(fl) > 0:
                    outf.write(' %i, S%i\n' % (cel, fl[0]))

    print('time before writing contact surfaces:' + str(time.time() - sTime) + '\n\n')

    face_counter.swap()
    for csid in BsurfDict:
        bsname = 'BSURF_ID_%i' % (csid)
        outf.write('*SURFACE, NAME=%s, TYPE=ELEMENT\n' % bsname)
        for cel in BsurfDict[csid]:
            if eltype[cel] == 6:
                #               fl=freehex(cel,hexFace,nod1,nod2,nod3,nod4,nod5,nod6,nod7,nod8,penFace)
                #               if len(fl) > 0 :
                #                  for ss in fl :
                #                      outf.write(' %i, S%i\n' %(cel,ss))
                if cel in face_counter.unique_surf:
                    for ss in face_counter.unique_surf[cel]:
                        outf.write(' %i, S%i\n' % (cel, ss))
            elif eltype[cel] == 4:
                #               fl=freetet(cel,tetFace,nod1,nod2,nod3,nod4)
                #               fl=face_counter.original
                if cel in face_counter.unique_surf:
                    for ss in face_counter.unique_surf[cel]:
                        outf.write(' %i, S%i\n' % (cel, ss))
            elif eltype[cel] == 5:
                #               fl=freepen(cel,penFace,nod1,nod2,nod3,nod4,nod5,nod6,nod7,nod8,hexFace)
                #               if len(fl) > 0 :
                #                  for ss in fl :
                #                      outf.write(' %i, S%i\n' %(cel,ss))
                if cel in face_counter.unique_surf:
                    for ss in face_counter.unique_surf[cel]:
                        outf.write(' %i, S%i\n' % (cel, ss))
            elif eltype[cel] == 0 or eltype[cel] == 1:
                outf.write(' %i, S1\n' % cel)
                outf.write(' %i, S2\n' % cel)
    print('time before writing materials:' + str(time.time() - sTime) + '\n\n')

    for mid1 in matDict:
        mName = 'MAT1_ID' + str(mid1)
        midname[mid1] = mName
        tmp = '*MATERIAL, NAME=%s \n' % mName
        outf.write(tmp)
        tmp = '*DENSITY \n %24.6e,\n' % matDict[mid1][1]
        outf.write(tmp)
        tmp = '*ELASTIC, TYPE=ISOTROPIC \n %24.6f,%24.6f,\n' % (matDict[mid1][2], matDict[mid1][3])
        outf.write(tmp)
        try:
            # Stefan: check if blank is passed as stress/Strain table id... if blank
            # this is a perfectly plastic material, not yet supported and it will throw an exception
            int([plast[1]][1])

            plast = midEPname[mid1]
            outf.write('*PLASTIC, HARDENING=ISOTROPIC \n')
            eps = tabDict[plast[1]][0]
            sig = tabDict[plast[1]][1]
            cntx = 0
            while cntx < len(eps):
                e2 = eps[cntx]
                s2 = sig[cntx]
                tmp = ' %10.3f,%10.3f \n' % (s2, e2)
                outf.write(tmp)
                cntx = cntx + 1
        except:
            print(' No plasticity, or perfectly plastic (unsupported) for MAT1, ID: %i' % mid1)

    #               pidname[partpid]=[cpid,'beam']
    print('time before writing properties:' + str(time.time() - sTime) + '\n\n')

    for name in pidname:
        cpid2 = pidname[name][0]
        ptype = pidname[name][1]
        if ptype == 'beam':
            mpid = pBarDict[cpid2][0]
            psmat = midname[mpid]
            #           ori=pidOri[cpid2] replaced by beamOri,which is x product vector for Abaqus orientation
            ori = beamOri[cpid2]
            if pBarDict[cpid2][3] == 'ROD':
                tmp = '*BEAM SECTION,SECTION=CIRC,ELSET=%s, MATERIAL=%s \n' % (name, psmat)
                outf.write(tmp)
                outf.write(' %10.7f\n  %10.7f, %10.7f, %10.7f\n' % (pBarDict[cpid2][1], ori[0], ori[1], ori[2]))
            elif pBarDict[cpid2][3] == 'TUBE' or pBarDict[cpid2][3] == 'TUBE2':
                tmp = '*BEAM SECTION,SECTION=PIPE,ELSET=%s, MATERIAL=%s \n' % (name, psmat)
                outf.write(tmp)
                outf.write(' %10.7f, %10.7f\n  %10.7f, %10.7f, %10.7f\n' % (
                    pBarDict[cpid2][1], pBarDict[cpid2][2], ori[0], ori[1], ori[2]))
            elif pBarDict[cpid2][3] == 'BAR':
                tmp = '*BEAM SECTION,SECTION=RECT,ELSET=%s, MATERIAL=%s \n' % (name, psmat)
                outf.write(tmp)
                outf.write(' %10.7f, %10.7f\n  %10.7f, %10.7f, %10.7f\n' % (
                    pBarDict[cpid2][2], pBarDict[cpid2][1], ori[0], ori[1], ori[2]))
            # pBarDict[cpid2]=[mpid,Dim1,Dim2,sec,Dim3,Dim4,Dim5,Dim6]			   
            elif pBarDict[cpid2][3] == 'I':
                # l is offset of beam...need to get....use h for now
                tmp = '*BEAM SECTION,SECTION=I,ELSET=%s, MATERIAL=%s \n' % (name, psmat)
                outf.write(
                    tmp)  # l                          h                  b1                    b2              t1                  t2                  t3
                outf.write(' %10.7f, %10.7f, %10.7f, %10.7f, %10.7f, %10.7f, %10.7f\n %10.7f, %10.7f, %10.7f\n' % (
                    pBarDict[cpid2][1], pBarDict[cpid2][1], pBarDict[cpid2][2], pBarDict[cpid2][4], pBarDict[cpid2][6],
                    pBarDict[cpid2][7], pBarDict[cpid2][5], ori[0], ori[1], ori[2]))
            elif pBarDict[cpid2][3] == 'T':
                # l is offset of beam...need to get....use 0 for now, set b1 and t1 to zero to get T from I 
                tmp = '*BEAM SECTION,SECTION=I,ELSET=%s, MATERIAL=%s \n' % (name, psmat)
                outf.write(tmp)  # l          h        b1          b2         t1            t2                  t3
                outf.write(' %10.7f, %10.7f, %10.7f, %10.7f, %10.7f, %10.7f, %10.7f\n %10.7f, %10.7f, %10.7f\n' % (
                    pBarDict[cpid2][2], pBarDict[cpid2][2], 0.0, pBarDict[cpid2][1], 0.0, pBarDict[cpid2][4],
                    pBarDict[cpid2][5], ori[0], ori[1], ori[2]))
            elif pBarDict[cpid2][3] == 'L':  # offs               h                  b1                    b2
                # sequence of Dim1...etc need to be sorted out for L section		   
                tmp = '*BEAM SECTION,SECTION=L,ELSET=%s, MATERIAL=%s \n' % (name, psmat)
                outf.write(tmp)  # a                    b              t1              t2
                outf.write(' %10.7f, %10.7f, %10.7f, %10.7f\n %10.7f, %10.7f, %10.7f\n' % (
                    pBarDict[cpid2][1], pBarDict[cpid2][2], pBarDict[cpid2][4], pBarDict[cpid2][5], ori[0], ori[1],
                    ori[2]))


        elif ptype == 'shell':
            mpid = pShlDict[cpid2][0]
            psmat = midname[mpid]
            psthick = pShlDict[cpid2][1]
            tmp = '*SHELL SECTION, ELSET=%s, MATERIAL=%s \n' % (name, psmat)
            outf.write(tmp)
            outf.write(' %10.7f\n' % psthick)
        elif ptype == 'sol':
            mpid = pSolDict[cpid2][0]
            psmat = midname[mpid]
            tmp = '*SOLID SECTION, ELSET=%s, MATERIAL=%s \n' % (name, psmat)
            outf.write(tmp)
        else:
            print('invalid property type')

    outf.write('*ELSET, ELSET=EALL, GENERATE\n')
    outf.write('1,99999999,1\n')

    print('time before writing STEP:' + str(time.time() - sTime) + '\n\n')

    if existBolt == 1 and preStep == 1:
        cnt = -1
    else:
        cnt = 0
    while cnt < len(stepList):
        if cnt == -1:  # prestep
            cnt = cnt + 1
            outf.write('** \n')
            outf.write('*STEP,NLGEOM=%s \n' % (nlgeom))
            outf.write('*STATIC \n')
            outf.write('0.01       ,1.0       ,1.0000E-05, 1 \n')
            outf.write('*** \n')
            outf.write('** BOUNDARY \n')
            outf.write('*** \n')
            outf.write('*BOUNDARY, TYPE=DISPLACEMENT, OP=NEW\n')
            sid = spcList[cnt]
            sidL = SpcDict[sid]
            for ssid in sidL:
                key = spcId[ssid]
                if spcs[key] == 123456:
                    outf.write('%s, 1, 6, 0.0\n' % (key))
                elif spcs[key] == 123:
                    outf.write('%s, 1, 3, 0.0\n' % (key))
                else:
                    dstr = str(spcs[key])
                    if '1' in dstr:
                        outf.write('%s, 1, , 0.0\n' % (key))
                    if '2' in dstr:
                        outf.write('%s, 2, , 0.0\n' % (key))
                    if '3' in dstr:
                        outf.write('%s, 3, , 0.0\n' % (key))
                    if '4' in dstr:
                        outf.write('%s, 4, , 0.0\n' % (key))
                    if '5' in dstr:
                        outf.write('%s, 5, , 0.0\n' % (key))
                    if '6' in dstr:
                        outf.write('%s, 6, , 0.0\n' % (key))
            lid = loadList[cnt]
            try:
                loads = LoadDict[lid]
                for key in forceId:
                    if key[0] in loads[2]:
                        fname1 = forceId[key[0], key[1]]
                        outf.write('%s, 1, , %10.6e \n' % (fname1, preOverLap))
            except:
                outf.write(
                    '** WARNING: no loads found for Case Control Load Id: %i . Check Nastran input file!\n' % (lid))
                loads = 0
            outf.write('*** \n')
            outf.write('** Output\n')
            outf.write('************************************\n')
            outf.write('** ODB file\n')
            outf.write('*OUTPUT, FIELD\n')
            outf.write('*ELEMENT OUTPUT\n')
            outf.write('S,\n')
            outf.write('PEEQ,\n')
            outf.write('*NODE OUTPUT\n')
            outf.write('U,\n')
            outf.write('RF,\n')
            outf.write('*CONTACT OUTPUT\n')
            outf.write('CDISP,\n')
            outf.write('CSTRESS,\n')
            outf.write('CSTATUS,\n')
            outf.write('*END STEP\n')
            cnt = cnt - 1
        else:
            outf.write('** \n')
            outf.write('*STEP,NLGEOM=%s \n' % (nlgeom))
            outf.write('*STATIC \n')
            outf.write('0.1       ,1.0       ,1.0000E-05, 1 \n')
            outf.write('*** \n')
            outf.write('** CLOAD \n')
            outf.write('*** \n')
            outf.write('*CLOAD, OP=NEW\n')
            lid = loadList[cnt]
            try:
                loads = LoadDict[lid]
                for key in forceId:
                    if key[0] in loads[2]:
                        fname1 = forceId[key[0], key[1]]
                        if load[fname1][0] > 1.0e-9:
                            outf.write('%s, 1, %10.6e \n' % (fname1, load[fname1][0]))
                        if load[fname1][1] > 1.0e-9:
                            outf.write('%s, 2, %10.6e \n' % (fname1, load[fname1][1]))
                        if load[fname1][2] > 1.0e-9:
                            outf.write('%s, 3, %10.6e \n' % (fname1, load[fname1][2]))
            except:
                outf.write(
                    '** WARNING: no CLOAD loads found for Case Control Load Id: %i . Check Nastran input file!\n' % (
                        lid))
                loads = 0
            outf.write('*** \n')
            outf.write('** DLOAD \n')
            outf.write('*** \n')
            outf.write('*DLOAD, OP=NEW\n')

            ## ploadId[elid,int(lin[8:16])]=[fname,float(coeff),int(lin[56:64]),int(lin[64:72])]

            try:
                loads = LoadDict[lid]
                for key in ploadId:
                    if key[1] in loads[2]:
                        if eltype[key[0]] < 2:
                            outf.write('%i, P, %10.6e \n' % (key[0], ploadId[key[0], key[1], key[2]][1]))
                        elif eltype[key[0]] == 6:
                            pressFace = HexPress(key[0], hexFace, [ploadId[key[0], key[1], key[2]][2],
                                                                   ploadId[key[0], key[1], key[2]][3]])
                            outf.write(
                                '%i, P%i, %10.6e \n' % (key[0], pressFace[0], ploadId[key[0], key[1], key[2]][1]))
                        elif eltype[key[0]] == 5:
                            pressFace = PenPress(key[0], penFace, [ploadId[key[0], key[1], key[2]][2],
                                                                   ploadId[key[0], key[1], key[2]][3]])
                            outf.write(
                                '%i, P%i, %10.6e \n' % (key[0], pressFace[0], ploadId[key[0], key[1], key[2]][1]))
                        elif eltype[key[0]] == 4:
                            pressFace = TetPress(key[0], tetFace, [ploadId[key[0], key[1], key[2]][2],
                                                                   ploadId[key[0], key[1], key[2]][3]])
                            outf.write(
                                '%i, P%i, %10.6e \n' % (key[0], pressFace[0], ploadId[key[0], key[1], key[2]][1]))
            except:
                outf.write(
                    '** WARNING: no DLOAD loads found for Case Control Load Id: %i . Check Nastran input file!\n' % (
                        lid))
                loads = 0
            outf.write('*** \n')
            outf.write('*BOUNDARY, TYPE=DISPLACEMENT, OP=NEW\n')
            try:
                loads = LoadDict[lid]
                for key in spcdId:
                    if key[0] in loads[2]:
                        fname1 = spcdId[key[0], key[1]]
                        outf.write('%s, %i, %10.6e \n' % (fname1, load[fname1][0], load[fname1][1]))
            except:
                outf.write(
                    '** WARNING: no spcd found for Case Control Load Id: %i . Check Nastran input file!\n' % (lid))
                loads = 0

            # Added by Jim He to include gravity loading in the loadstep
            if gravflg == 1:
                try:
                    loads = LoadDict[lid][2]
                    if gravid in loads:
                        tmp = '*DLOAD \n'
                        outf.write(tmp)
                        tmp = 'EALL,GRAV,%f,%f,%f,%f \n' % (gravval, gravdirx, gravdiry, gravdirz)
                        outf.write(tmp)
                except:
                    loads = 0
            outf.write('*** \n')
            outf.write('** BOUNDARY \n')
            outf.write('*** \n')
            outf.write('*BOUNDARY, TYPE=DISPLACEMENT, OP=NEW\n')
            sid = spcList[cnt]
            sidL = SpcDict[sid]
            boltTmp = ''
            for ssid in sidL:
                key = spcId[ssid]
                if spcs[key] == 123456:
                    outf.write('%s, 1, 6, 0.0\n' % (key))
                elif spcs[key] == 123:
                    outf.write('%s, 1, 3, 0.0\n' % (key))
                elif 'AXIAL_BOLT_FIXED' in key:
                    boltTmp = boltTmp + '%s, 1, ,\n' % (key)
                else:
                    dstr = str(spcs[key])
                    if '1' in dstr:
                        outf.write('%s, 1, , 0.0\n' % (key))
                    if '2' in dstr:
                        outf.write('%s, 2, , 0.0\n' % (key))
                    if '3' in dstr:
                        outf.write('%s, 3, , 0.0\n' % (key))
                    if '4' in dstr:
                        outf.write('%s, 4, , 0.0\n' % (key))
                    if '5' in dstr:
                        outf.write('%s, 5, , 0.0\n' % (key))
                    if '6' in dstr:
                        outf.write('%s, 6, , 0.0\n' % (key))
            if len(boltTmp) > 1:
                outf.write('*BOUNDARY, TYPE=DISPLACEMENT, OP=NEW, FIXED\n')
                outf.write(boltTmp)
            outf.write('*** \n')
            outf.write('** Output\n')
            outf.write('************************************\n')
            outf.write('** ODB file\n')
            outf.write('*OUTPUT, FIELD\n')
            outf.write('*ELEMENT OUTPUT\n')
            outf.write('S,\n')
            outf.write('PEEQ,\n')
            outf.write('*NODE OUTPUT\n')
            outf.write('U,\n')
            outf.write('RF,\n')
            outf.write('*CONTACT OUTPUT\n')
            outf.write('CDISP,\n')
            outf.write('CSTRESS,\n')
            outf.write('CSTATUS,\n')
            outf.write('*END STEP\n')
        cnt = cnt + 1
    print('Total time:' + str(time.time() - sTime) + '\n\n')

    return out_inp_file


def process_grid(cnt1, gflag, inl, lin, outf):
    if gflag == 1:
        gflag = 0
        outf.write('*NODE \n')
    elif inl[cnt1 - 2][0:4] != 'GRID':
        outf.write('*NODE \n')
    xx1 = convert_real2(lin[24:32])
    yy1 = convert_real2(lin[32:40])
    zz1 = convert_real2(lin[40:48])
    tmp = '%8i,%f,%f,%f\n' % (int(lin[8:16]), xx1, yy1, zz1)
    outf.write(tmp)
    return gflag


def process_rbe3(cnt1, inl, lin, outf, partName):
    rbe3id = int(lin[8:16])
    refnod = int(lin[24:32])
    rbe3dof = lin[32:40].strip()
    rbe3coeff = convert_real2(lin[40:48])
    #
    tmp = '*SURFACE, TYPE=NODE, NAME=%s_SURF_RBEID_%i_REF_%i_DOF_%s \n' % (partName, rbe3id, refnod, rbe3dof)
    #
    outf.write(tmp)
    cntrbe3 = 7
    while (cntrbe3 + 1) * 8 < len(lin):
        tmp = (lin[(cntrbe3 * 8):((cntrbe3 + 1) * 8)])
        tmp = ' %i,%f \n' % (int(tmp), rbe3coeff)
        outf.write(tmp)
        cntrbe3 = cntrbe3 + 1
    lin = inl[cnt1]
    cntrbe3 = 1
    while (lin[0:1] == '+'):
        #         print lin,cntrbe3,cnt1
        tmp = (lin[(cntrbe3 * 8):((cntrbe3 + 1) * 8)])
        if tmp != '':
            tmp = ' %i,%f \n' % (int(tmp), rbe3coeff)
            outf.write(tmp)
            cntrbe3 = cntrbe3 + 1
        else:
            cntrbe3 = 9
        if cntrbe3 == 9:
            cntrbe3 = 1
            cnt1 = cnt1 + 1
            lin = inl[cnt1]
    #            print cnt1,lin
    tmp = '*COUPLING, CONSTRAINT NAME=%s_RBEID_%i_REF_%i_DOF_%s, REF NODE=%i, SURFACE=%s_SURF_RBEID_%i_REF_%i_DOF_%s \n' % (
        partName, rbe3id, refnod, rbe3dof, refnod, partName, rbe3id, refnod, rbe3dof)
    outf.write(tmp)
    tmp = '*DISTRIBUTING\n'
    outf.write(tmp)
    for i in range(len(rbe3dof)):
        tmp = '%i \n' % (int(rbe3dof[i:i + 1]))
        outf.write(tmp)
    return cnt1


def process_bconprp(lin, outf):
    cbprpid = int(lin[8:16])
    if lin[24:32].replace(' ', '') == 'FRIC':
        fricv = convert_real2(lin[32:40])
    else:
        fricv = 0.000
    outf.write('*SURFACE INTERACTION, NAME=Interaction_ID_%i\n' % (cbprpid))
    outf.write('*FRICTION \n')
    outf.write(' %8.5f,\n' % fricv)


def process_bsurf(BsurfDict, cnt1, inl, lin):
    csList = []
    csid = int(lin[8:16])
    tmp_str = lin[16:72].replace('+', '')
    l8 = chunkstring(tmp_str, 8)
    lin = inl[cnt1]
    cnt1 = cnt1 + 1
    while (lin[0:1] == '+'):
        l8.extend(chunkstring(lin.replace('+       ', '').replace('+', ''), 8))
        lin = inl[cnt1]
        cnt1 = cnt1 + 1
    cnt1 = cnt1 - 1
    cntbs = 0
    while cntbs < len(l8):
        strbs = l8[cntbs]
        if 'THRU' in strbs:
            start_id = csList[-1]
            cntbs += 1
            strbs = l8[cntbs]
            end_id = int(strbs)
            if 'BY' in l8[cntbs + 1]:
                cntbs += 2
                step = int(l8[cntbs])
            else:
                step = 1
            for thru_id in range(start_id + 1, end_id + 1, step):
                csList.append(thru_id)

        else:
            csList.append(int(strbs))
        cntbs += 1
    BsurfDict[csid] = csList
    return cnt1


def process_rbe2(cnt1, inl, lin, outf, partName):
    rbe2id = int(lin[8:16])
    refnod = int(lin[16:24])
    rbe2dof = int(lin[24:32])
    tmp = '*NSET, NSET=%s_RBEID_%i_REF_%i_DOF_%i \n' % (partName, rbe2id, refnod, rbe2dof)
    outf.write(tmp)
    cntrbe2 = 4
    while (cntrbe2 + 1) * 8 < len(lin):
        tmp = (lin[(cntrbe2 * 8):((cntrbe2 + 1) * 8)])
        tmp = ' %i,' % (int(tmp))
        outf.write(tmp)
        cntrbe2 = cntrbe2 + 1
    lin = inl[cnt1]
    outf.write('\n')
    cntrbe2 = 1
    while (lin[0:1] == '+'):
        #         print lin,cntrbe2,cnt1
        tmp = (lin[(cntrbe2 * 8):((cntrbe2 + 1) * 8)])
        if tmp != '':
            tmp = ' %i,' % (int(tmp))
            outf.write(tmp)
            cntrbe2 = cntrbe2 + 1
        else:
            cntrbe2 = 9
        if cntrbe2 == 9:
            outf.write('\n')
            cntrbe2 = 1
            cnt1 = cnt1 + 1
            lin = inl[cnt1]
    #            print cnt1,lin
    tmp = '*KINEMATIC COUPLING, REF NODE=%i\n %s_RBEID_%i_REF_%i_DOF_%i ,1,6 \n' % (
        refnod, partName, rbe2id, refnod, rbe2dof)
    outf.write(tmp)
    return cnt1


def process_spc1(BoltCNlist, lin, outf, partName, spc1flg, spcId, spccnt, spcid, spcs):
    spc1flg = 1
    snid = int(lin[24:32])
    if spcid != int(lin[8:16]):
        spcid = int(lin[8:16])
        spcdof = int(lin[16:24])
        if snid in BoltCNlist:
            if spcdof < 100:
                sname = '%s_SPC1ID_%i_AXIAL_BOLT_DOF%i' % (partName, spcid, 0)
                spcs[sname] = 0
            else:
                sname = '%s_SPC1ID_%i_AXIAL_BOLT_FIXED' % (partName, spcid)
                spcs[sname] = 1
        else:
            sname = '%s_SPC1ID_%i_DOF_%i' % (partName, spcid, spcdof)
            spcs[sname] = spcdof
        tmp = '*NSET, NSET=%s \n' % (sname)
        spcId[spcid] = sname
        outf.write(tmp)
        spccnt = 0
    outf.write(' %i' % (int(lin[24:32])))
    spccnt = spccnt + 1
    if spccnt == 8:
        outf.write(',\n')
        spccnt = 0
    else:
        outf.write(',')
    return spc1flg, spccnt, spcid


def process_spc(lin, outf, partName, spcId, spccnt, spcflg, spcid, spcs):
    spcflg = 1
    if spcid != int(lin[8:16]):
        spcid = int(lin[8:16])
        spcdof = int(lin[24:32])
        sname = '%s_SPCID_%i_DOF_%i' % (partName, spcid, spcdof)
        tmp = '*NSET, NSET=%s \n' % (sname)
        spcs[sname] = spcdof
        spcId[spcid] = sname
        outf.write(tmp)
        spccnt = 0
    outf.write(' %i' % (int(lin[16:24])))
    spccnt = spccnt + 1
    if spccnt == 8:
        outf.write(',\n')
        spccnt = 0
    else:
        outf.write(',')
    return spccnt, spcflg, spcid


def process_pload4(lin, outf, ploadId, pressCnt):
    outf.write('** ' + lin)
    fname = 'PLOAD_ID_%i' % (int(lin[8:16]))
    elid = int(lin[16:24])
    if (len(lin) < 40):
        coeff = convert_real2(lin[24:32])
        ploadId[elid, int(lin[8:16]), pressCnt] = [fname, coeff]
    elif (len(lin) < 66):
        coeff = convert_real2(lin[24:32])
        ploadId[elid, int(lin[8:16]), pressCnt] = [fname, coeff, int(lin[56:64]), int(lin[56:64])]
    else:
        coeff = convert_real2(lin[24:32])
        ploadId[elid, int(lin[8:16]), pressCnt] = [fname, coeff, int(lin[56:64]), int(lin[64:72])]


def process_force(BoltCNlist, forceId, lin, load, outf):
    outf.write('** ' + lin + '\n')
    fname = 'FORCE_ID_%i_GRID_%i' % (int(lin[8:16]), int(lin[16:24]))
    forceId[int(lin[8:16]), int(lin[16:24])] = fname
    outf.write('*NSET, NSET=%s\n' % fname)
    outf.write(' %i,\n' % int(lin[16:24]))
    coeff = convert_real2(lin[32:40])
    xr = convert_real2(lin[40:48])
    yr = convert_real2(lin[48:56])
    zr = convert_real2(lin[56:64])
    if int(lin[16:24]) in BoltCNlist:
        fmag = sqrt(
            (coeff * xr) ** 2 + (coeff * yr) ** 2 + (coeff * zr) ** 2)
        load[fname] = [fmag, 0.0, 0.0]
    else:
        load[fname] = [coeff * xr, coeff * yr, coeff * zr]


def process_bconprg(bcb2p, bcong2p, bcprg, cnt1, inl, lin, outf, small_sliding, tieAll):
    cbprgid = int(lin[8:16])
    cnt1 = cnt1 - 1
    lin = inl[cnt1]
    # concatenate all bconprg_strings, remove cont
    bconprg_id = int(lin[8:16])
    tmp_str = inl[cnt1][24:72].replace('+', '')
    while inl[cnt1 + 1].find("+") == 0:
        tmp_str = tmp_str + inl[cnt1 + 1].replace('+       ', '').replace('+', '')
        cnt1 += 1
    bconD = {}
    # Organize tmp stri in a list with chunks of 16, then into a dict
    bconL = [tmp_str[i:i + 16] for i in range(0, len(tmp_str), 16)]
    # print bconL
    for item in bconL:
        bconD[item[0:8].strip()] = item[8:16].strip()
    adjust = convert_real2(bconD['ERROR'])
    glue = int(bconD['IGLUE'])
    if tieAll == 1:
        glue = 1
    #
    # continue Magnus Stuff
    s1 = 'BSURF_ID_%i' % (bcb2p[bcprg[cbprgid][0]])
    s2 = 'BSURF_ID_%i' % (bcb2p[bcprg[cbprgid][1]])
    if glue > 0:
        outf.write('*TIE, NAME=%s_%s, POSITION TOLERANCE=%10.6f, ADJUST=YES\n' % (s1, s2, adjust))
        outf.write(' %s, %s\n' % (s1, s2))
    else:
        if bcong2p[cbprgid] != 0:
            interid = bcong2p[cbprgid]
            outf.write(
                '*CONTACT PAIR, INTERACTION=Interaction_ID_%i, ADJUST=%10.6f,  TYPE=SURFACE TO SURFACE' % (
                    interid, adjust))
            if small_sliding == 1:
                outf.write(', SMALL SLIDING\n')
            else:
                outf.write('\n')
        else:
            outf.write('*CONTACT PAIR, ADJUST=%10.6f,  TYPE=SURFACE TO SURFACE' % (adjust))
            if small_sliding == 1:
                outf.write(', SMALL SLIDING\n')
            else:
                outf.write('\n')
        outf.write(' %s, %s\n' % (s1, s2))
    return cnt1




def process_cpenta(BoltElList, TopList, cpid, eflagpen, eltype, eqDict, face_counter, lin, inl, outf, partName, penFace,
                   penId, pidname, cnt1):
    lin2 = inl[cnt1]
    if lin2[0:1] == ' ' or lin2[0:1] == '+' :
        porder=2
    else :
        porder=1
    if eflagpen == 1 or (cpid != int(lin[16:24])):
        cpid = int(lin[16:24])
        partpid = '%s_PID_%i' % (partName, cpid)
        pidname[partpid] = [cpid, 'sol']
        if porder == 1 :
            tmp = '*ELEMENT, TYPE=C3D6, ELSET=%s\n' % (partpid)
        else :
            tmp = '*ELEMENT, TYPE=C3D15, ELSET=%s\n' % (partpid)
        outf.write(tmp)
        eflagpen = 0
    nl = []
    nl.append(int(lin[24:32]))
    nl.append(int(lin[32:40]))
    nl.append(int(lin[40:48]))
    nl.append(int(lin[48:56]))
    nl.append(int(lin[56:64]))
    nl.append(int(lin[64:72]))
    pId = int(lin[8:16])
    eltype[pId] = 5
    g = 0
    while g < 6:
        if nl[g] in TopList:
            nl[g] = eqDict[nl[g]]
            BoltElList.add(pId)
        g = g + 1
    if porder == 2:
        lin = inl[cnt1]
        cnt1 = cnt1 + 1
        nl.append(int(lin[8:16]))
        nl.append(int(lin[16:24]))
        nl.append(int(lin[24:32]))
        nl.append(int(lin[32:40]))
        nl.append(int(lin[40:48]))
        nl.append(int(lin[48:56]))
        nl.append(int(lin[56:64]))
        nl.append(int(lin[64:72]))
        lin = inl[cnt1]
        cnt1 = cnt1 + 1
        nl.append(int(lin[8:16]))
        g = 6
        while g < 15:
            if nl[g] in TopList:
                nl[g] = eqDict[nl[g]]
                BoltElList.add(pId)
            g = g + 1
        tmp = '%8i,%8i,%8i,%8i,%8i,%8i,%8i,%8i,%8i,%8i,%8i,\n%8i,%8i,%8i,%8i,%8i\n' % (
            pId, nl[0], nl[1], nl[2], nl[3], nl[4], nl[5], nl[6], nl[7], nl[8], nl[12], nl[13], nl[14], nl[9], nl[10], nl[11])
    else:
        tmp = '%8i,%8i,%8i,%8i,%8i,%8i,%8i\n' % (pId, nl[0], nl[1], nl[2], nl[3], nl[4], nl[5])
    outf.write(tmp)
    face_counter.add(pId, 1, [nl[0], nl[2], nl[1], nl[0]])
    face_counter.add(pId, 2, [nl[3], nl[4], nl[5], nl[3]])
    face_counter.add(pId, 3, [nl[0], nl[1], nl[4], nl[3]])
    face_counter.add(pId, 4, [nl[1], nl[2], nl[5], nl[4]])
    face_counter.add(pId, 5, [nl[2], nl[0], nl[3], nl[5]])
    penFace[pId, 1] = [nl[0], nl[2], nl[1], nl[0]]
    penFace[pId, 2] = [nl[3], nl[4], nl[5], nl[3]]
    penFace[pId, 3] = [nl[0], nl[1], nl[4], nl[3]]
    penFace[pId, 4] = [nl[1], nl[2], nl[5], nl[4]]
    penFace[pId, 5] = [nl[2], nl[0], nl[3], nl[5]]
    penId.append(pId)
    return cpid, eflagpen


def process_ctria3(cpid, eflagtri, eltype, lin, matInteg, outf, pShlDict, partName, pidname):
    if eflagtri == 1 or (cpid != int(lin[16:24])):
        cpid = int(lin[16:24])
        intAba = matInteg[pShlDict[cpid][0]]
        if intAba == 'red':
            elSuffix = 'R'
            outf.write('** Reduced integration formulation selected from Material Description\n')
        elif intAba == 'std':
            elSuffix = ''
            outf.write('** Full integration formulation selected from Material Description\n')
        else:
            elSuffix = ''
            outf.write('** Full integration formulation selected since Material Description is missing\n')
        partpid = '%s_PID_%i' % (partName, cpid)
        pidname[partpid] = [cpid, 'shell']
        tmp = '*ELEMENT, TYPE=S3%s, ELSET=%s\n' % (elSuffix, partpid)
        outf.write(tmp)
        eflagtri = 0
    tmp = '%8i,%8i,%8i,%8i\n' % (int(lin[8:16]), int(lin[24:32]), int(lin[32:40]), int(lin[40:48]))
    outf.write(tmp)
    eltype[int(lin[8:16])] = 0
    return cpid, eflagtri

def process_ctria6(cpid, eflagt6, eltype, lin, matInteg, outf, pShlDict, partName, pidname):
    if eflagt6 == 1 or (cpid != int(lin[16:24])):
        cpid = int(lin[16:24])
        intAba = matInteg[pShlDict[cpid][0]]
        # all formulation set to STRI65
        if intAba == 'red':
            elSuffix = '5'
            outf.write('** Reduced integration formulation selected from Material Description\n')
        elif intAba == 'std':
            elSuffix = '5'
            outf.write('** Full integration formulation selected from Material Description\n')
        else:
            elSuffix = '5'
            outf.write('** Full integration formulation selected since Material Description is missing\n')
        partpid = '%s_PID_%i' % (partName, cpid)
        pidname[partpid] = [cpid, 'shell']
        tmp = '*ELEMENT, TYPE=STRI6%s, ELSET=%s\n' % (elSuffix, partpid)
        outf.write(tmp)
        eflagt6 = 0
    tmp = '%8i,%8i,%8i,%8i,%8i,%8i,%8i\n' % (int(lin[8:16]), int(lin[24:32]), int(lin[32:40]), int(lin[40:48]), int(lin[48:56]), int(lin[56:64]), int(lin[64:72]))
    outf.write(tmp)
    eltype[int(lin[8:16])] = 0
    return cpid, eflagt6



def process_cquad8(cpid, eflagq8, eltype, lin, inl, matInteg, outf, pShlDict, partName, pidname, cnt1):
    if eflagq8 == 1 or (cpid != int(lin[16:24])):
        cpid = int(lin[16:24])
        intAba = matInteg[pShlDict[cpid][0]]
        # all formulation set to S8R
        if intAba == 'red':
            elSuffix = 'R'
            outf.write('** Reduced integration formulation selected from Material Description\n')
        elif intAba == 'std':
            elSuffix = 'R'
            outf.write('** Full integration formulation selected from Material Description\n')
        else:
            elSuffix = 'R'
            outf.write('** Full integration formulation selected since Material Description is missing\n')
        partpid = '%s_PID_%i' % (partName, cpid)
        pidname[partpid] = [cpid, 'shell']
        tmp = '*ELEMENT, TYPE=S8%s, ELSET=%s\n' % (elSuffix, partpid)
        outf.write(tmp)
        eflagq8 = 0
    tmp = '%8i,%8i,%8i,%8i,%8i,%8i,%8i,\n' % (
        int(lin[8:16]), int(lin[24:32]), int(lin[32:40]), int(lin[40:48]), int(lin[48:56]), int(lin[56:64]), int(lin[64:72]))
    outf.write(tmp)
    lin = inl[cnt1]
    cnt1 = cnt1 + 1
    tmp = '%8i,%8i\n' % (
        int(lin[8:16]), int(lin[16:24]))
    outf.write(tmp)

    eltype[int(lin[8:16])] = 1
    return cpid, eflagq8


def process_cbeam(NodeDict, beamOri, cpid, eflagbeam, eltype, lin, outf, partName, pidOri, pidname):
    if eflagbeam == 1 or (cpid != int(lin[16:24])):
        cpid = int(lin[16:24])
        partpid = '%s_PID_%i' % (partName, cpid)
        pidname[partpid] = [cpid, 'beam']
        pidOri[cpid] = [convert_real2(lin[40:48]), convert_real2(lin[48:56]),
                        convert_real2(lin[56:64])]
        beamOri[cpid] = Xprod(NodeDict[int(lin[24:32])], NodeDict[int(lin[32:40])], pidOri[cpid])
#        print(pidOri[cpid])
#        print(beamOri[cpid])
        tmp = '*ELEMENT, TYPE=B33, ELSET=%s\n' % (partpid)
        outf.write(tmp)
        eflagbeam = 0
    # try to switch connectivity in order to get orientation right..
    tmp = '%8i,%8i,%8i\n' % (int(lin[8:16]), int(lin[32:40]), int(lin[24:32]))
    #           tmp='%8i,%8i,%8i\n' %(int(lin[8:16]),int(lin[24:32]),int(lin[32:40]))
    outf.write(tmp)
    eltype[int(lin[8:16])] = 33
    return cpid, eflagbeam


def process_cbar(NodeDict, beamOri, cpid, eflagbar, eltype, lin, outf, partName, pidOri, pidname):
    if eflagbar == 1 or (cpid != int(lin[16:24])):
        cpid = int(lin[16:24])
        partpid = '%s_PID_%i' % (partName, cpid)
        pidname[partpid] = [cpid, 'beam']
        pidOri[cpid] = [convert_real2(lin[40:48]), convert_real2(lin[48:56]),
                        convert_real2(lin[56:64])]
        beamOri[cpid] = Xprod(NodeDict[int(lin[24:32])], NodeDict[int(lin[32:40])], pidOri[cpid])
#        print(pidOri[cpid])
#        print(beamOri[cpid])
        tmp = '*ELEMENT, TYPE=B31, ELSET=%s\n' % (partpid)
        outf.write(tmp)
        eflagbar = 0
    # try to switch connectivity in order to get orientation right..
    tmp = '%8i,%8i,%8i\n' % (int(lin[8:16]), int(lin[32:40]), int(lin[24:32]))
    #           tmp='%8i,%8i,%8i\n' %(int(lin[8:16]),int(lin[24:32]),int(lin[32:40]))
    outf.write(tmp)
    eltype[int(lin[8:16])] = 31
    return cpid, eflagbar


# def main(exportedFilePath):    
if __name__ == "__main__":
    # bdf = exportedFilePath
    # bdf=r"C:\mandreas\dev\nas2aba_apex\Assembly2_mix_elems.bdf"
    # bdf=r"C:\AbaqusTest\BoltedBracket\CbarAndTouch\sol101_MountAssembly_v00.bdf"
    # bdf=r"C:\AbaqusTest\BoltedBracket\BoltsPreload\sol400_MountAssembly_v01.bdf"
    # bdf=r"D:\Software\Apex\TCOMS_fromIndia\BeamCheck.bdf"
    bdf=r"C:\mandreas\dev\apex2aba\test_aba\aaa.bdf"
    print('Input file ', bdf)
    # inp = process_bdf_inp(bdf)
    import cProfile
    import pstats

    prof = cProfile.Profile()
    prof.runcall(process_bdf_inp, bdf)
    prof.dump_stats('bdf_pyd1b.profile')

    #stats = pstats.Stats("bdf.profile")
    #stats.sort_stats('tottime')  # time in function
    # stats.sort_stats('cumtime')  # time in function & subfunctions
    #stats.strip_dirs()

    # print('Output file ', inp)


def fem_export_trigger(exportedFilePath):
    # set up in options/AppicationSettings/ScriptsAndCustomization

    # if os.path.isdir("C:/temp/OutTmp"):
    #    shutil.rmtree("C:/temp/OutTmp")

    process_bdf_inp(exportedFilePath)

    # if not os.path.exists(os.path.dirname(exportedFilePath)):
    #    os.makedirs(os.path.dirname(exportedFilePath))

    # file_h=open(exportedFilePath,'w')
    # file_h.write("ok")
    # file_h.close()
    print("Done")

# if __name__ == "__main__":
#    exportedFilePath=r"C:\Temp\apa\apa2.bdf"
#    fem_export_trigger(exportedFilePath)
