#!/usr/bin/python
# -*- coding: latin-1 -*-
#'- vg5000 bin2k7exec.py version 201308031534

import os,sys
finp_st=sys.argv[1];fout_st=finp_st+".k7"
strt1=0x49FB;strt2=0x4A0A;exe1=strt1

if finp_st.lower()=="--help".lower():
  print "converts a z80 binary VG5000 file starting at 0x???? into an autoexecutable .k7 file"
  print "usage: python bin2k7exec.py yourfile.bin"
  print "the result will be a neighbour file named yourfile.bin.k7"
else
  finp_fl=open(finp_st,"r")
  #? lng1=lof(1);lng2=lng1+15
  sum1=576
  while True:
    byte_st=finp_fl.read(1)
    sum1+=byte_st
  finp_fl.close()

#open finp_st for input as #1
#  lng1=lof(1):lng2=lng1+15:sum1=576
#  for i=1 to lng1
#    sum1=sum1+readbyte(1)
#    next
#  close #1

  finp_fl=open(finp_st,"r");fout_fl=open(fout_st,"w")
  for i in range(0,10,1):fout_fl.write(chr(0xD3))
  fout_fl.write(chr(0x4D))

  for i in range(0,6,1)
    #if (i+1)<=
    #else

  fout_fl.write(chr(0x00))

  fout_fl.write("1"));fout_fl.write("0"))
  for i in range(0,6,1):fout_fl.write(chr(0x00))


  for i in range(0,10,1):fout_fl.write(chr(0xD6))

  fout_fl.write(chr(0x00));fout_fl.write(chr(0x08));fout_fl.write(chr(0x4A));fout_fl.write(chr(0x0A))
  fout_fl.write(chr(0x00));fout_fl.write(chr(0x9F));fout_fl.write(chr(0x31));fout_fl.write(chr(0x38))
  fout_fl.write(chr(0x39));fout_fl.write(chr(0x35));fout_fl.write(chr(0x34));fout_fl.write(chr(0x3A))
  fout_fl.write(chr(0x00));fout_fl.write(chr(0x00));fout_fl.write(chr(0x00))

  for i in range(0,10,1):fout_fl.write(chr(0x00))

  finp_fl.close();fout_fl.close()


#open finp_st for input as #1:open fout_st for output as #2
#  for i=1 to 10:writebyte(2,0xD3):next
#  writebyte(2,0x4D)
  for i=1 to 6
    if i<=len(finp_st) then
      writebyte(2,asc(mid_st(finp_st,i,1)))
    else
      writebyte(2,0x00)
    end if
    next
#  writebyte(2,0x00)
#  writebyte(2,asc("1")):writebyte(2,asc("0"))
#  for i=1 to 6:writebyte(2,0x00):next

  writebyte(2,strt1 mod 256)
  writebyte(2,(int(strt1/256))mod 256)
  writebyte(2,lng2 mod 256)
  writebyte(2,(int(lng2/256))mod 256)
  writebyte(2,sum1 mod 256)
  writebyte(2,(int(sum1/256))mod 256)

  for i=1 to 10:writebyte(2,0xD6):next

  writebyte(2,0x00):writebyte(2,0x08):writebyte(2,0x4A):writebyte(2,0x0A)
  writebyte(2,0x00):writebyte(2,0x9F):writebyte(2,0x31):writebyte(2,0x38)
  writebyte(2,0x39):writebyte(2,0x35):writebyte(2,0x34):writebyte(2,0x3A)
  writebyte(2,0x00):writebyte(2,0x00):writebyte(2,0x00)

  for i=1 to lng1:writebyte(2,readbyte(1)):next

  for i=1 to 10:writebyte(2,0x00):next
  close #1:close #2


