#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Mon Feb 10 15:24:07 2020
Convert mindmap txt file to relational database structure.
The mindmap text file marks the level by tab.
@author: ydx
"""
import os
import sys
input = sys.argv[1]
output = sys.argv[2]
f_i = open(input, mode='r', encoding='utf-8')
f_o = open(output, mode='w', encoding='utf-8')
f_o.write('name,lvl,rid,prid,bseq'+'\n')
rid = 1 #row id
bseq = 1 #branch sequence
l_rid = [1] #list of row id
l_bseq = [1] #list of branch sequence
lvl_h = 0 #level hold
lvl_max = 0 #max level
for x in f_i:
lvl = x.rstrip().count('\t')
if lvl > lvl_h:
bseq=1
f_o.write(x.strip()+','+str(lvl)+','+str(rid)+','+str(l_rid[lvl-1])+','+str(bseq)+'\n')
if lvl > lvl_max:
lvl_max = lvl
l_rid.append(rid)
l_bseq.append(bseq)
else:
l_rid[lvl] = rid
l_bseq[lvl] = bseq
rid+=1
lvl_h = lvl
elif lvl <= lvl_h:
bseq = l_bseq[lvl]+1
f_o.write(x.strip()+','+str(lvl)+','+str(rid)+','+str(l_rid[lvl-1])+','+str(bseq)+'\n')
l_rid[lvl] = rid
l_bseq[lvl] = bseq
rid+=1
lvl_h = lvl
else:
f_o.write(x.strip()+','+str(lvl)+','+str(rid)+','+str(l_rid[lvl-1])+','+str(bseq)+'\n')
l_rid[lvl] = rid
l_bseq[lvl] = bseq
f_i.close()
f_o.close()