import argparse

if __name__ == '__main__':
    parser = argparse.ArgumentParser()
    parser.add_argument('-b','--bootloader-file', help='Bootloader *.fs filename')
    parser.add_argument('-a','--application-file', help='Main application *.fs filename')
    parser.add_argument('-o','--offset', help="Byte offset for application file. Default 1MB (hex: 0x100000, decimal: 1,048,576)"
                                              " Hex can be input with \"0x\" prefix. Otherwise assumed decimal",default=0x100000)
    parser.add_argument('-f','--output-filename', help='Output *.fs filename. Default "combined.fs"',default="combined.fs")
    args=parser.parse_args()


    if args.bootloader_file is None:
        print("Need bootloader file.")
        exit()
    if args.application_file is None:
        print("Need application file.")
        exit()
    if type(args.offset) == str:
        if(args.offset.startswith("0x")):
            args.offset = int(args.offset[2:],16)
        else:
            args.offset = int(args.offset)

    num_bits = 0
    with open(args.output_filename, 'w') as ofi:
        with open(args.bootloader_file, 'r') as bfi:
            for line in bfi:
                line = line.strip()
                if line.startswith('//'):
                    # comment line, we need to save all of these in the output
                    ofi.write(line+'\n')
                else:
                    # data line. series of 1s and 0s.
                    # all we need to do is copy over to output file, and count the total bits
                    num_bits += len(line)
                    ofi.write(line+'\n')
        extra_bits = args.offset*8 - num_bits
        print(f"Bootloader: {args.bootloader_file}, length: {int(num_bits/8)}, {hex(int(num_bits/8))}")
        print(f"Offset: {args.offset}, {hex(args.offset)}")
        if extra_bits < 0:
            print("Error. Offset is less than bootloader file size.")
        while extra_bits > 512:
            ofi.write('1'*512+'\n')
            extra_bits -= 512
        if extra_bits > 0:
            ofi.write('1'*extra_bits+'\n')
        
        num_bits = 0
        # append the application file
        with open(args.application_file, 'r') as afi:
            for line in afi:
                line = line.strip()
                if line.startswith('//'):
                    # skip all these comment lines
                    pass
                else:
                    ofi.write(line+'\n')
                    num_bits += len(line)
        print(f"Application: {args.application_file}, length: {int(num_bits/8)}, {hex(int(num_bits/8))}")


