#!/usr/bin/perl -i.bak

use English;


undef $INPUT_RECORD_SEPARATOR;
$file = <>;

$file =~ s/\\fig(?:\[(.+?)\])?{(.+?)}(?:{(.+?)})?(?:{(.+?)})?/easyFigure($2,$1, $3, $4)/ge;
$file =~ s/\\cfig(?:\[(.+?)\])?{(.+?)}(?:{(.+?)})?(?:{(.+?)})?/easyFigure($2,$1 . ',center', $3, $4)/ge;



print $file;




sub easyFigure {
    my ($file, $opts, $labelText, $captionText) = @_;

    # DEFAULTS
    my $centering = '';
    my @includegraphicsOptions = ();
    my $includegraphicsOptions = '';

    @opts = split(/,/, $opts);
    foreach $opt (@opts) { 
#	print STDERR $opt;
#	print STDERR "\n\n";

	if ($opt eq 'center') { 
	    $center = '\\centering';
	}
	else {
	    push(@includegraphicsOptions, $opt);
#print STDERR ('[' . join(',', @includegraphicsOptions) . ']\n\n');

	}
	    
    }

    if ($captionText) {
	$caption = "\\caption{$captionText}";
    }

    if ($labelText) {
	$label = "\\label{$labelText}";
    }

    if ($#includegraphicsOptions >= 0) {
	$includegraphicsOptions = '[' . join(',', @includegraphicsOptions) . ']';
	#print STDERR "$includegraphicsOptions\n\n";
    }


    my $ret = <<EOF;
\\begin{figure}$label
$center \\includegraphics${includegraphicsOptions}{$file} $caption
\\end{figure}
EOF

    chop($ret);
    #print STDERR $ret;
    return $ret;

}
