#!/usr/bin/env python

import sys,string,os.path,zlib

def d2s(d):
       """Converts an integer to a little-endian DWORD expressed as a string"""
       assert(d>=0 and d<256**4)
       v = [d%256, (d>>8)%256, (d>>16)%256, (d>>24)%256]
       s = string.join([chr(x) for x in v],sep='')
       return s

assert(len(sys.argv)>=2)

filedata=""
indexdata=""
numfiles = 0
for fn in sys.argv[2:]:
       fpath=string.join(os.path.normpath(fn).split(os.path.sep),'\\')
       f=open(fn,'rb').read() #the file data
       #no compression as yet
       indexdata += d2s(len(fpath))
       indexdata += fpath
       indexdata += d2s(len(filedata)) #offset of this file
       indexdata += d2s(len(f)) #file length
       indexdata += d2s(len(f)) #why it's twice I don't know
       indexdata += d2s(0) #compression flag
       indexdata += d2s(0) #would be compressed size if compressed
       filedata += f #store f in the archive
       numfiles +=1

indexcompressed = zlib.compress(indexdata)

#all files done, time to actually write the thing
outfile = open(sys.argv[1],'wb')
outfile.write(d2s(2)) #archive version 2
outfile.write(d2s(numfiles))
outfile.write(d2s(len(indexdata)))
outfile.write(d2s(len(indexcompressed)))
outfile.write(d2s(0x64)) #some sort of encryption flag thing
outfile.write("jingaimakyou"+'\x00'*244) #game identifier
outfile.write(indexcompressed)
outfile.write(filedata)
outfile.close()