#!/usr/bin/perl -w
use File::Copy;
#use Math::ElFun qw(:all);

######################################
# generator of open IT DDDB          #
#  -~= Written by Vincent Fave =~-   #
######################################


# arg 0 is filename 
# arg 1 is the ASide opening shift in cm's
# arg 2 is the CSide opening shift in cm's

$BkpNotExists = 0;

@args2ll = ("ls","-l","$ARGV[0].bkp");
system(@args2ll) == 0 or $BkpNotExists = 1;

if($BkpNotExists == 1){
    if(-e $ARGV[0])
    {
	copy("$ARGV[0]","$ARGV[0].bkp") or die "File cannot be copied";
    }
    else
    {
	print "File does not exist.\n";
	exit;
    }
}

sub sign
{
$out = 1.0;
if($_[0]<0.0){$out = -1.0;}else{$out = 1.0;}    
}


$scale = 10.0;

$element = qr/<posXYZ\sx="\(?(-?\d*\.?\d*)(\+?.*?)(c|m)m"/;
#$element = qr/posXYZ/;
print $element;
open(INPUT,"$ARGV[0].bkp") or die "Cannot open file: $ARGV[0].bak $! \n";
open(FILE,">$ARGV[0]");
@LINES = <INPUT>;		# Read it into an array
for $i (0 ... $#LINES){
    $_ = $LINES[$i];    
    if($LINES[$i] =~ /$element/){
	#print "$2\n";
	$posxini = $1;
	$posx = $1;
	if($3 =~ /c/){
	    if($LINES[$i+1] =~ /rotX/){
		$posx = $posxini;		
	    } elsif($LINES[$i-1] =~ /"pvT(1|2|3)SigR5"/) {
		if(sign($posxini) == 1){	
		    $posx = $posxini-$ARGV[2];
		} elsif(sign($posxini) == -1) {
		    $posx = $posxini+$ARGV[1];	
		}
	    } else {
		if(sign($posxini) == 1){	
		    $posx = $posxini+$ARGV[1];
		} elsif(sign($posxini) == -1) {
		    $posx = $posxini-$ARGV[2];	
		}	
	    }
	} elsif($3 =~ /m/){	
	    if ($LINES[$i-1] =~ /"pvT(1|2|3)SigA1"/) {
		$posx = $posxini+$ARGV[1]*$scale;
	    } elsif($LINES[$i-1] =~ /"pvT(1|2|3)SigC(1|2)"/) {
		if(sign($posxini) == 1){	
		    $posx = $posxini-$ARGV[2]*$scale;
		} elsif(sign($posxini) == -1) {
		    $posx = $posxini+$ARGV[1]*$scale;	
		}
	    } else {
		if(sign($posxini) == 1){	
		    $posx = $posxini+$ARGV[1]*$scale;
		} elsif(sign($posxini) == -1) {
		    $posx = $posxini-$ARGV[2]*$scale;	
		}
	    }
	}
	s/(<posXYZ\sx=..?)$posxini/$1$posx/g;
	print;
    }
    print FILE;
}

close FILE;


