#!/usr/local/bin/perl5
# bdc_standalone: Compiles specified template file into cpp and h files - no server
# Copyright (C) 1998-2001  Carnegie Mellon University
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2
# of the License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.

use strict;
use LWP::UserAgent;
use HTTP::Request::Common;

#determine the name by which we were invoked
my $ARGV0 = $0;
$ARGV0 =~ s/.*\///;

# check usage
unless  (@ARGV)   {
     die "usage:  $ARGV0 <template file> ...\n";
}

##################################
# Assign default values
###################################

my $FORM_SITE = 'http://ballista.ece.cmu.edu/compile';  # site of Ballista compiler form
my $CGI_SITE = "$FORM_SITE/fup.cgi";                    # Ballista compiler
my $ua = LWP::UserAgent->new;

################################
# Compile each specified dataType
################################
foreach my $tpl_file (@ARGV) {

    # extract directory and filename from arguments
    my ($tpl_dir, $template) = $tpl_file =~ m#(.*/)?([\w]+).tpl$#;

    # do some error checking to insure values were extracted properly
    unless ($template){
	die "didn't extract template filename from command line: $!\n";
    }

    my $result_dir;  #web site of successfully generated .cpp and .h file

    print "$tpl_dir";
    print " do_parse $tpl_file\n";
    system ("do_parse $tpl_file");
} # end of foreach
exit(0);

################################# 
# Get the file specified URL at $html
#   and print the content to $file.
#################################
sub get_and_save{
    my ($html,$file) = @_;
    my $ua = LWP::UserAgent->new;    
    my $response = $ua->request(GET $html);
    
    unless($response->is_success) {
	print "Error: Can't get $html\n";
	return 0;
    }

    if ($file eq "STDOUT") {

	print $response->content;

    } else {

	unless (open (FILE, ">$file")){
	print "Error: Can't open $file:  $!\n";
	return 0;
        }
    
	print FILE $response->content;
	close FILE;
    }
    return 1;
}
