#!/usr/local/bin/python
"""
TI-89 and TI-92 ebook generator 
by Michael Huynh (mike@mikexstudios.com | http://www.mikexstudios.com)
-------------------------------
Purpose:
Since ttebkgen.exe from TI-GCC Tools can only create maximum variable sizes of
65608 bytes, large e-texts cannot be converted without splitting the file into
many parts. This script facilitates the splitting of the ebook by blocks of
user defined bytes.

Version 1 - Ported PHP version to Python
"""

import os

#Location of the file to convert into an ebook.
inputFilename = 'hamlet05.txt'
#Calculator variable name (output name)
ebkVariable = 'hamle5'
#Description that shows up on the book selection screen of the ebook reader
ebkDesc = 'Hamlet - ' #A number will be appended to the end of this
#Location of ttebkgen.exe
ebkgenProgram = 'F:\\Programs\\TIGCCdev\\tt\\bin\\ttebkgen.exe'

#-----These do not have to be changed.-----
#Temporary file generated by this script. Does not need to be modified
partFilename = inputFilename+'temp.txt'
#Arguments passed to ttebkgen.exe 
ebkArgs = '-89 -v' #-89 means generate only for the 89 -v means verbose
#ebkArgs .= ' -keepfiles' #keep temporary generated files
#How many bytes to read before splitting the file. You can leave this as it is.
thresholdChars = 60000 #TI-89 limit is 65608 bytes
    
ebkVariableCount = 0 #Appended to the end of the variable name
#------------------------------------------

#Open file for reading
inBookHandle = open(inputFilename, 'r')


while(True):
    #Read file segment by segment until the end
    inBookSeg = inBookHandle.read(thresholdChars)
    print len(inBookSeg)
    if(inBookSeg == ''):
        break

    #Write particular segment to file
    writeSegHandle = open(partFilename, 'w')
    writeSegHandle.write(inBookSeg)
    writeSegHandle.close()

    #Convert segment into TI ebook
    ebkInvokeCmd = ebkgenProgram+' '+ebkArgs+' "'+partFilename+'" '+\
                   ebkVariable+str(ebkVariableCount)+' "'+ebkDesc+str(ebkVariableCount)+'"'
    print ebkInvokeCmd
    os.system(ebkInvokeCmd) #Execute system command
 
    #Increment segment counter
    ebkVariableCount = ebkVariableCount+1

#Close file
inBookHandle.close()
    






