#!/usr/bin/python
# coding: UTF-8
# Rec10 TS Recording Tools
# Copyright (C) 2009 Yukikaze
import sys
import commands
import tv2avi
import os.path
import time
import shutil
def ts2mkv(pin, pout, opt):
    dir=os.path.split(pout)[0]
    title=os.path.split(pout)[1]
    title=os.path.splitext(title)[0]
    tpavi=os.path.join(dir,title+".avi")
    tpmkv=os.path.join(dir, title+".mkv")
    tv2avi.ts2avi(pin, tpavi, opt)
    time.sleep(10)
    avi2mkv(tpavi,tpmkv)
    #shutil.move(tpavi,pout.replace(".mkv",".avi"))
    #shutil.move(tpmkv,pout)
def avi2mkv(pin,pout):
    exe = "mkvmerge"
    #doexe = exe.encode('utf-8') + u' \"' + pin.encode('utf-8') + u'\" \"' + pout.encode('utf-8') + u'\"'
    doexe = exe + u" -o '" + pout + u"' --cues 0:all --forced-track 0:no --forced-track 1:no -a 1 -d 0 -S '" + pin + u"' --track-order 0:0,0:1"
    doexe = "nice -n 17 " + doexe
    print doexe
    logo=pout.replace(".mkv",".log")
    os.environ['LANG']="ja_JP.UTF-8"
    txt= doexe+"\n"
    txt = txt+commands.getoutput(doexe)
    txt = "\n####mkvmerge-log####\n"+txt
    f=open(logo,'a')
    f.write(txt)
    f.close()
    sys.stdout.flush()