#!/usr/bin/perl
#
# Program to edit bib files to have 2 curly braces surrounding the text in the 'Title' field
# matched lines are printed and numbered, with changes printed below

$numArgs = $#ARGV + 1;
if ($numArgs == 2)	# at least make sure user gives two arguments
{
	print "thanks, you gave me the following filenames:\n";
	print "file in: $ARGV[0]\n";
	print "file out: $ARGV[1]\n";
}
else
{
	print "please provide two filenames.\n syntax is: \'format-bib.pl filename-in.bib filename-out.bib\' \n";
	exit 0;			# because arguments given <> 2
}

$file = "$ARGV[0]";
$file2 = "$ARGV[1]";
open(INFO, "<$file");		# Open the file for input
open(OUT, ">$file2");		# Open the file for output

$a = 1;						# Counter for matched lines

while ($lines = <INFO>)
{
	if ($lines =~ /(\bTitle = {[^{])(.*)(},)/) # regexp to match Title lines with only one curly brace
	{
		print "$a $lines";	# print to show matches with line number for reference
		$a++;	#count all lines whether matched or not
		$lines =~ s/(\bTitle = {)(.*)(},)/\1\{\2\}\3/; #substitute using back refs
		print "$lines";		# print to show changes
		print OUT "$lines";	# save to output
	}
	else
	{
# could uncomment this next line to make 'verbose'
#		print "$lines";
		$a++;	#count all lines whether matched or not
		print OUT "$lines";	# save to output
	}
}

close(INFO);
close(OUT);

