#! D:\perl\bin\perl.exe

###############################################################################
###############################################################################
#
# To combine C & Perl source files into one without tabs for inclusion in
#  wordprocessing documents.
#
#			Version 2
#
#	by Andrew Hardwick, http://duramecho.com, 2001/12/14 - 2002/4/10
#
#	Released under GNU Public Licence.
#
###############################################################################
###############################################################################
#
# How To Use
#
# It takes one command-line parameter, the directory to use.
# It extracts data from files under that directory.
# It outputs to 'Combined.txt'.
# It reports progress to STDIO.
#
###############################################################################
###############################################################################

# Include libraries
use File::Find;		# For file finding command
use Text::Tabs;		# Expand tabs
# Disenable automatic global variables
use strict;

###############################################################################
# Main routine
###############################################################################

# Settings
my $Divider='-'x(80)."\n";
$tabstop=4;
# Get directory name (from command line)
unless($ARGV[0])
{	die("Error: No directory specified.\n");}
my $Directory=$ARGV[0];
# Find all source files (store names indexed by path)
my %Files;
find(sub
	{	if(/.*\.(txt|c|h|cpp|pl)$/i)	# grab source & txt files
		{	unless($_ eq 'Combined.txt') # skip the output file
			{	$Files{$File::Find::name}=$_;}}},
	$Directory);
# Create Output file
open(FILETOWRITE,'>'.'Combined.txt')||
			die("Cannot open file to write.");
print FILETOWRITE "C source code from: $Directory\n";
# Process all the files
foreach my $FromFilePath (sort SortFiles keys %Files)
{	print "Processing $Files{$FromFilePath}\n";
	print FILETOWRITE "\n$Files{$FromFilePath}:\n\n";
	# Get lines from file
	open(FILETOREAD,'<'.$FromFilePath)||
			die("Cannot open $FromFilePath to read.");
	while(<FILETOREAD>)
	{	# Output to combined file with spaces for tabs
		print FILETOWRITE expand($_);}
	print FILETOWRITE "\n$Divider",;
	close FILETOREAD;}
close FILETOWRITE;

###############################################################################
# Sorting function
###############################################################################
# To be called from 'find'
# Sorts so that each *.h file
#  ends up directly before its correspondingly named *.c or *.ccp file
###############################################################################

sub SortFiles
{	my($A,$B)=($a,$b);
	# Replace .c & .cpp endings to something between .h & .pl
	$A=~s/^(.*)\.cp*$/$1\.i/i;
	$B=~s/^(.*)\.cp*$/$1\.i/i;
	# Compare
	return $A cmp $B;}
