#!/usr/bin/perl


use strict;
use warnings;

use List::Util qw(max);
use Getopt::Long;
use Carp qw{confess};
use File::Basename;
use File::Find;
use File::stat;
use Cwd;

# Color
use Term::ANSIColor qw(:constants);
$Term::ANSIColor::AUTORESET = 1;

my $commentre = '(/\*.*\*/)\s';

my $basedir = getcwd();
my $outdir = $basedir."/processed";
mkdir $outdir || confess("Could not create $outdir: $!");

my @dirs = ("src");
find({wanted => \&wanted,preprocess => \&filter}, @dirs);

sub filter {
    my @files = @_;
    return grep {!/(^\..*)/} @files;
}

sub wanted {
  my $file = $_;
  my $name = $File::Find::name;
  if (-f $file && ! -l $file && $file =~ /\.scala$/) {
	print BOLD BLUE "Processing file $file...\n";
	process($file);
  }
  else {
	if (-d $file) {
	  print BOLD YELLOW "Current dir: $name/\n";
	}
  }
}

sub process {
  my $file = shift;
  my ($name,$suffix) = split(/\./,$file);
  open(my $fd, "<", $file) or confess("Could not open $file: $!");

  # File without comments
  my $outfilenc = $outdir."/$name.nc.$suffix";
  open(my $commentless,">",$outfilenc) or confess("Could not open $outfilenc: $!");

  # File without numbers
  my $outfilenn = $outdir."/$name.nn.$suffix";
  open(my $numberless,">",$outfilenn) or confess("Could not open $outfilenn: $!");

  # Write content without any comments and without any numbers
  my @numbers = ();
  while(<$fd>) {
	if (/\/\*(\d+)\s/gxms) {
	  push @numbers, $1;
	}
	print {$commentless} remove_comment($_);
	print {$numberless} remove_number($_);
  }
  close($commentless);
  close($numberless);

  # Write content without numbers
  my $max = max @numbers;
  if ($max) {
	for my $i (0..$max) {
	  my $outfile = $outdir."/$name.$i.$suffix";
	  open(my $out,">",$outfile) or confess("Could not open $outfile: $!");
	  seek($fd,0,0);
	  while(<$fd>) {
		print {$out} upto_number($_,$i);
	  }
	  close($out);
	}
  }
}

sub remove_comment {
  my $line = shift;
  $line =~ s{$commentre}{}gxms;
  return $line;
}

sub remove_number {
  my $line = shift;
  $line =~ s{\d*}{}gxms;
  return $line
}

sub upto_number {
  my $line = shift;
  my $upto = shift;
  if ($line =~ /\/\*(\d+)\s/gxms) {
	my $number = $1;
	$line =~ s/$number//gxms;
	if ($number > $upto) {
	  my $comment = $line;
	  $comment =~ s{.*$commentre.*}{$1}gxms;
	  my $replacement = " "x(1+(length $comment));
	  $line =~ s{$commentre}{$replacement}gxms;
	}
  }
  return $line;
}
