#!/bin/bash
#
# Optimize the XML files in OSX to improve responsiveness and speed
# Copyright 2008 Joel Bryan T. Juliano <joelbryan.juliano@gmail.com>
# GNU Public License
#
# By XML Optimization, the metadata will be preformatted, by removing the
# whitespace between the tags, and compacting the whole XML content into a
# single line, without making any changes in the data inside the tags. The
# process will make the file much smaller, giving increased memory space,
# and increased ease for the xml parser to read it.
#

start_dir="/"

COUNTER=0;
PASS=2;

while [  $COUNTER -ne $PASS ];
	do
		find "$start_dir" -type f -exec file '{}' \; | \
		grep "XML 1.0 document text" | sed 's/: XML 1.0 document text//g' | \
		while read filename;
			do
				before_filesize=$( stat -f %z "$filename" );
				if [ $COUNTER -ge 1 ]; then
					echo "Re-Optimizing file: $filename";
					echo "REDUCED MEMORY HEAP FOOTPRINT THROUGH OPTIMIZATION: $( expr $before_filesize_total - $after_filesize_total ) kb"
				else
					echo "Optimizing file: $filename";
				fi
             			cat "$filename" | sed -e '/^[ \t]*$/d;s,^[ \t]*,,g;s,>[ \t]*<,><,g;s,[ \t]*$,,g' > "$filename".temp
				cat "$filename".temp | tr '\012\011' ' ' > "$filename";
				rm -rf "$filename".temp*;
				after_filesize=$( stat -f %z "$filename" );
				let before_filesize_total+=before_filesize
				let after_filesize_total+=after_filesize
			done
		let COUNTER=COUNTER+1
	done

