package Perlfect::Template;

use Exporter;
@ISA = qw(Exporter);
@EXPORT_OK = qw(cast);

#use strict;
use vars qw($errstr);
$errstr = '';


sub new
  {
    my ($class, $file) = @_;
    my $self = {
		file => $file,
		template => '',
	       };
    #unless(open(FILE, $file))
    #  {
    #	$errstr = "Cannot open $file: $!";
#	return undef;
 #     }
    open(FILE, $file) or die "Cannot open file $file: $!";
    while(<FILE>)
      {
	$$self{template} .= $_;
      }
    close(FILE);
    bless $self, $class;
    return $self;
  }


sub cast
  {
    my ($self, $hr) = @_;
    my $html = $$self{template};
    while($html=~s/<!--\s*cgi:\s*(\S+?)(?:\((.*)\))?\s*-->/_exec_directive($hr, $1, $2)/ie)
      {}
    return $html;
  }



sub _exec_directive
  {
    my ($hr, $directive, $args) = @_;
    if(ref($$hr{$directive}))
      {
	my $code = "\@a = ($args);";
	my @args = eval $code;
	return &{$$hr{$directive}}(@args);
      }
    else
      {
	return $$hr{$directive};
      }
  }

1;
