# mkimg.py
#
# Python script to generate image file compatible with Atom SDDOS
# from AtomDOS formatted disk images.
#
# Usage:
#  python mkimg.py [list file] [output binary]
#
# list file format:
#
# disk_image_filename, image description
# ....
# ....
#
# Description is capped at 13 characters.
#
# Script is quick and dirty - there is very little fancy
# error checking.
#
# You will see message indicating number of images found
# upon successful completion.
#
# Get python here:  http://www.python.org/
#
# SirMorris 2010


import sys
import array

def shortToFile(out, short):
    a = short / 256
    b = short & 255
    c = array.array('B')
    c.append(a)
    c.append(b)
    c.tofile(out)

def stringToFile(out, info):
    c = array.array('B')
    c.fromstring(info)
    c.tofile(out)

def infoToFile(out, info, state):
    info += '             '
    shortinfo = info[0:13]
    c = array.array('B')
    c.fromstring(shortinfo)
    c.append(0x88)
    c.append(0x88)
    c.append(state)
    c.tofile(out)


def main(configfile, outfile):
    try:
        IDENTITY_MAP = ''.join(chr(x) for x in range(256))
        BAD_MAP = ''.join(chr(x) for x in range(32) + [124])

        out = open(outfile, 'wb')
        shortToFile(out, 1)    
        shortToFile(out, 2)    
        shortToFile(out, 3)    
        shortToFile(out, 4)    
        stringToFile(out, 'SDDOS   ')    

        count = 0
        
        config = open(configfile, "r")
        lineList = config.readlines()
        for line in lineList:
            filenamedesc = line.split(',')
            filename = filenamedesc[0]
            test = open(filename, 'rb')
            test.seek(0,2)
            size = test.tell()
            test.close()
            if size != 102400:
                error = '** Disk image is not exactly 10240 bytes: ' + filename
                raise RuntimeError(error)

            desc = filenamedesc[1].translate(IDENTITY_MAP, BAD_MAP)
            desc.strip(' ')
            infoToFile(out, desc, 0x0f)
            count = count + 1

        fcount = count
        
        while count < 1023:
            infoToFile(out, '', 0xf0)
            count = count + 1

        for line in lineList:
            filename = line.split(',')[0]
            source = open(filename, 'rb')
            copyBuffer = source.read(128*1024)
            source.close()
            out.write(copyBuffer)

        out.close()

        print 'OK!', fcount, 'images found and compiled to', outfile

        return 0
            
    except Exception, err:
        sys.stderr.write('ERROR: %s\n' % str(err))
        return 1


if __name__ == "__main__":
    main(sys.argv[1], sys.argv[2])
