# coding: Shift_JIS

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

# ファイル名: mujoken.py
# 機能: ネストの深さをチェックし，
#	対象Cファイルにおける最大の深さに満たないネストに対して無条件if文の追加を行う．
# 関数: CheckStatement, CheckHiraki, CheckToji, mujoken
# 著者名: 山本椋太，若林丈紘

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

#from parse import *
import re
import sys

##!!!!! while未対応


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

# 関数名: ChwckStatement
# 機能: 処理のみの行であるか確認する．
# 引数
#   line: 解析中の行

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

def CheckStatement(line):
    if not "@@@" in line and\
       CheckHiraki(line)==False and\
       CheckToji(line)==False and\
       not "" == line:
        return True
    else:
        return False

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

# 関数名: CheckHiraki
# 機能: 解析中の行に"{"が存在するか確認する．
# 引数
#   line: 解析中の行

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

def CheckHiraki(line):
    #if  "{" in line or\
    #    "HIRAKI###" in line:
    if  "{" in line:
        return True
    else:
        return False

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

# 関数名: ChwckToji
# 機能: 解析中の行に"}"が存在するか確認する．
# 引数
#   line: 解析中の行

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

def CheckToji(line):
    #if  "}" in line or\
    #    "TOJI###" in line:
    if  "}" in line:
        return True
    else:
        return False

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

# 関数名: mujoken
# 機能: ネストの深さをチェックし，
#	対象Cファイルにおける最大の深さに満たないネストに対して無条件if文の追加を行う．
# 引数
#   workFile1: 解析対象のcファイル
#   workFile2: 解析対象のcファイル

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

def mujoken(workFile1,workFile2):

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

    # _および#で始まる記述をすべて削除
    fo = open(workFile1,"w")
    kakko = 0
    for line in lines:
        if "}" in line:
            kakko -= 1
        if re.match("^#",line) == None and re.match("^_",line) == None:
            print(line,end="",file=fo)
        else:
            if kakko != 0:
                print(line,end="",file=fo)
        if "{" in line:
            kakko += 1
    fo.close()

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

    maxnests = []
    i = 0

    # for文の中括弧を全角にしておく
    for line in lines:
        if "FC@@@" in lines[i]:
            for j in range(i+1,len(lines)):
                if "{" in lines[j]:
                    if re.match("for[ \t]*\(",lines[j-1]):
                        forkakko = 1
                        k = j
                        for forline in lines[j:]:
                            if "{" in forline:
                                forkakko += 1
                            if "}" in forline:
                                forkakko -= 1
                            if forkakko == 1:
                                lines[k] = "TOJI###0\n"
                                break
                            k += 1
                        lines[j] = "HIRAKI###0\n"
        i += 1

    #nestの深さのチェック(for文を除く)
    maxnests = []
    i = 0
    for line in lines:
        if "FC@@@" in lines[i]:
            hirakakko = 0
            tojikakko = 0
            kakko = 0
            maxkakko = 0
            for j in range(i+1,len(lines)):
                if "{" in lines[j]:
                    kakko += 1
                    hirakakko += 1
                if "}" in lines[j]:
                    kakko -= 1
                    tojikakko += 1
                if maxkakko < kakko:
                    maxkakko = kakko
                if hirakakko == 0 and tojikakko == 0:
                    continue
                if hirakakko == tojikakko:
                    break
            temp = lines[i]
            maxnests.append(maxkakko)
        i += 1

    fo = open(workFile1,"w")
    for line in lines:
        print(line,file=fo,end="")
    fo.close()

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

    ON = 1
    OFF = 0

    open_cnt = 0
    close_cnt = 0
    nest_cnt = 0
    func_maxnest = 0
    func_cnt = 0
    new_lines = []

    MJKopen = "IF@@@if(%%%MJK%%%)\n{\n"
    MJKclose = "}\n"
    MJK_flg = OFF

    ## 無条件IF文(MJK)とカッコの追加
    for num_line,line in enumerate(lines):

        if num_line > 0:
            pre_line = lines[num_line-1]
        else:
            pre_line = ""

        if num_line < len(lines)-1:
            post_line = lines[num_line+1]
        else:
            post_line = ""

        if "FC@@@" in line:
            func_maxnest = max(maxnests)
            func_cnt += 1

        if CheckToji(line) == True:
            close_cnt +=1
            nest_cnt -=1

        if CheckHiraki(line) == True:
            open_cnt +=1
            nest_cnt +=1

        new_line = ""

        new_line = new_line + line

        if (CheckHiraki(line)==True or CheckToji(line)==True) and \
           CheckStatement(post_line)==True and \
           nest_cnt != func_maxnest:
            MJK_flg = ON
            new_line = new_line + MJKopen
            #print (new_line,"\n")

        if CheckStatement(line)==True and \
           MJK_flg == ON  and \
           CheckStatement(post_line)==False:
            MJK_flg = OFF
            new_line = new_line + MJKclose
            #new_line = new_line + MJKclose

         #無条件処理のみの関数にはMJKを追加する
        if CheckHiraki(line)==True and func_maxnest == 1:
            MJK_flg = ON
            new_line = new_line + MJKopen
            #print (new_line,"\n")

        new_lines.append(new_line)

    fo = open(workFile2,"w")
    for new_line in new_lines:
        print(new_line,end="",file=fo)
    fo.close()


    #全角括弧を半角に戻す
    fi = open(workFile2)
    lines = fi.readlines()
    fi.close()

    fo = open(workFile2,"w")
    for line in lines:
        if "TOJI###0" in line:
            line = "T###\n"
        if "TOJI###1" in line:
            line = "}\n"
        if "TOJI###2" in line:
            line = "}\n"
        if "TOJI###3" in line:
            line = "}\n"
        if "HIRAKI###0" in line:
            line = "H###\n"
        print(line,end="",file=fo)
    fo.close()

    return max(maxnests)

if __name__ == '__main__':
    mujoken(sys.argv[1],sys.argv[2])
