#!/bin/sh
perl - `dirname $0` "$@" <<\ENDOFPERL
#!perl

use strict;


# -------------------------------
# nios-run-gprof
# usage: nios-run-gprof filename.c
#
# To save results into a file, do:
#    nios-run-gprof filename.c > filename.profile


my $line;
my $source_file_name = $ARGV[1];
my $text_output_file_name = $ARGV[1];
$text_output_file_name =~ s/^(.*?)\.c/\1\.txt/ ;
my $output_file_name = "gmon.out";
my $build_command = "nios-build -cc -pg " . $source_file_name;
my $run_command = "nios-run " . $source_file_name;
$run_command =~ s/^(.*?)\.c/\1\.srec/ ;
my $gprof_command = "nios-elf-gprof -C -q " . $source_file_name;
$gprof_command =~ s/^(.*?)\.c/\1\.out/ ;
$gprof_command = $gprof_command . " --traditional gmon.out | tee " ;

open OUTFILE, ">$output_file_name"; 
binmode OUTFILE;


print "Nios Gprof Batch Utility\n";
print "Input Source file name: ", $source_file_name, "\n";

# Build the source file with the -pg option:
print "Compile and build ", $source_file_name, "\n";
system($build_command);

#run the program, creating the text output file
print "Run and create ", $text_output_file_name, "\n";
system($run_command . "| tee $text_output_file_name");

# Convert the text file into the gmon.out binary used by gprof:

open INFILE, $text_output_file_name;

my $inline;

while ($inline = <INFILE>)
{
    if ($inline =~/^\#\#\#(.*)$/)
    {
        my $hex_string = $1;

	my $hex_pair;

        $hex_string =~s/ //g;      # remove the spaces
        $hex_string =~s/\*//g;     # remove the asterix
	while ($hex_string ne "")
	{
            $hex_pair = substr($hex_string, 0, 2);

	    my $byte = hex($hex_pair);  # hex returns a number, now in byte
	    printf OUTFILE "%c", $byte;

	    $hex_string = substr($hex_string,2);
	}
    }
}

print "Created output file name: ", $output_file_name, "\n";

close INFILE;
close OUTFILE;

# Run the gprof utility with default settings and display results:
print "gprof string: " , $gprof_command , "\n"; 
system($gprof_command);



