#!/perl -w
# NAME: space2tab.pl
# AIM: Convert LEADING spaces to tab
use strict;
use warnings;
require 'logfile.pl' or die "Unable to load logfile.pl ...\n";
# log file stuff
my ($LF);
my $pgmname = $0;
if ($pgmname =~ /\w{1}:\\.*/) {
	my @tmpsp = split(/\\/,$pgmname);
	$pgmname = $tmpsp[-1];
}
my $outfile = "temp.$pgmname.txt";
open_log($outfile);
prt( "$0 ... Hello, World ...\n" );

my $in_file = 'temp1.txt';
my $out_file = 'temp2.txt';
my $tot_chars = 0;
my $conv_chars = 0;
my $line_count = 0;
### The program as a SINGLE LINE !!!
###perl -i~ -pe "/^( +)/ or next; $I or $I=$1; for($i=0;s/^$I//;$i++){}$_=(qq'\t' x $i).$_;" file ...
### THe program working line by line ...
prt( "Process $in_file ...\n" );
if (open INF, "<$in_file") {
	my @lines = <INF>;
	close INF;
	my @nlines = ();
	foreach my $line (@lines) {
		#chomp $line;
		$line_count++;
		my $len = length($line);
		my $nline = '';
		my $ch = '';
		my $i = 0;
		$tot_chars += $len;
		if ($line =~ /^ /) {
			for ($i = 0; $i < $len; $i++) {
				$ch = substr($line, $i, 1 );
				if ($ch eq ' ') {
					$conv_chars++;
					###prt( "Converted $conv_chars ...\n" );
				} else {
					last;
				}
			}
			$nline .= (qq'\t' x $i).substr($line,$i);
		} else {
			$nline = $line;
		}
		push(@nlines, $nline);
	}
	prt( "Done $line_count lines, $tot_chars characters, converting $conv_chars to TAB ...\n" );
	write2file( join('', @nlines), $out_file );
	prt( "Results written to $out_file ...\n" );
	do_file($in_file);

} else {
	prt( "ERROR: FAILED TO OPEN FILE ... $! ...\n" );
}

close_log($outfile,0);
exit(0);

# Another way using the $_ variable
sub do_file {
	my ($file) = shift;
	my ($I, $i);
	prt( "Processing $file again ...\n" );
	if (open INF, "<$file") {
		while (<INF>) {
			if (/^( +)/) {
				$I or $I=$1;
				for($i = 0; s/^$I//; $i++){}
				$_ = (qq'\t' x $i).$_;
			}
			prt( $_ );
		}
		close INF;
	}
}

# eof
