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

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

# ファイル名: add_mujoken_statement.py
# 機能: Excel上でユーザが選択した状態変数を含む条件式のネストの外側に，「無条件」イベントで実行される処理がある場合，
#	それらの処理を，各状態における処理の前後に付加する．
# 関数: getAllStatementInScope_limit, getAllIDandSTInScope, add_mujoken_statement
# 著者名: 山本椋太，若林丈紘

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

import re
import os
import shutil
import sys
from makestm import getAllStatementInScope
from makestm import getAllIDParent

LIMIT = 15

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

# 関数名: getAllStatementInScope_limit
# 機能: IDを入力すると，そのIDの中にあるSTを根こそぎリストで返す．
#       ※makestm.pyにあるgetAllStatementInScopeを使おうとしたところ，無限再帰に陥った．（原因不明）
#       　そこで本モジュール内で再帰数制限付きの関数として定義した．
# 引数
#   sequence: IDとSTの依存関係がまとめられたファイル
#   tid: IDの識別番号
#   limit_cnt: 再帰数の制限

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

def getAllStatementInScope_limit(sequence, tid,limit_cnt):
    limit_cnt += 1
    line = sequence[int(tid[2:])-1]
    row = line.split("\t")
    statement = list()
    if limit_cnt>LIMIT:
        return statement
    for r in row[1:]:
        if "ID" in r:
            temp = getAllStatementInScope_limit(sequence, r,limit_cnt)
            for t in temp:
                if t == "":continue
                statement.append(t)
        else: statement.append(r)
    i = 0
    while statement.count("") > 0:
        statement.remove("")
    return statement

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

# 関数名: getAllIDandSTInScope
# 機能: ※呼び出し元を確認できなかった
# 引数
#   tid:
#   sequence:

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

def getAllIDandSTInScope(sequence, tid):
    line = sequence[int(tid[2:])-1]
    row = line.split("\t")
    id_st = list()
    for r in row[1:]:
        if "ID" in r:
            id_st.append(r)
            temp = getAllIDandSTInScope(sequence, r)
            for t in temp:
                if t == "":continue
                id_st.append(t)
        else: id_st.append(r)
    i = 0
    while id_st.count("") > 0:
        id_st.remove("")
    return id_st

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

# 関数名: add_mujoken_statement
# 機能: 条件式に状態変数を含む制御構文の外側に無条件処理がある場合，その処理を前述の制御構文内に移動させる．
# 引数
#   param: 状態変数
#   func: 解析対象の関数名
#   directory: 解析対象の関数に関する情報がまとめられたディレクトリ

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

def add_mujoken_statement(param, func, directory):

    print("\n===============")
    print("= add_mujoken_statement =")
    print("param: ", param)
    print("func: ", func)
    print("directory: ",directory)
    print("===============\n")

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

    # 関数: add_mujoken_statement_
    # 機能： 条件式に状態変数を含む制御構文の外側に無条件処理がある場合，その処理を前述の制御構文内に移動させる
    #         ex)
    #         void func(hoge){
    #            if (event==0){
    #              if(%%%MJK%%%){
    #                 proc1();
    #              }
    #              if(state==0){
    #                 state = 1;
    #              }
    #              else{
    #                 state = 0;
    #              }
    #              if(%%%MJK%%%){
    #                 proc2();
    #              }
    #            }
    #         }
    #
    #         ↓
    #
    #         void func(hoge){
    #            if (event==0){
    #              if(state==0){
    #                 proc1();
    #                 state = 1;
    #                 proc2();
    #              }
    #              else{
    #                 proc1();
    #                 state = 0;
    #                 proc2();
    #              }
    #            }
    #         }

    # INPUT ： idlist2-4.tsv, sequence6-4.tsv, stlist3.tsv
    # OUTPUT: idlist2-5.tsv, sequence6-5.tsv, stlist4.tsv

    # INPUTの入力元 : temp/FUNCTION/ (FUNCTIONは任意の関数名)
    # OUTPUTの出力先: temp/FUNCTION/ (FUNCTIONは任意の関数名)

    # idlist2-4.tsv   : 各関数における条件式の一覧
    # stlist3.tsv     : 各関数における処理の一覧
    # sequence6-4.tsv : 条件式（ID)と，その制御構造に内包されるID，STの一覧

    # idlist2-5.tsv   : idlist2-4.tsvに本機能を適用させたファイル
    # stlist4.tsv   : stlist3.tsvにに本機能を適用させたファイル
    # sequence6-5.tsv : sequence6-4.tsvに本機能を適用させたファイル

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


    out_directory = "temp/" + directory + "/"

    # changed_170926
    rfile = out_directory + "idlist2_4.tsv"
    # rfile = out_directory + "idlist2_3.tsv"
    fi = open(rfile)
    id_lines = fi.readlines()
    fi.close()

    # changed_170926
    rfile = out_directory + "sequence6_4.tsv"
    # rfile = out_directory + "sequence6_3.tsv"
    fi = open(rfile)
    sq_lines = fi.readlines()
    fi.close()

    # changed_170926
    rfile = out_directory + "stlist3.tsv"
    # rfile = out_directory + "stlist3.tsv"
    fi = open(rfile)
    st_lines = fi.readlines()
    fi.close()

    # changed_170926
    fo_id = open(out_directory+"idlist2_5.tsv",'w')
    fo_sq = open(out_directory+"sequence6_5.tsv",'w')
    fo_st = open(out_directory+"stlist4.tsv",'w')

    state_var_cond_list = list()
    # 状態変数を含むIDを抽出
    for i, idl in enumerate(id_lines):
        idl = idl.replace("\n",'')
        row = idl.split('\t')
        if '%%%MJK%%%' in row[1]:continue
        if re.match('(if\()|(else[ \t]+if\()', row[1]) :
            if re.search("[ \+\-\*\\&\|%/=\(\)]"+param+"[ \+\-\*\\&\|%/=\(\)]", row[1]):
                state_var_cond_list.append(row)
            print(row)
            pass
        else:
            tarnest = row[2]
            templist = id_lines[:i]
            templist.reverse()
            for tl in templist:
                tl = tl.replace('\n','')
                trow = tl.split('\t')
                if trow[2] != row[2] : continue
                if re.search("[ \+\-\*\\&\|%/=\(\)]"+param+"[ \+\-\*\\&\|%/=\(\)]", trow[1]):
                    state_var_cond_list.append(row)
#                    print('trow:', trow)
                    break
                else:break

#        print(row)

    print(state_var_cond_list)
    print('--------')

    ifblock_list = list()
    ilcnt = 0 - 1

    # 状態変数を含む条件文をブロックごとにわける
    # 制約: 異なる変数が1ブロック内に2つ存在しない
    for i, svcl in enumerate(state_var_cond_list):
        if re.match('if\(', svcl[1]) :
            ifblock_list.append([svcl])
            ilcnt += 1
            templist = state_var_cond_list[i+1:]
            cur_nest = svcl[2]
            for tl in templist:
#                print(tl,templist)
                if tl[2] != cur_nest:continue
                if re.match('if\(', tl[1]) :break
                ifblock_list[ilcnt].append(tl)

    premjk = list()
    postmjk = list()
    ilcnt = 0 - 1
    for ibl in ifblock_list: # 各ブロックに分割
        premjk.append([])
        postmjk.append([])
        ilcnt += 1
        headif = ibl[0] # 先頭がifになっているはずなので先頭をとる．
        headid = int(headif[0][2:]) - 1 # IDとリストのインデックスのギャップを吸収
        headnest = int(headif[2])
        templist = id_lines[:headid] # 結局終端は未満であるため，＋1しないとだめになる．
        templist.reverse()

        for tl in templist:
            tl = tl.replace('\n','')
            trow = tl.split('\t')
            if headnest < int(trow[2]):continue
            elif headnest == int(trow[2]):
                if '%%%MJK%%%' in trow[1]: premjk[ilcnt].append(trow)
                else: break
            else: break

        tailif = ibl[-1] # 終端がelseまたは最後のelifになっているはず
        tailid = int(tailif[0][2:]) - 1 # IDとリストのインデックスのギャップを吸収
        tailnest = int(tailif[2])
        templist = id_lines[tailid+1:]

        for tl in templist:
            tl = tl.replace('\n','')
            trow = tl.split('\t')
            if headnest < int(trow[2]):continue
            elif headnest == int(trow[2]):
                if '%%%MJK%%%' in trow[1]: postmjk[ilcnt].append(trow)
                else: break
            else: break

    seqlist = list()
    for sl in sq_lines:
        sl = sl.replace('\n','')
        seqlist.append(sl.split('\t'))
        while seqlist[-1][-1] == '':
            seqlist[-1] = seqlist[-1][:-1]


    for i, ifl in enumerate(ifblock_list):
        for cond in ifl:
            target = int(cond[0][2:]) - 1
            preinsid = ''
            for pm in premjk[i]:
                preinsid += pm[0]
            postinsid = ''
            for pm in postmjk[i]: postinsid += pm[0]
            seqlist[target] = [seqlist[target][0], preinsid] + seqlist[target][1:] + [postinsid]
            while seqlist[target][-1] == '':
                seqlist[target] = seqlist[target][:-1]

    print(seqlist)
    print('=========')
    print(premjk)
    print(postmjk)
    print("ecp")

    for idl in id_lines:
        print(idl,end='',file=fo_id)
    for sql in seqlist:
        outstr = ''
        for sq in sql: outstr += sq + '\t'
        outstr = outstr[:-1]
        print(outstr, file=fo_sq)
    for stl in st_lines:
        print(stl,end='',file=fo_st)


    fo_id.close()
    fo_sq.close()
    fo_st.close()

    return


    # fo_id = open(out_directory+"idlist2_4.tsv",'w')
    # fo_sq = open(out_directory+"sequence6_4.tsv",'w')
    # fo_st = open(out_directory+"stlist3.tsv",'w')

    # id_linesから，状態遷移直前にある無条件処理のイベントを削除して，preid_linesに格納する
    # 状態遷移直後にある無条件処理のイベントを削除して，postid_linesに格納する
    # ex)の場合，preid_linesにはproc1()のMJK, postid_linesにはproc2()のMJKが格納される
    # ex)
    # void func(hoge){
    #    if (event==0){
    #      if(%%%MJK%%%){
    #         proc1();
    #      }
    #      if(state==0){
    #         state = 1;
    #      }
    #      else{
    #         state = 0;
    #      }
    #      if(%%%MJK%%%){
    #         proc2();
    #      }
    #    }
    # }
    newid_lines = []
    id_line_type = "PRE"
    jotai_nest = 0
    preid_lines = []
    postid_lines = []
    start_preids = []
    start_postids = []
    #added_170925
    pre_events = []
    outermost_event_nest = 0

    for i,id_line in enumerate(id_lines):
        parentids = []
        temp = id_line.split("\t")
        not_MJKevent_flg = False
        id = temp[0]
        code = temp[1]
        nest = int(temp[2])

        if i != 0:
            prev_temp = id_lines[i-1].split("\t")
            prev_code = prev_temp[1]
            prev_nest = int(prev_temp[2])
        else:
            prev_code = ""
            prev_nest = 0

        if nest <= prev_nest and id_line_type == "JOTAI_ELSE":
            id_line_type = "POST"
            #added_170925
            if len(pre_events)!=0:
                outermost_event_nest = int(pre_events[0][2])

        if param in code and code[:2] == "if" and id_line_type == "PRE":
            jotai_nest = nest
            id_line_type = "JOTAI"

        if nest == jotai_nest and id_line_type == "JOTAI" and re.match("else\s*$",code):
            id_line_type = "JOTAI_ELSE"

        # added_170925
        if id_line_type == "POST" and nest <= outermost_event_nest and "%%%MJK%%%" not in code:
            id_line_type = "END"

       # ＊getAllStatementInScope_limitの説明
       # makestm.pyにあるgetAllStatementInScopeを使おうとしたところ，無限再帰に陥った（原因不明）
       # そこで本モジュール内で再帰数制限付きの関数として定義した
        childsts = [st for st in getAllStatementInScope_limit(sq_lines,id,1) if st != "\n"]
        for childst in childsts:
            parentids.extend(getAllIDParent(sq_lines,childst))
        parentids = list(set(parentids))
        for parentid in parentids:
            for id_line2 in id_lines:
                id2 = id_line2.split("\t")[0]
                code2 = id_line2.split("\t")[1]
                if parentid == id2 and param in code2:
                    not_MJKevent_flg = True
                    break

        #added_170925
        if id_line_type == "PRE" and code[:2] == "if":
            pre_events.append(temp)

        if id_line_type == "PRE" and "%%%MJK%%%" in code and not_MJKevent_flg == False:
            newnest = nest
            id_line = id + "\t" + code + "\t" + str(newnest)
            preid_lines.append(id_line)
            if "%%%MJK%%%" not in prev_code:
                start_preids.append(id)
        elif id_line_type == "POST" and "%%%MJK%%%" in code:
            newnest = nest
            id_line = id + "\t" + code + "\t" + str(newnest)
            postid_lines.append(id_line)
            if prev_nest >= nest :
                start_postids.append(id)
        else:
            newid_lines.append(id_line)

        print(i,code,id_line_type)

    id_lines = newid_lines

    print("ID_LINES",id_lines)
    print("PREID_LINES",preid_lines)
    print("START_PREIDS",start_preids)
    print("POSTID_LINES",postid_lines)
    print("START_POSTIDS",start_postids)

    # 1)状態遷移直前の無条件処理，2)直後の無条件処理，
    # 1)2)のいずれも発生しない場合は，以降の処理はいらないので，
    # idlines2-4.tsv, stlist3.tsv, sequence6-4.tsvに書き出して終了する
    if len(preid_lines) == 0 and len(postid_lines) == 0:
        for id_line in id_lines:
            print (id_line,file=fo_id,end="")
        fo_id.close()
        for st_line in st_lines:
            print (st_line,file=fo_st,end="")
        fo_st.close()
        for sq_line in sq_lines:
            print (sq_line,file=fo_sq,end="")
        fo_sq.close()
        return

    preids = [preid_line.split("\t")[0] for preid_line in preid_lines]
    postids = [postid_line.split("\t")[0] for postid_line in postid_lines]

    print("ID_LINES",id_lines)
    print(preids,postids,start_preids,start_postids)

    # changed_170925
    # (格納の処理をまとめるため，sequenceへ格納する処理をid_lines挿入処理より前に移動させた)
    # 状態遷移のネストの外側にある無条件処理のsequenceをpre_sqs, post_sqsに格納する
    newsq_lines = []
    pre_sqs = []
    post_sqs = []
    ins_mjknum = 0

    for i,sq_line in enumerate(sq_lines):
        ids = sq_line.replace("\n","").split("\t")
        target_id = ids[0]
        if target_id in preids:
            pre_sqs.append(sq_line)
            continue
        elif target_id in postids:
            post_sqs.append(sq_line)
            continue

        newsq_lines.append(sq_line)

    # 移動ここまで---

    print(pre_sqs,post_sqs)
    print(preid_lines,postid_lines)

    # added_170926
    # 状態遷移のブロックに挿入される条件式(preid_lines,post_idlines)のうち，
    # 一番内側にある無条件を削除する
    # ※挿入されることで，状態遷移の条件式1つぶん，ネストがずれてしまう．
    # このため，列幅調整のために無条件を削除しなければならない

    pre_replacedID = ()
    post_replacedID = ()

    if len(start_preids)!=0:
        for i,preid_line in enumerate(preid_lines):
            tmp = preid_line.split('\t')
            nest = int(tmp[2])
            tmp[2] = str(nest+1)
            preid_lines[i] = '\t'.join(tmp)

        new_pre_sqs = []
        replaced_IDs = []
        for i,presq in enumerate(reversed(pre_sqs)):
            tmp = presq.split('\t',1)
            target_id = tmp[0]
            tmp = tmp[1].rsplit('\t',1)
            other_ids = tmp[0]
            print(target_id,other_ids,replaced_IDs)

            if i != 0:
                for repID in replaced_IDs:
                    if repID[0] in other_ids:
                        other_ids = other_ids.replace(repID[0],repID[1])

            replaced_IDs.append((target_id,other_ids))
            new_pre_sqs.append('\t'.join([target_id,other_ids,tmp[1]]))

        pre_sqs = new_pre_sqs
        pre_sqs.reverse()

        preid_lines.pop()
        pre_sqs.pop()
        preids.pop()
        if len(pre_sqs)==0:
            pre_replacedID = replaced_IDs[0]


    if len(start_postids)!=0:
        for i,postid_line in enumerate(postid_lines):
            tmp = postid_line.split('\t')
            nest = int(tmp[2])
            tmp[2] = str(nest+1)
            postid_lines[i] = '\t'.join(tmp)

        new_post_sqs = []
        replaced_IDs = []
        for i,postsq in enumerate(reversed(post_sqs)):
            tmp = postsq.split('\t',1)
            target_id = tmp[0]
            tmp = tmp[1].rsplit('\t',1)
            other_ids = tmp[0]
            print(target_id,other_ids,replaced_IDs)

            if i != 0:
                for repID in replaced_IDs:
                    if repID[0] in other_ids:
                        other_ids = other_ids.replace(repID[0],repID[1])

            replaced_IDs.append((target_id,other_ids))
            new_post_sqs.append('\t'.join([target_id,other_ids,tmp[1]]))
        post_sqs = new_post_sqs
        post_sqs.reverse()

        postid_lines.pop()
        post_sqs.pop()
        postids.pop()
        if len(post_sqs)==0:
            post_replacedID = replaced_IDs[0]

    # 追加ここまで---

    # id_linesのうち，状態変数を含む条件式が現れたらその直前にpreid_linesを挿入する
    # また，その条件式内の処理が終わる直後にpostid_linesを挿入する
    newid_lines =[]
    jotai_ids = []
    jotaiflg = False
    #newMJKids = [] # deleted_170925

    for i,id_line in enumerate(id_lines):
        nest_cnt = 1
        start_preid_num = 0
        start_postid_num = 0

        temp = id_line.split("\t")
        id = temp[0]
        code = temp[1]
        nest = int(temp[2])

        # deleted_170925
        # newMJKid = id+"mjk"
        # newMJKcode = "if(%%%MJK%%%)"
        # newMJKnest = str(jotai_nest + 1)
        # newMJKid_line = "\t".join([newMJKid,newMJKcode,newMJKnest]) + "\n"

        if param in code and code[:2] == "if" and jotaiflg == False:
            jotai_nest = nest
            jotaiflg = True

        newid_lines.append(id_line)

        # 状態遷移直前に無条件処理を挿入する
        if jotaiflg == True and nest == jotai_nest:
            MJK_insert_flg = False
            jotai_ids.append(id)

            for preid_line in preid_lines:
                pre_temp = preid_line.split("\t")
                pre_id = pre_temp[0]
                pre_code = pre_temp[1]

                if start_preid_num < len(start_preids):
                    if start_preids[start_preid_num] == pre_id:
                        start_preid_num += 1
                        nest_cnt = 1
                pre_nest = str(jotai_nest + nest_cnt)

                new_preid_line = "\t".join([pre_id,pre_code,pre_nest]) + "\n"
                newid_lines.append(new_preid_line)
                pre_id = preid_line.split("\t")[0]
                nest_cnt += 1

            # deleted_170925
            # newid_lines.append(newMJKid_line)
            # newMJKids.append(newMJKid)
            # MJK_insert_flg = True

        # changed_170925
        # (元コードが冗長であるため簡潔に書き直した）
        # 状態遷移直後に無条件処理を挿入する
        if i != len(id_lines)-1:
            nextnest = int(id_lines[i+1].split("\t")[2])
            if not (jotaiflg == True and nextnest == jotai_nest):
                continue

        for postid_line in postid_lines:

            post_temp = postid_line.split("\t")
            post_id = post_temp[0]
            post_code = post_temp[1]

            if start_postid_num < len(start_postids):
                if start_postids[start_postid_num] == post_id:
                    start_postid_num += 1
                    nest_cnt = 1
            post_nest = str(jotai_nest + nest_cnt)

            new_postid_line = "\t".join([post_id,post_code,post_nest]) + "\n"
            newid_lines.append(new_postid_line)
            post_id = postid_line.split("t")[0]
            nest_cnt += 1

        # 修正ここまで---

    id_lines = newid_lines

    # added_170926
    # 直前の無条件処理（presqs)と直後の無条件処理（postsqs)に挟まれる処理ori_insert_sqlinesと
    # それら3つの処理が結びつく条件式（状態変数が評価される式）ori_insert_startidsを取得する
    ori_insert_startids = []
    ori_insert_sqlines = []
    j = 0

    for i,sq_line in enumerate(sq_lines):
        tmp = sq_line.split('\t')
        target_id = tmp[0]
        other_ids = tmp[1:-1]
        if target_id in jotai_ids:
            ori_insert_startids.append(other_ids)

    for i,ois in enumerate(ori_insert_startids):
        for j,sq_line in enumerate(sq_lines):
            tmp = sq_line.split('\t')
            target_id = tmp[0]
            if target_id in ois:
                print(ois,target_id)
                ori_insert_sqlines.append(sq_line)
                break


    ori_insert_startids_flat = []
    for ois in ori_insert_startids:
        ori_insert_startids_flat.append(ois[0])

    print("jotai_ids",jotai_ids)
    print("ori_insert",ori_insert_startids)
    print("ori_sqlines",ori_insert_sqlines)

    # 追加ここまで---

    # 状態遷移のネストの外側にある無条件処理のsequence(pre_sqs, post_sqs)を，
    # sq_linesに挿入する
    sq_lines = newsq_lines
    newsq_lines = []
    else_insert_flg = False

    ins_mjknum = 0
    pre_insert_flg = False

    if len(jotai_ids)>0:
        deepest_event_id = "ID" + str(int(jotai_ids[0][2:])-1)
    else:
        deepest_event_id = "ID0"

    for i,sq_line in enumerate(sq_lines):
        insert_lines = []
        newsq_line = ""
        ids = sq_line.replace("\n","").split("\t")
        target_id = ids[0]

        # added_170926
        if target_id in ori_insert_startids_flat:
            continue

        for id_line in id_lines:
            print(id_lines)
            if target_id == id_line.split("\t")[0]:
                target_nest = int(id_line.split("\t")[2])
                break

        ids = [id for id in ids\
                             if (id not in start_preids) and (id not in start_postids) and ('' is not id)]

        if i == 0:
             ids = [id for id in ids\
                         if (id not in jotai_ids)]
        if target_id == deepest_event_id:
            for jotai_id in jotai_ids:
                if jotai_id not in ids:
                    ids.append(jotai_id)

        if target_id in jotai_ids:
            insert_ids = [target_id]
            insert_ids.extend(start_preids)
            # changed_170926
            #insert_ids.append(newMJKids[ins_mjknum])
            insert_ids.extend(ori_insert_startids[ins_mjknum])
            insert_ids.extend(start_postids)
            insert_line = "\t".join(insert_ids) + "\t\n"

            # added_170926
            if pre_replacedID != ():
                insert_line = insert_line.replace(pre_replacedID[0],pre_replacedID[1])
            if post_replacedID != ():
                insert_line = insert_line.replace(post_replacedID[0],post_replacedID[1])

            insert_lines.append(insert_line)

            if len(start_preids)>0:
                for j,presq in enumerate(pre_sqs):
                    insert_lines.append(presq)

            # added_170926
            if ori_insert_sqlines != []:
                insert_lines.append(ori_insert_sqlines[ins_mjknum])

            if len(start_postids)>0:
                for j,postsq in enumerate(post_sqs):
                    insert_lines.append(postsq)

            for pre_id in preids:
                for j,insert_line in enumerate(insert_lines):
                    ins_ids = insert_line.split("\t")
                    for k,ins_id in enumerate(ins_ids):
                        if pre_id == ins_id:
                            ins_ids[k] = ins_id + "ins"+str(i)
                    insert_lines[j] = "\t".join(ins_ids)

            for post_id in postids:
                for j,insert_line in enumerate(insert_lines):
                    ins_ids = insert_line.split("\t")
                    for k,ins_id in enumerate(ins_ids):
                        if post_id == ins_id:
                            ins_ids[k] = ins_id + "ins"+str(i)
                    insert_lines[j] = "\t".join(ins_ids)
            print("INSERT",insert_lines,st_lines)
            ins_mjknum +=1
        else:
            newsq_line = "\t".join(ids) + "\t\n"
            newsq_lines.append(newsq_line)
        newsq_lines.extend(insert_lines)

    sq_lines = newsq_lines


    # 無条件処理を挿入したid_lines, sq_linesのID番号を振り直す
    idcnt = 1
    jotaicnt = 0
    newid_lines = []
    newsq_lines = []
    id_reassigns = []

    for i,sq_line in enumerate(sq_lines):
        sq_temp = sq_line.split("\t",1)
        sq_id = sq_temp[0]
        rest_sq_line = sq_temp[1]

        il_temp = id_lines[i].split("\t",1)
        il_id = il_temp[0]
        rest_id_line = il_temp[1]

        reassign_id = "ID" + str(idcnt)
        id_reassigns.append((sq_id,reassign_id + "new"))

        newsq_line = reassign_id + "new" + "\t" + rest_sq_line
        newsq_lines.append(newsq_line)

        newid_line = reassign_id + "\t" + rest_id_line
        newid_lines.append(newid_line)
        idcnt += 1

    id_lines = newid_lines
    sq_lines = newsq_lines

    reassign_cnt = 0
    for i,sq_line in enumerate(sq_lines):
        ids = sq_line.split("\t")
        for j,target_id in enumerate(ids):
            for re_id in id_reassigns:
                if target_id == re_id[0]:
                    ids[j] = re_id[1]
                ids[j] = ids[j].replace("new","")
        sq_lines[i] = "\t".join(ids)



    # sq_linesのST番号を振り直し，番号に合わせてstを並べ直す
    stcnt = 1
    newst_lines = []

    for i, seq in enumerate(sq_lines):
        row = seq.replace("\n","").split("\t")
        line = ""
        for r in row:
            if "ID" in r:
                line += r+"\t"
                continue
            if "ST" in r:
                stnum = int(r[2:])
                newst_lines.append(st_lines[stnum-1])
                line += "ST" + str(stcnt) + "\t"
                stcnt += 1
        sq_lines[i] = line + "\n"

    st_lines = newst_lines
    stnum_move_flg = False


    # idlines2-4.tsv, stlist3.tsv, sequence6-4.tsvに書き出す
    for id_line in id_lines:
        print (id_line,file=fo_id,end="")
    fo_id.close()

    for i,st_line in enumerate(st_lines):
        print (st_line,file=fo_st,end="")
    fo_st.close()

    for sq_line in sq_lines:
        print (sq_line,file=fo_sq,end="")
    fo_sq.close()

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