diff --git a/inc/parserutils.php b/inc/parserutils.php
index 1dbc1430fde95c100532edc94111097f82e4700c..349e8372572f8e7da10793a7be5591b2d359c826 100644
--- a/inc/parserutils.php
+++ b/inc/parserutils.php
@@ -321,7 +321,7 @@ function p_get_first_heading($id){
     $instructions = p_cached_instructions($file,true);
     foreach ( $instructions as $instruction ) {
       if ($instruction[0] == 'header') {
-        return $instruction[1][0];
+        return trim($instruction[1][0]);
       }
     }
   }
diff --git a/inc/template.php b/inc/template.php
index b635f6093e84bb6d173cb9e366a655cb9a07a60b..1ee995b5c39a661a77013c7f948242f02bebca94 100644
--- a/inc/template.php
+++ b/inc/template.php
@@ -676,5 +676,27 @@ function tpl_mediauploadform(){
   ptln('</form>',2);
 }
 
+/**
+ * Prints the name of the given page (current one if none given).
+ *
+ * If useheading is enabled this will use the first headline else
+ * the given ID is printed.
+ *
+ * @author Andreas Gohr <andi@splitbrain.org>
+ */
+function tpl_pagetitle($id=null){
+  global $conf;
+  if(is_null($id)){
+    global $ID;
+    $id = $ID;
+  }
+
+  $name = $id;
+  if ($conf['useheading']) {
+    $title = p_get_first_heading($id);
+    if ($title) $name = $title;
+  }
+  print hsc($name);
+}
 
 //Setup VIM: ex: et ts=2 enc=utf-8 :
diff --git a/lib/tpl/default/main.php b/lib/tpl/default/main.php
index b3b0d5de10e44bac81a72b2a21b8dbe3986f179c..7d3c1c46f774046e17515a40597feca2f984ffbc 100644
--- a/lib/tpl/default/main.php
+++ b/lib/tpl/default/main.php
@@ -17,7 +17,7 @@
 <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="<?php echo $conf['lang']?>"
  lang="<?php echo $conf['lang']?>" dir="<?php echo $lang['direction']?>">
 <head>
-  <title><?php echo $ID?> [<?php echo hsc($conf['title'])?>]</title>
+  <title><?php tpl_pagetitle()?> [<?php echo hsc($conf['title'])?>]</title>
   <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
 
   <?php tpl_metaheaders()?>