#!/usr/bin/perl -w
use strict;
use Getopt::Std;

my %opts;
getopts('o:d:p', \%opts);
$opts{d} = 10 unless exists $opts{d};
# Check the value of $opts{d}?
my $out = *STDOUT;
open $out, '>', $opts{o} or die "Error: couldn't write to `$opts{o}': $!\n"
if exists $opts{o};
select $out;

print <<EOT;
#include <curses.h>
#include <time.h>
int main(void) {
initscr(); noecho(); cbreak();
clock_t tick;
EOT

my($y, @img) = (0);
while (<>) {
s/\s+$//;
1 while s/\t+/' ' x (length($&)*8 - length($`)%8)/e;
my $x = 0;
foreach (split //) {
 $_ = "\\$_" if $_ eq "'" || $_ eq "\\";
 if (!exists $img[$y][$x] || $img[$y][$x] ne $_) {
  print " mvaddch($y, $x, '$_');\n" unless !exists $img[$y][$x] && /^\s$/;
  $img[$y][$x] = $_;
 }
 $x++;
}
if (exists $img[$y][$x]) {
 print " move($y, $x); clrtoeol();\n"; splice @{$img[$y]}, $x;
}
$y++;
if (eof) {
 if ($y < @img) {print " move($y, 0); clrtobot();\n"; splice @img, $y; }
 print " move(LINES-1, COLS-1); refresh();\n";
 print " for (tick=clock(); clock()-tick < CLOCKS_PER_SEC * $opts{d}/100;);\n";
 $y = 0;
}
}
print " getch();\n" if exists $opts{p};
print " endwin();\n return 0;\n}\n";