#!/usr/bin/env ruby

def simplifyRouteV1(directions)
  result = directions.join('')
  loop { break unless result.gsub!(/NS|SN|EW|WE/, '') }
  result.split('')
end

def simplifyRoute(directions)
  reverse = { 'N' => 'S', 'S' => 'N', 'E' => 'W', 'W' => 'E' }
  directions.each_with_object([]) do |step, simplified|
    reverse[step] == simplified.last ? simplified.pop : simplified.push(step)
  end
end

if __FILE__ == $PROGRAM_NAME
  (warn "Usage: ruby #{$0} <csv-directions> (v1|v2[default])"; exit) unless ARGV.length == 1 || ARGV.length == 2
  directions = ARGV[0].split(',').map(&:strip)
  warn "directions: #{directions.inspect}"
  case ARGV[1]
  when 'v1'
    result = simplifyRouteV1(directions)
  else
    result = simplifyRoute(directions)
  end
  warn 'Result:'
  puts result.inspect
end
