#!/usr/bin/perl

use strict;
use Getopt::Long;

my $help=0;
my $gap_fill="\n-----\n";
my $spaces=0;

my $configfile1="../../conf/kot.conf";
my $configfile2="../conf/kot.conf";

#read configuration files###########################
my $file;
foreach $file ($configfile1, $configfile2){
  if(open(CONFIG, $file)){
  	while (<CONFIG>) {
  		chomp;                  
      		s/#.*//;                
	      	s/^\s+//;               
      		s/\s+$//;               
    		next unless length;     
    		my ($name, $value) = split(/\s*=\s*/, $_, 2);
    		if(($name eq "gap-fill")or($name eq "g")){
			$gap_fill=$value;
    		}
    		elsif(($name eq "spaces")or($name eq "s")){
			$spaces=1;
		}
    		elsif(($name eq "help")or($name eq "h")){
			$help=1;
    		}
    	
	} 
  	close CONFIG;
  }
}
#########################################################

GetOptions("gap-fill|g=s" => \$gap_fill,
	   "spaces|r" => \$spaces,
	   "help|h" => \$help);

if($help)
{
    print <<'END'
Usage: ser [OPTIONS] [file ..]

Options:
   --gap-fill -g                  Help.
   --spaces -r                    
   --define=FILE                  Read macrodefinitions from FILE.
   --flex-template=FILE           Read flex code template from FILE.
   --only-matching -m		  Print only fragments matching PATTERN.
   --flex                         Print only the generated flex code and exit.
END
;
    exit 0;
}


$gap_fill =~ s/\\t/\t/g;
$gap_fill =~ s/\\n/\n/g;
$gap_fill =~ s/\\r/\r/g;
$gap_fill =~ s/\\f/\f/g;

my $prevend=-1;
my $count=0;

while(<>)
{
    my ($start,$len,$type,$form) = /^\s*(\d+)\s+(\d+)\s+(\S+)\s+(\S+)/;
    
    if($start > $prevend)
    {
	print $gap_fill unless $count++ == 0;
    }

    $prevend=$start+$len;
    
    next if $len==0;# || $form eq "*";

    $form =~ s/\\\*/*/g;

    if($type eq 'S' && ! $spaces)
    {
	$form =~ s/_/ /g;
	$form =~ s/\\t/\t/g;
	$form =~ s/\\n/\n/g;
	$form =~ s/\\r/\r/g;
	$form =~ s/\\f/\f/g;
    }

    print $form;
}

#print $gap_fill;

# print "\n";
