#!/usr/bin/perl
#
#	cpm-v1:	a prototype "C with pattern matching" to C translator..
#
#	This first version of our tool simply reads every line of input,
#	identify % lines, complain unless they're %when lines, and copy all
#	other lines to stdout unchanged.  But that's pretty trivial in Perl!
#
#	(C) June 2018, Duncan C. White
#

use strict;
use warnings;
use 5.010;
use Data::Dumper;
use Function::Parameters;


my $infh;		# fd of current C+PM file we're translating
my $lineno = 0;		# current line no inside $infh
my $currline;		# current line (set by nextline(), used in fatal())


#
# my $line = nextline();
#	Read the next line from $infh, incrementing $lineno afterwards,
#	and return it.
#
fun nextline()
{
	my $line = <$infh>;
	$currline = $line;
	$lineno++;
	return $line;
}


#
# handle_line( $line, $ofh );
#	handle $line [and if necessary, any subsequent lines of input],
#	print out whatever text is generated (or copied) to $ofh
#
fun handle_line( $line, $ofh )
{
	#print "debug: handling line <<$line>> at line no $lineno\n";
	unless( $line =~ /^\s*%/ )
	{
		print $ofh "$line\n";
		return;
	}
	$line =~ s/^(\s*)//;
	my $indent = $1;
	print "debug: line is <<$line>> at line $lineno\n";

	die "$indent$line\n$indent^ Error at line $lineno: %when expected\n"
		unless $line =~ /^%when/;
	print $ofh "$indent// $line\n";
}


die "Usage: cpm-v1 inputfile\n" unless @ARGV == 1;
my $inputfilename = shift;

my $cfilename = $inputfilename;
$cfilename =~ s/pm$//;

open( $infh, '<', $inputfilename ) || die "cpm: can't open $inputfilename\n";

unlink( $cfilename );
open( my $cfh, '>', $cfilename ) || die "cpm: can't create $cfilename\n";

while( defined( $_ = nextline() ) )
{
	chomp;
	handle_line( $_, $cfh );
}
close( $infh );
close( $cfh );
