#!/usr/bin/perl

#
# Author: Tsantilas Christos
# email:  christos@chtsanti.net
#
#

use File::Copy;



$in=$ARGV[0];
$out="$in.converted";
print $in,$out;
copy($in, "$in.original");

if(!open(IN,"<$in")){
    print "Can't open input file: $in\n";
    exit -1;
}


if(!open(OUT,">$out")){
    print "Can't open output file: $out\n";
    exit -1;
}

my $i = 0;
my $line,$mod_statement;
my $t;


while(<IN>){
    $line=$_;
    if ( $line =~ /( |\t)debug\((\d*),( )*(\d*)\)/ ) {
	$i=0;
	while($line !~ /\);/){

	    if (! ($t=<IN>) ){
		exit(-1);
	    }

	    $i=$i+1;
	    if($i>10){
		# More than 10 lines to a single debug statement?
		# something goes wrong in parsing
		exit(-1);
	    }
	    $line=$line.$t;
	}
	print "Found a debug line : $line  \n";
	$mod_statement=process_debug_command($line);
	if($mod_statement){
	    print "Converted to line: $mod_statement \n";
	    print OUT $mod_statement;
	}
	else{
            print "Not modified\n";
	    print OUT $line;
        }
	print "---------------------\n\n";
    }
    else{
	print OUT $line;
    }
}

close(IN);
close(OUT);

# Here we believe that we correctly do any convertion so copy new file
# to the original 

copy("$in.converted", $in);
exit(0);


sub process_debug_command{
    my($line)=@_;
    my $dsec,$dlevel,$format,$args,$arg,$val;
    my @array_args;

    # Handle multilined strings
    $line =~ s/\"( |\n|\t)*\"//g;
    
    #remove newlines
    $line =~ s/\n//g;

#    print "This is the line:$line\n";

    #read debug section and level and debug arguments..... 
    $line =~ /debug\((\d*),( )*(\d*)\)( )*\((.*)\)\;/sm;
    $dsec=$1; 
    $dlevel=$3;
    $args=$5;
    



    if($args =~ /\"(.*)\",(.*)/sm){
	$format=$1;
	$args=$2;
    }
    elsif($args =~ /\"(.*)\"$/sm){
	$format=$1;
	$args="";
    }
    else{
	return '';
    }
#    print "Format str:",$format,"\n","Args:",$args,"\n";



    @array_args = split(/,/ , $args );

#    print "debugs($dsec, $dlevel, $format";
#    foreach $arg (@array_args){
#	$val=~ s/^(( |\n|\t)*)//;
#	chomp($val);

#	print ", $arg";
#    }
#    print ");\n";


    $arg=shift(@array_args);
    $arg=~ s/^(( |\n|\t)*)//;
    chomp($arg);
    # we understand the following %x formats
    while( $format =~ s/%(s|lu|ld|d|u|p|x)/" << $arg << "/ ){
	if(!$arg){
	    return '';
	}
	$arg=shift(@array_args);
	$arg=~ s/^(( |\n|\t)*)//;
	chomp($arg);
    }
    if($arg){
         print "ERROR remain arg:$arg\n";
         return '';
    }
    $format="debugs($dsec, $dlevel, \"$format\" );\n";
#    print "debugs($dsec, $dlevel, \"$format\" );\n";

    return $format;
}

