def to_listing
buffer=contents
end_of_line_number_table=(buffer[2]<<8)+buffer[3]
start_of_line_number_table=(buffer[4]<<8)+buffer[5]
number_of_lines=(1+end_of_line_number_table-start_of_line_number_table)/4
relocation_offset=start_of_line_number_table-7
line_number_table=buffer[8,(number_of_lines*4)]
detokenised_lines={}
number_of_lines.times do |i|
line_number_data=line_number_table[i*4,4]
line_number=(line_number_data[0]<<8)+line_number_data[1]
location_of_line_in_memory=(line_number_data[2]<<8)+line_number_data[3]
location_of_line_in_buffer=location_of_line_in_memory-relocation_offset
line_length=buffer[location_of_line_in_buffer]
detokenised_line="#{line_number} "
p=location_of_line_in_buffer+1
last_byte_was_token=false
while (p<location_of_line_in_buffer+line_length) && (!buffer[p].nil?) && (buffer[p]!=0) do
token=buffer[p]
token_text=TI_BASIC_TOKENS[token]
if (token_text.nil?) then
detokenised_line<<" " if ((detokenised_line=~/\w$/) && (last_byte_was_token))
if token==0xC7 then
detokenised_line<<"\"#{buffer[p+2,buffer[p+1]]}\""
p+=buffer[p+1]+1
elsif token==0xC8 then
detokenised_line<<"#{buffer[p+2,buffer[p+1]]}"
p+=buffer[p+1]+1
elsif token==0xC9 then
detokenised_line<<"#{(buffer[p+1]<<8)+buffer[p+2]}"
p+=2
else
detokenised_line<<token.chr
end
last_byte_was_token=false
else
last_byte_was_token=true
detokenised_line<<" " if detokenised_line=~/(\w|:|")$/ && token_text=~/^(\w|:|")/
detokenised_line<<token_text
end
p+=1
end
detokenised_lines[line_number]=detokenised_line
end
result=""
detokenised_lines.keys.sort.each do |line_number|
result << "#{detokenised_lines[line_number]}\n"
end
result
end
end