#-*- coding: utf-8 -*-
#EXE_TOOL v0.9 :plugin for MobilHex by fann95
class EXTENSION:
    def __init__(s,DATA,EXT):
        s.EXT=EXT#object
        #s.EXT.note("Hello")
        #s.EXT.progress(i,len(cycle))
        s.DATA=DATA#data is read from a file
        s.STRINGS=[]#found strings in unicode(s.STRINGS=[[string,color],[..,.],..])
        s.INDEX=[]#addresses beginning of text lines"""
        #reserved name in mobilhex (EXTENSION,SEARCH_STRINGS,EDIT_DATA,DATA,STRINGS,INDEX)




    def SEARCH_STRINGS(s):#algorithm for finding(nothing returning but fills a s.STRINGS and s.INDEX) 
        start=1
        if s.DATA[0x10:0x14]=='EPOC':
            if s.DATA[0x1C:0x20]=='\x00\x00\x00\x00':
                import struct
                iCodeSize=struct.unpack("<L",s.DATA[0x30:0x34])[0]
                iCodeOffset=struct.unpack("<L",s.DATA[0x64:0x68])[0]
                a=s.DATA[iCodeOffset:iCodeSize+iCodeOffset]
            else:
                start=0
                s.EXT.note("compress file is not supported")
        else:
            iCodeOffset=0
            a=s.DATA
            if len(a)<4:
                start=0
        if start==1:
                i=0
                st=''
                while i<len(a)-1:
                    s.EXT.progress(i,len(a))
                    if (a[i]=='\x00' or a[i]=='\x04') and (eval("0x"+(a[i-1].encode("hex"))) in range(32-(4*eval((a[i].encode("hex")))),128-(12*eval((a[i].encode("hex")))))):
                        st+=a[i-1:i+1]
                        i+=2;continue
                    elif st=='':
                        i+=1;continue
                    elif len(st)>=4 and (a[i-1:i+1]=='\x00\x00' or a[i-1:i+1]=='\x0a\x00' or a[i-1:i+1]=='\x09\x00' or a[i-1:i+1]=='\x0d\x00'):
                        s.STRINGS.append([st.decode("utf-16le"),0xffffff])
                        s.INDEX.append(iCodeOffset+i-1-len(st))
                        st=''
                        i=i-1;continue
                    else:
                        st=''
                        i=i-1;continue
                if s.STRINGS==[]:
                    s.EXT.note("not found")
        else:pass


    def EDIT_DATA(s,NEW_STRING,POS):#NEW_STRING string entered by the user,
                                      #POS position of strings in the list
        
        LL=len(NEW_STRING)-len(s.STRINGS[POS][0])
        if LL>0:
           NEW_STRING=NEW_STRING[:-LL]
        else:
           NEW_STRING=NEW_STRING+u' '*abs(LL)
        NEW_STRING=NEW_STRING.encode("utf-16le")
        s.DATA=s.DATA[:s.INDEX[POS]]+NEW_STRING+s.DATA[s.INDEX[POS]+len(NEW_STRING):]
        s.STRINGS[POS][0]=NEW_STRING.decode("utf-16le")
