#!/usr/bin/perl

#
# Looking at converting a string of 4 letters into a binary representation,
# which should make it go from 8 bits per character to 2 bits per character.
#
#

my $string = 'gatacagatacagatacagatacagatacagg';
print "The string is '$string'.\n";
print "Its length is " . length($string) . "\n";
print "(Make sure this is a multiple of 4.)\n";

# binary encoding definition
my %encoding = (
  a => '00',
  c => '01',
  g => '10',
  t => '11',
);

# Convert string to 0's and 1's.
my $binary_string = $string;
for my $char qw(a c g t){
  my $code = $encoding{$char};
  $binary_string =~ s/$char/$code/g;
}

print "String as 0's and 1's is '$binary_string'.\n";
print "Length of that is " . length($binary_string) . ".\n";

# Pack those ASCII 0's and 1's into binary; 1 bit for each.
my $binary = pack('B*',$binary_string);
print "Packed into binary that is '" . $binary . "'.\n";
print "Length of that is " . length($binary) . ".\n";

print "Writing file 'dna_string'.\n";
open(FILE1, '>dna_string') or die "Couldn't open file";
print FILE1 $string;
close(FILE1);

print "Writing file 'dna_binary'.\n";
open(FILE2, '>dna_binary') or die "Couldn't open file";
print FILE2 $binary;
close(FILE2);

# Shell processing
`cp dna_binary dna_binary.orig`;
`bzip2 dna_binary`;

`cp dna_string dna_string.orig`;
`bzip2 dna_string`;
