#!/usr/bin/ruby
#programmer: Elnaz Ebrahimi
#Description:
#Reorders the file generated by simpoint so
#that it is easier to process by esesc.

def readFile(labelFile, index, toBeReplaced, newLabelFile, labelAry)
   if(index == 0)
     while (line = labelFile.gets)
       labelAry.push(line)
     end
   end
   labelFile.seek(0,IO::SEEK_SET)
   row = 0
   while (line = labelFile.gets)
      text = line.split(' ')
      if (text[0]== toBeReplaced)
         text[0] = index
         labelAry[row] = text[0].to_s+' '+text[1].to_s
      end
      row = row + 1
   end
end

lineAry = Array.new
labelAry = Array.new
$row = 0

if ARGV.length != 4
   puts "USAGE: " + $0 + "  simpoint_file label_file new_label_file new_simpoint_file"
   exit 0
end

spFile      = File.open(ARGV[0],"r")
labelFile   = File.open(ARGV[1], "r+")
newLabelFile = File.open(ARGV[2], "w")
newSpFile   = File.open(ARGV[3], "w")

while (line = spFile.gets)
   lineAry.push(line)
end

lineAry.sort! {|a,b| a.to_i <=> b.to_i}

# Reorder simpoint file based on # of instructions
# skipped
for j in 0..(lineAry.length-1)
   tmptext = lineAry[j].split(' ')
   newSpFile.puts tmptext[0].to_s+' '+j.to_s
end

# The index to LineAry is the new value
# The second field in the sorted lineAry is the old value
for i in 0..(lineAry.length-1)
   text = lineAry[i].split(' ')
   toBeReplaced = text[1]
   readFile(labelFile, i, toBeReplaced, newLabelFile, labelAry)
end
labelAry.each do |line|
  newLabelFile.puts line
end

spFile.close
labelFile.close
newLabelFile.close
newSpFile.close


