#perl to match curly brackets

$filename = shift;

open(INFILE, "< $filename") or die "Can not open $filename $!";

$prev_depth = 0;
$depth = 0;
while ($inline = <INFILE>) {
  ($outline) = ($inline =~ m/\s*(.*)/); #remove leading spaces
  $flag_close_open = 0;
  while ($inline and ($inline =~ m/[\{\}]/)) {
    $found = $&;
    $inline = $';
    if ($found eq '{') {
      $depth = $depth + 1;
      if ($flag_close_open eq 1) {
        $flag_close_open = 2; # found "} else {"
      } else {
        $flag_close_open = 9; # too complicated
      }
    }
    if ($found eq '}') {
      $depth = $depth - 1;
      if ($flag_close_open) {
        $flag_close_open = 9; # too complicated
      } else {
        $flag_close_open = 1; # possible "} else {"
      }
    }
  }
  # Create formatting pre-line
  $flag_line = '';
  if ($prev_depth < $depth) {
    $indent = $prev_depth;
  } else {
    $indent = $depth;
  }
  if ($flag_close_open eq 2) {
    $indent = $indent - 1;
  }
  if ($indent) {
    foreach (1..$indent) {
      $flag_line = $flag_line . '| ';
    }
  }
  if ($flag_close_open eq 2) {
    $flag_line = $flag_line . '>-';
  }
  $flag_line = $flag_line.' /'  if $prev_depth < $depth;
  $flag_line = $flag_line.' \\' if $prev_depth > $depth;
  print $flag_line.$outline."\n";
  $prev_depth = $depth;
}
close (INFILE);