1 |
package Tape; |
2 |
|
3 |
# Dobrica Pavlinusic, <dpavlin@rot13.org> 08/03/07 11:11:56 CEST |
4 |
|
5 |
use strict; |
6 |
use warnings; |
7 |
|
8 |
use base qw/Class::Accessor/; |
9 |
__PACKAGE__->mk_accessors(qw(tape tape_pos tape_rate)); |
10 |
|
11 |
use File::Slurp; |
12 |
use Carp qw/confess/; |
13 |
|
14 |
=head1 NAME |
15 |
|
16 |
Tape - implement tape reader/recorder |
17 |
|
18 |
=cut |
19 |
|
20 |
=head2 read_tape |
21 |
|
22 |
$self->read_tape; |
23 |
|
24 |
=cut |
25 |
|
26 |
my $last_warn = ''; |
27 |
|
28 |
sub _warn { |
29 |
my $msg = shift; |
30 |
if ( $msg ne $last_warn ) { |
31 |
warn "$msg\n"; |
32 |
$last_warn = $msg; |
33 |
} |
34 |
} |
35 |
|
36 |
my @tape_bits; |
37 |
|
38 |
sub read_tape { |
39 |
my $self = shift; |
40 |
if ( ! $self->tape ) { |
41 |
_warn "please load tape!"; |
42 |
return 0; |
43 |
} |
44 |
my $pos = $self->tape_pos; |
45 |
my $tape = $self->tape; |
46 |
if ( $pos > length( $tape ) ) { |
47 |
_warn "end of tape [$pos]"; |
48 |
return -1; |
49 |
} |
50 |
|
51 |
if ( ! @tape_bits ) { |
52 |
my $byte = ord( substr($self->tape,$pos,1) ); |
53 |
warn sprintf("tape pos %d = %02x\n", $pos, $byte); |
54 |
|
55 |
$pos++; |
56 |
$self->tape_pos( $pos ); |
57 |
|
58 |
@tape_bits = split(//, unpack("B8",$byte) ); |
59 |
} |
60 |
my $bit = shift @tape_bits ? 0xff : 0x00; |
61 |
warn "\t$bit\n"; |
62 |
return $bit; |
63 |
} |
64 |
|
65 |
=head2 load_tape |
66 |
|
67 |
$self->load_tape( '/path/to/file' ); |
68 |
|
69 |
=cut |
70 |
|
71 |
sub load_tape { |
72 |
my $self = shift; |
73 |
my $path = shift || return; |
74 |
|
75 |
my $tape = read_file( $path ) || confess "can't load $path: $!"; |
76 |
|
77 |
$self->tape_pos( 0 ); |
78 |
$self->tape( $tape ); |
79 |
$self->tape_rate( 512 ); |
80 |
warn "loaded tape $path ", -s $path, " bytes rate ", $self->tape_rate, "\n"; |
81 |
return 1; |
82 |
} |
83 |
|
84 |
|
85 |
1; |