def indent_c_file(filename)
  f = File.open(filename, "r")
  lines = f.readlines
  f.close

  indentation = 0
  indent_string = "  "
  indent_tokens = {
    /\/\*/    => [ 0, +1, 0],
    /\{/      => [ 0, +1, 0],
    /\*\//    => [-1,  0, 0],
    /}/       => [-1,  0, 0],
    /^[^?]*:$/=> [-1, +1, 0],
    /^throw/  => [+1, -1, 0],
    /\(/      => [ 0, +8, 0],
    /\)/      => [ 0, -8, 0],
    /[=+-]$/  => [ 0,  1,-1],
    /\?.*:$/  => [ 0,  1,-1],
  }
  indentation = [0,0,0]

  lines = lines.collect{|line|
    indentation.shift
    indentation[2] = indentation[1]

    # remove spaces at the beginning, at the end, replace tabs with spaces,
    # replace consecutive spaces with just one space
    line = line.gsub(/\s+/, " ").strip
    
    if (line[0,2] != "//")
      indent_tokens.each{|token,value|
	occurences = line.scan(token).size
	if (occurences > 0)
	  value.each_with_index{|v,i|
	    i.upto(2){|j|
	      indentation[j] += v * occurences
	    }
	  }
	end
      }
    end
    if (line != "")
      line = indent_string * indentation[0] + line
    end
    line
  }
  f = File.open(filename, "w+")
  f.puts(lines)
  f.close
end

if $0 == __FILE__
  ARGV.each{|filename| indent_c_file(filename)}
end
