+ return $subs;
+}
+
+# Replace top-level values in $main with top-level templates from $tem.
+function merge_templates($main, $tem) {
+ $out = array('name' => $main['name'], 'pieces' => array());
+
+ $subs = top_sub_templates($tem);
+
+ foreach($main['pieces'] as $piece) {
+ $sub = $subs[$piece['name']];
+ if(is_array($piece) and !$piece['pieces'] and $sub and $sub['args'][0] != 'hide') {
+ $piece = $subs[$piece['name']];
+ }
+ $out['pieces'][] = $piece;
+ }
+ return $out;
+}
+
+
+
+# tem_auto functions
+# ------------------
+#
+# If a { tag has an argument, the corresponding tem_auto function is called.
+# This allows it to mangle the data to automate some common cases.
+
+# 'sep' (separator) sections will be shown for all but the last parent row.
+# Sample usage:
+# <!--~rows {~-->
+# <!--~row {~-->
+# row content...
+# <!--~separator sep {~--><hr><!--~}~-->
+# <!--~}~-->
+# <!--~}~-->
+#
+function tem_auto_sep(&$value, $key, $context) {
+ $rows =& $context['parent']['parent'];
+ if($rows['cur'] != count($rows['rows'])-1) # last row?
+ return $value = true; # show once
+}
+
+# auto-show once, only when this is the first row of the parent
+function tem_auto_last(&$value, $key, $context) {
+ $rows =& $context['parent']['parent'];
+ if($rows['cur'] == count($rows['rows'])-1) # last row?
+ return $value = true; # show once
+}
+
+# auto-show once, only when this is the last row of the parent
+function tem_auto_first(&$value, $key, $context) {
+ $rows =& $context['parent']['parent'];
+ if($rows['cur'] == 0) # first row?
+ return $value = true; # show once
+}
+
+# 'show' sections will be shown unless the corresponding data value
+# is false (only false, not 0 or '' or array()).
+
+function tem_auto_show(&$value) {
+ if($value !== false) $value = array(array());
+ return $value;
+}
+
+# 'evenodd' sections are given an 'evenodd' attribute whose value
+# alternates between 'even' and 'odd'.
+
+function tem_auto_evenodd(&$values) {
+ $even = true;
+ if($values) foreach($values as &$value) {
+ $value['evenodd'] = $even ? 'even' : 'odd';
+ $even = !$even;
+ }
+ return $values;
+}