from __future__ import print_function
import os
import sys
import glob
from struct import *

def jp(*paths):
    return os.path.normcase(os.path.join(paths[0], *paths[1:]))

def opencreate(path, mode):
    path = os.path.normcase(path)
    dir = os.path.dirname(path)
    if dir != '' and not os.path.exists(dir):
        os.makedirs(dir)
    return open(path, mode)

def build(directory, name):
    img = opencreate(name+'.img', 'wb')
    dirf = opencreate(name+'.dir', 'wb')
    tablepos = img.tell()
    curpos = 0
    dir = []
    for root, dirs, files in os.walk(directory):
        for file in files:
            fname = os.path.join(root, file)
            print(fname, file)
            f = open(fname, 'rb')
            data = f.read()
            f.close()
            img.write(data)
            size = (len(data)+2047)//2048
            dir.append((curpos, size, file))
            curpos += size
            img.seek(curpos*2048, 0)
    for entry in dir:
        dirf.write(pack('IHH24s', entry[0], entry[1], 0, entry[2].encode()))
    img.close()
    dirf.close()

def extract(path):
    img = open(path+".img", "rb")
    dir = open(path+".dir", "rb")
    while True:
        entry = dir.read(32)
        if entry == '':
            break
        pos, size, name = unpack('2I24s', entry)
        name = name.decode('latin')
        x = name.index('\x00')
        if x > 0:
            name = name[:x]
        lastname = name
        img.seek(pos*2048, 0)
        data = img.read(size*2048)
        print(hex(pos), hex(size), name)
        file = opencreate(jp(path+'_img', name), "wb")
        file.write(data)
        file.close()
    img.close()
    dir.close()

if len(sys.argv) > 1:
    path = sys.argv[1];
    if path[-4:] == '_img':
        build(path, path[:-4])
    if path[-4:] == '.img' or path[-4:] == '.dir':
        extract(path[:-4])
else:
    print("nothing")
