#!/usr/bin/perl

################################################################################
# Program to fix incorrect node IDs of DIMES measurement                       #
# Please send questions, suggestions and bugs to waehlisch@ieee.org            #
################################################################################

$dimesnodef = $ARGV[0];
$dimesedgef = $ARGV[1];

if(@ARGV != 2) {
  print "usage: <DIMES node file> <DIMES edge file>\n";
  exit;
}

print "Using node file $dimesedgef and edge file $dimesnodef\n";

#Process edge file
print "Processing edge file ...\n";
open(DIMESEDGE,$dimesedgef) || die "File $dimesedgef not found";
open(DIMESEDGEFIX,"> $dimesedgef.fix") || die "File $dimesedgef.fix not found";
while(<DIMESEDGE>){
  next if /^\s*#/;
  chomp;
  (@edgeline)=split(/,/);

  #Filter
  #Check source IP
  if($edgeline[0] =~ /\d-\d/) {
    ($tmpsrcip1,$trash,$tmpsrcip2) = split(/-/,$edgeline[0]);
    if($tmpsrcip1 eq $edgeline[1]) {
      $edgeline[0] = $tmpsrcip2;
    }
    else {
      $edgeline[0] = $tmpsrcip1;
    }
  }
  #Check destination IP
  if($edgeline[1] =~ /\d-\d/) {
    ($tmpdstip1,$trash,$tmpdstip2) = split(/-/,$edgeline[1]);
    if($tmpdstip1 eq $edgeline[0]) {
      $edgeline[1] = $tmpdstip2;
    }
    else {
      $edgeline[1] = $tmpdstip1;
    }
  }
  print DIMESEDGEFIX join(" ",@edgeline) . "\n";
}
close(DIMESEDGE);
close(DIMESEDGEFIX);

#Process node file
print "Processing node file ...\n";
open(DIMESNODE,$dimesnodef) || die "File $dimesnodef not found";
open(DIMESNODEFIX,"> $dimesnodef.fix") || die "File $dimesnodef.fix not found";
while(<DIMESNODE>){
  next if /^\s*#/;
  chomp;
  (@nodeline)=split(/,/);
  if($nodeline[0] =~ /\d-\d/) {
    ($tmpnodeip1,$trash,$tmpnodeip2) = split(/-/,$nodeline[0]);
    if($nodeexists{$tmpnodeip1} != 1) {
      $nodeline[0] = $tmpnodeip1;
    }
    elsif($nodeexists{$tmpnodeip2} != 1) {
      $nodeline[0] = $tmpnodeip2;
    }
  }
  print DIMESNODEFIX join(" ",@nodeline) . "\n";
  $nodeexists{$nodeip} = 1;
}
close(DIMESNODE);
close(DIMESNODEFIX);

print "Finished ...\n";
