#!/usr/bin/python
# -*- coding: latin-1 -*-
import os,sys
finp_st=sys.argv[1];fout_st=finp_st+".tap"
if finp_st.lower()=="--help".lower():
  print "bin2tap - 20110929154305 - Paulo Silva (GPL licence)"
  print "converts a binary file into a zx-spectrum .tap file"
  print "usage: python bin2tap.py file.bin"
  print "the result will be a neighbour file named yourfile.bin.tap"
  print "file size limit: 48kb";print""
else:
  wrk4=[0]*49152;wrk5=[0]*49152;sphdr=[0]*32
  for i in range(0,32,1):sphdr[i]=0
  sphdr[0]=19;sphdr[3]=3;sphdr[19]=128;sphdr[23]=255
  wrk4[0]=19;wrk4[3]=3;wrk4[19]=128;wrk4[23]=255
  tapln=0
  specfinp_st=finp_st+"          "[:10]
  flsize=os.path.getsize(finp_st)
  if flsize<=65533 and flsize >=1:
    finp_fl=open(finp_st,"r");adrp=0
    while True:
      byte_st=finp_fl.read(1)
      if len(byte_st)==0:break
      wrk5[adrp]=ord(byte_st);adrp+=1
    finp_fl.close()
  flsize2=flsize+2
  flsizeh=(int(flsize/256))%256;flsizel=flsize%256
  flsize2h=(int(flsize2/256))%256;flsize2l=flsize2%256
  for i in range(0,10,1):
    u=ord(specfinp_st[i])
    wrk4[tapln+i+4]=u
  wrk4[tapln+14]=flsizel;wrk4[tapln+15]=flsizeh
  wrk4[tapln+21]=flsize2l;wrk4[tapln+22]=flsize2h
  checksum=0

  # for i in range(4,20,1): instead?
  # for i in range(2,20,1): old?

  for i in range(2,20,1):

    checksum=checksum^wrk4[tapln+i]
  wrk4[tapln+20]=checksum
  checksum=255
  for i in range(0,flsize,1):
    wrk4[tapln+i+24]=wrk5[i]
    checksum=checksum^wrk5[i]
  wrk4[tapln+flsize+24]=checksum
  tapln=tapln+(flsize+25)
  wrk4[0]=19;wrk4[3]=3;wrk4[19]=128;wrk4[23]=255
  fout_fl=open(fout_st,"w")
  for i in range(0,tapln,1):
    fout_fl.write(chr(wrk4[i]))
  fout_fl.close()

