#!/usr/bin/perl


@DEAD=();

undef $/; # read complete files
  file:
while (<>)
{
  print STDERR $ARGV,"\n";
# read functions
  $fpos=0;
  while ( ($name)= 
      (m/(\w+)\s*\([^)]+?\)\s*(\x7b)/m) ) 
# can't use open-curly-bracket because of auto-indent
      {
	$start=$-[2];
	$body=substr($_,$start);

	$fpos+=$start;

	$index=1;
	$level=1;
	while($level)
	{
	  $l_o=index($body,'{',$index);
	  $l_c=index($body,'}',$index);
	  print STDERR "found: $l_o $l_c \n" ; #in <$body>\n";
	  if ($l_c < 0)
	  {
	    push @DEAD,"$ARGV:$name:$fpos";
print $_;
	    next file;
	  }

	  if ($l_c < $l_o || $l_o<0)
	  {
	    $level--;
	    $index=$l_c+1;
	  }
	  else
	  {
	    $level++;
	    $index=$l_o+1;
	  }
	}

	$text= substr($body,0,$index);
	print substr($_,0,$start),&Change($ARGV,$name,$text);
	substr($_,0,$start+$index)="";
	$fpos+=$index;
      }

  print $_;
}


if (@DEAD)
{
  print STDERR "\n\nDEAD FILES: ******************\n";
  print STDERR join("\n",@DEAD,"");
}

exit;


sub Change
{
  my($file,$func,$txt)=@_;
  my($sol,$index,$pk,$fmt,$parm,$is_kern,$e);
  my(%insert);


  $sol=1; # start of line set for function start

    %insert=();	# indizes to insert KERN_-values
    $index=-1;
  while (1)
  {
    print STDERR "$file:$func:$index\n";
    $index=index($txt,"printk",$index+1);
    last if $index == -1;

    if (substr($txt,$index-1,256) !~ m#\b(printk\s*\x28\s*)(\S[^,\x29]+\S)(\s*,[\x00-\xff]+?\S)?\s*\x29\s*;#)
    {
# not a real printk
      next;
    }

    ($pk,$fmt,$parm)=($1,$2,$3);
    $is_kern= $fmt =~ m#^KERN_#;

    if ($sol)
    {
      if ($is_kern)
      {
# ok
      }
      else
      {
# KERN_DEBUG missing
	$insert{$index + length($pk)}=" KERN_DEBUG ";
      }
    }
    else
    {
      if ($is_kern)
      {
	warn "possibly too much KERN_* at $file:$func:$index\n";
      }
      else
      {
# ok
      }
    }

# find \n in strings, and append a KERN_DEBUG if there's no " after \n
    $insert{$index + length($pk) + length($1)} = '" KERN_DEBUG "'
      while ($fmt =~ m#^([\x00-\xff]*\\n)(?!")#g);

    $sol = $fmt =~ m#\\n"$#;
  }

# from end to start, to avoid invalidating the indizes
  for (sort { $b <=> $a } keys %insert)
  {
    substr($txt,$_,0)=$insert{$_}
  }

  $txt;
}


__END__

while ( $txt =~ s#\b(printk\s*\x28\s*)(")#$1 KERN_DEBUG $2 #gx)
{
  print STDERR "in $file:$func:$txt\n";
}

## vim: sw=2 

