#!/usr/bin/env python
# coding: Shift_JIS

# ##############################

# ファイル名: jokenshori.py
# 機能: 条件処理表を作成するためのセル情報（関数ごと）を出力する．
# 関数: CheckStatementNumber, CheckSequencer, jokenshori
# 著者名: 山本椋太，若林丈紘

# ##############################

#from parse import *

import re
import os
import shutil
import sys

# ##############################

# 関数名: CheckStatementNumber
# 機能: statementの数を確認する．
# 引数
#   ID: 関数，および条件文を識別する識別番号
#   IDlist: 関数，および条件文のリスト

# ##############################

def CheckStatementNumber(ID,IDlist):
    check = IDlist[ID-1]
    check = check.replace("\t\n","\n")
    check = check.replace("\n","")
    check = check.split("\t")
    check = check[1:]


    statements = 0
    for c in check:
        if c[-1] == "\n":
            c = c[:-1]
        if re.match("ID",c):
            num = int(c[2:])
            statements += CheckStatementNumber(num,IDlist)
        elif re.match("ST",c):
            statements += 1
        elif re.match("None",c):
            return 0
        else:
            statements = -9999999
    return statements

# ##############################

# 関数名: CheckSequencer
# 機能: IF文の登場順序にソート
# 引数
#   ID: 関数，および条件文を識別する識別番号
#   IDlist: 関数，および条件文のリスト
#   alldata: 条件文の依存関係を表すリスト
#   fout: 出力先の情報

# ##############################

def CheckSequencer(ID,IDlist,alldata,fout):
    check = alldata[ID-1]
    check = check.split("\t")
    check[0] = check[0].replace("\n","")
    print(check[0],file=fout)
    IDlist.remove(check[0])
    if len(IDlist) == 0:
        return IDlist
    if len(check) == 1:
        return IDlist
    check = check[1:]
    for c in check:
        nextid = int(c[2:])
        IDlist = CheckSequencer(nextid,IDlist,alldata,fout)
    return IDlist

# ##############################

# 関数名: jokenshori
# 機能: 条件処理表を作成するためのセル情報（関数ごと）を出力する．
# 引数
#   readFile: 解析対象のcファイル
# ##############################

def jokenshori(readFile):

    ###############################
    # row[0]:ID,
    # row[1]:CodeStart
    # row[2]:Code itself
    # row[3]:Nest
    # row[4]:Number of Line
    # row[5]:Parent Node

    ID = 0
    CS = 1
    CO = 2
    NS = 3
    NL = 4
    PN = 5

    ###############################


    fi = open(readFile)
    lines = fi.readlines()
    fi.close()

    fo = open("temp/temp3.tsv",'w')
    i = 1
    lista = 1

    ##################################
    # ベースになる構文解析。
    # {}を見つけることと、＠＠＠のネスト・プログラムの行数などを
    # 出力している
    ##################################

    #
    # ここでの出力フォーマット
    # ID番号, 行数, ネスト
    #

    mostdeep = 0

    for line in lines:
        nest = len(line.split('\t')) - 1	    # tabからネストを求めている
        if mostdeep < nest:
            mostdeep = nest
        if re.match("[ \t]*{",line):
            print("{{" + str(i) + "\t" + str(lista) + "\t" + str(nest) + "\t", file=fo)
            i += 1

        elif re.match("[ \t]*}",line):
            print("}}" + str(i) + "\t" + str(lista) + "\t" + str(nest) + "\t", file=fo)
            i += 1

        elif re.search('@@@',line) != None:
            line = line.replace("\t","")
            print("ID"+str(i)+"\t"+str(lista)+ "\t" +line[:-1]+ "\t" + str(nest) + "\t", file=fo)
            i += 1
        lista += 1
    fo.close()

    fo = open("temp/allprogram.tsv", 'w')
    i = 1
    j = 1
    lista = 1

    ##################################
    # ベースになる構文解析2。
    # {}を除き、ステートメントにタグ付け
    # している.ただしタブ区切り
    ##################################

    #
    # ここでの出力フォーマット
    # ID番号orST番号, 行数, C言語記述, ネスト
    #


    for line in lines:
        if re.match("[ \t]*{",line) or re.match("[ \t]*}",line):
            temp = line.split('\t')
            nest = len(temp)-1

        elif re.search('@@@',line):
            temp = line.split('\t')
            nest = len(temp)-1
            line = line.replace("\t","")
            print("ID" + str(i) + "\t" + str(lista) + "\t" + line[:-1] + "\t" + str(nest) + "\t", file=fo)
            i += 1

        else:
            temp = line.split("\t")
            nest = len(temp) - 1
            temp = temp[-1]
            print("ST" + str(j) + "\t" + str(lista) + "\t" + temp[:-1] + "\t"+str(nest),file=fo)
            j += 1
        lista += 1
    fo.close()

    idmujoken = i


    ###############################################
    ## 実行順序の親子関係ファイルの作成
    ###############################################
    rfile = "temp/allprogram.tsv"
    fi = open(rfile,"r")
    lines = fi.readlines()
    fi.close()

    fo =  open("temp/sequence.tsv",'w')

    i=1
    j = 0
    for counter,line in enumerate(lines):
        row = line.split("\t")
        lines2 = lines[i:]
        now = int(row[NS])
        outStr = ""
        if re.match("ST",row[ID]):
            i+=1
            continue

        ## row[ID]がIDだったら
        outStr += row[ID]
        for line2 in lines2:
            row2 = line2.split("\t")
            if now + 1 == int(row2[NS]):
                outStr += "\t" + row2[ID]
            if now == int(row2[NS]):
                break
        if len(outStr.split("\t")) > 1:
            print(outStr,file=fo)
        else:
            print(outStr+"\tNone",file=fo)
        i+=1
    fo.close()


    #
    #allprogramからIDリストだけ取り出す
    #
    rfile = "temp/allprogram.tsv"
    fi = open(rfile,"r")
    lines = fi.readlines()
    fi.close()

    fo =  open("temp/idlist.tsv",'w')

    for line in lines:
        if re.match("ID",line):
            line = line.replace("FC@@@","")
            line = line.replace("EI@@@","")
            line = line.replace("EL@@@","")
            line = line.replace("IF@@@","")
            line = line.replace("SW@@@","")
            line = line.replace("CS@@@","")
            line = line.replace("DF@@@","")
            row = line.split("\t")
            outstr = row[0] + "\t" + row[2] + "\t" + row[3]
            print(outstr,file=fo)
    fo.close()



    #
    #allprogramからSTリストだけ取り出す
    #
    rfile = "temp/allprogram.tsv"
    fi = open(rfile,"r")
    lines = fi.readlines()
    fi.close()

    fo =  open("temp/stlist.tsv",'w')

    for line in lines:
        if re.match("ST",line):
            row = line.split("\t")
            outstr = row[2]
            print(outstr,file=fo)
    fo.close()

    #
    # 無条件の処理
    #
    fi =  open("temp/sequence.tsv",'r')
    lines = fi.readlines()
    fi.close()

    fi =  open("temp/idlist.tsv",'r')
    lines2 = fi.readlines()
    fi.close()

    fo =  open("temp/sequence2.tsv",'w')
    fo2 =  open("temp/idlist.tsv",'a')

    mujokens = ""
    i = 0
    for line in lines:
        row2 = lines2[i].split("\t")
        nest = row2[2]
        nest = int(nest[:-1])

        if int(nest) != mostdeep-1:
            row = line.split("\t")
            Outstring1 = row[0] + "\t"
            Outstring2 = ""
            Outstring3 = ""
            tags = row[1:]
            j = 0
            tmax = len(tags)
            while(j < tmax):
                addMJKnum = 0
                if re.match("ST",tags[j]):
                    mujokens = mujokens + "\nID" + str(idmujoken)

                    while ((mostdeep-1)-nest > 1):
                        idmujoken += 1
                        mujokens = mujokens + "\tID" + str(idmujoken) + "\nID" + str(idmujoken)
                        Outstring3 += "ID"+str(idmujoken-1) + "\tif(%%%MJK%%%)\t" + str(int(nest)+1) + "\n"
                        addMJKnum += 1
                        nest += 1
                    print(Outstring3,file=fo2,end="")

                    while(j < tmax):
                        if re.match("ST",tags[j]) == None:
                            break
                        mujokens = mujokens + "\t" + tags[j]
                        j += 1
                    mujokens += "\n"
                    Outstring1 += "ID"+str(idmujoken-addMJKnum)+"\t"
                    Outstring2 += "ID"+str(idmujoken) + "\tif(%%%MJK%%%)\t" + str(int(nest)+1) + "\n"
                    print(Outstring2,file=fo2,end="")
                    idmujoken += 1
                    j -= 1
                else:
                    Outstring1 += tags[j]+"\t"
                j += 1
            print(Outstring1,file=fo)
        else:
            print(line,file=fo,end="")
        i += 1
    print(mujokens,file=fo)

    fo2.close()
    fo.close()

    fi =  open("temp/sequence2.tsv",'r')
    lines = fi.read()
    fi.close()
    fo =  open("temp/sequence3.tsv",'w')

    while "\n\n" in lines:
        lines = lines.replace("\n\t","\n")
        lines = lines.replace("\n\n","\n")
    print(lines,end="",file = fo)
    fo.close()

    ####
    #  ID の再ソートのための下ごしらえ
    ####

    fi =  open("temp/sequence3.tsv",'r')
    lines = fi.readlines()
    fi.close()
    fo =  open("temp/seq_simple.tsv",'w')

    idlist = [""]


    for line in lines:
        row = line.split("\t")
        idlist.append(row[0])
    del idlist[0]

    newlines = []
    for line in lines:
        row = line.split("\t")
        pointed = row[0]
        row = row[1:]
        newline = ""
        for r in row:
            if re.match("ID",r):
                newline = newline + r + "\t"
        if len(newline) !=0:
            newline = newline[:-1]
            newlines.append(pointed + "\t" + newline)
        else:
            newlines.append(pointed)

    i = 1
    while len(idlist) > 0:
        pointed = "ID" + str(i)
        if pointed not in idlist:
            i += 1
            continue
        idlist = CheckSequencer(i,idlist,newlines,fo)
    fo.close()



    fi =  open("temp/seq_simple.tsv",'r')
    lines2 = fi.readlines()
    fi.close()
    fi =  open("temp/idlist.tsv",'r')
    lines3 = fi.readlines()
    fi.close()


    fo =  open("temp/sequence4.tsv",'w')
    fo2 =  open("temp/idlist2.tsv",'w')

    maxarr = len(lines)
    i = 0

    while i < maxarr:
        line2 = lines2[i]
        indexarr = int(line2[2:-1])
        print(lines[indexarr-1],file=fo,end="")
        line3 = lines3[indexarr-1]
        row3 = line3.split("\t")
        print("ID" + str(i+1) + "\t" + row3[1] + "\t" + row3[2],file=fo2,end="")
        i += 1

    fo.close()
    fo2.close()


    #
    #
    #

    fi =  open("temp/sequence4.tsv",'r')
    lines = fi.readlines()
    fi.close()

    fo =  open("temp/idconvertrule.tsv",'w')

    idcnt = 1
    for line in lines:
        row = line.split("\t")
        row = row[0]
        idnum = int(row[2:])
        if idnum != idcnt:
            print(str(idnum)+"\t"+str(idcnt),file=fo)
        idcnt += 1
    fo.close()

    fi =  open("temp/idconvertrule.tsv",'r')
    lines2 = fi.readlines()

    origins = [int(row.split("\t")[0]) for row in lines2]
    convto = [int(row.split("\t")[1][:-1]) for row in lines2]

    fi.close()

    fo =  open("temp/sequence5.tsv",'w')

    idcnt = 1
    for line in lines:
        row = line.split("\t")
        row[-1] = row[-1][:-1]
        for r in row:
            if "ST" in r:
                print(r + "\t",end="",file=fo)
                continue
            if len(r) == 0:
                continue
            if r == "None":
                continue
            idnum = int(r[2:])
            if idnum in origins:
                i = 0
                while(i < len(origins)):
                    if idnum == origins[i]:
                        print("ID" +str(convto[i]) + "\t",file=fo,end="")
                        break
                    i += 1
            else:
                print(r + "\t",end="",file=fo)
        print("",file=fo)
    fo.close()

    fi =  open("temp/sequence5.tsv",'r')
    lines = fi.read()
    fi.close()

    fo =  open("temp/sequence6.tsv",'w')

    while "\t\n" in lines:
        lines = lines.replace("\t\t","\t")
        lines = lines.replace("\t\n","\n")
    while "\n\n" in lines:
        lines = lines.replace("\n\n","\n")

    print(lines,file=fo,end="")
    fo.close()

    rfile = "temp/sequence6.tsv"
    fi = open(rfile,"r")
    lines = fi.readlines()
    fi.close()

    rfile = "temp/idlist2.tsv"
    fi = open(rfile,"r")
    lines2 = fi.readlines()
    fi.close()

    fo =  open("temp/jokeninfo.tsv",'w')
    i = 0
    for line in lines:
        raw = line.split("\t")
        temp = raw[0]
        num = int(temp[2:])
        result = CheckStatementNumber(num,lines)
        raw2 = lines2[i].split("\t")
        nest = raw2[2]
        print("ID" + str(num) + "\t" + str(result) + "\t" + nest,end="",file=fo)
        i += 1
    fo.close()

    rfile = "temp/jokeninfo.tsv"
    fi = open(rfile,"r")
    lines = fi.readlines()
    fi.close()

    rfile = "temp/idlist2.tsv"
    fi = open(rfile,"r")
    lines2 = fi.readlines()
    fi.close()

    lines = lines
    #fo =  open("temp/tableinfo_0.tsv",'w')
    i = 0
    offset_c = 2
    prevfunc_endrow = offset_c
    r = 1
    sy = 0
    nestmax = 0
    fcnt = 0
    filenamelist = [""]
    rows = []
    for line in lines:
        row = line.split("\t")
        temp = row[2]
        nest = int(temp[:-1])
        if nest == 0:
            r += prevfunc_endrow
            fcnt += 1
            fo.close()
            if not os.path.isdir("temp/tableinfo"):
                os.mkdir("temp/tableinfo")
            nfilename = "temp/tableinfo/tableinfo_"+str(fcnt)+".tsv"
            filenamelist.append(nfilename)
            fo =  open(nfilename,'w')
            startY = [r+1,r+1,r+1,r+1,r+1,r+1,r+1,r+1,r+1,r+1,r+1,r+1,r+1,r+1,r+1,r+1,r+1,r+1,r+1,r+1,r+1,r+1,r+1]
            r = r + 1
            prevfunc_endrow = int(row[1])
        if nestmax < nest:
            nestmax = nest
        posX = chr(ord("B") + nest)
        start = posX + str(startY[nest])
        endY = startY[nest] + int(row[1]) -1
        end   = posX + str(endY)
        startY[nest] = endY + 1
        row2 = lines2[i].split("\t")

        if nest == 0:
            rows.append(int(end[1:])-int(start[1:])+1)
        statement = row2[1]
        statement = statement.replace("T###","}")
        statement = statement.replace("H###","{")
        print(start + "\t" + end + "\t" + statement,file=fo)
        i += 1
    fo.close()


    del filenamelist[0]
    rfile = "temp/stlist.tsv"
    fi = open(rfile,"r")
    lines = fi.readlines()
    fi.close()

    i = 0
    offset_c = 2
    prevfunc_endrow = offset_c
    r = 2
    statecnt = 0
    for fn,finame in enumerate(filenamelist):
        fo =  open(finame,"a")
        if fn == 0:
            r1 = 0
            r2 = rows[0]
        else:
            r1 += rows[fn-1]
            r2 += rows[fn]

        for i in range(r1,r2):
            posX = chr(ord("B") + nestmax+1)
            posY = str(i+1+r+1)
            posXY = posX + posY
            statement = lines[statecnt][:-1]
            statement = statement.replace("T###","}")
            statement = statement.replace("H###","{")
            print(posXY + "\t" + posXY + "\t" + statement,file=fo)
            statecnt += 1
        r += 1
        fo.close()

if __name__ == '__main__':
    jokenshori(sys.argv[1])
