#!/usr/bin/perl

# Beautify RTF
# Written by Harald Fernengel (harry@bnro.de)
# 
# Command Line Utility that takes an RTF file and outputs a .BRTF file (Beautfied RTF)
# This BRTF file could not be opened in a RTF Reader!!
# All Blocks are indented and Word 2000 Pictures are removed so that the file could be
# read in a simple Text-Editor
#
# Feel free to use it. No copyright.
#

$RTFFile = $ARGV[0];

if (!(open (FILE, "<$RTFFile"))) {

	die ("File not found!");
}

if (!(open (DestFILE, ">$RTFFile" . ".brtf"))) {

	die ("Could not create destination!");
}

$indent = "";

@ResultFile = <FILE>;
$Result = join("", @ResultFile);
$Result =~ s/\r//gm;
$Result =~ s/\n//gm;
$Result =~ s/{\\\*\\blipuid.*?}.*?}/PICTUREDATA}/gm;

while ($Result =~ m/(.*?){/g) {
	
	$MatchRes = $+;
	
	while ($MatchRes =~ m/(.*?)}/g) {
				
		print DestFILE $+;
		print DestFILE "}\n";
		chop $indent;
		chop $indent;
		print DestFILE $indent;
		$MatchRes =~ s/.*?}//;

	}
	
	print DestFILE $MatchRes;
	
	$indent = $indent . '  ';
	
	print DestFILE "\n" . $indent . "{";
	
	$Result =~ s/.*?{//;
	
}

while ($Result =~ m/(.*?)}/g) {
			
	print DestFILE $indent . $+	;
	print DestFILE "}\n";
	chop $indent;
	chop $indent;
	$Result =~ s/.*?}//;

}

print DestFILE $Result;

print "Ready";
