#!/usr/bin/python3

import sys

waypoint_horz=10
waypoint_vert=1
directions=["E", "S", "W", "N"]
ship_x=0
ship_y=0

def do_waypoint_move(direction, amount):
    global waypoint_horz
    global waypoint_vert
    if direction in ["E", "W"]:
        if direction == "W":
            amount=amount*-1
        waypoint_horz+=amount
    elif direction in ["N", "S"]:
        if direction == "S":
            amount=amount*-1
        waypoint_vert+=amount

def turn(amount,multiplier):
    global waypoint_horz,waypoint_vert
    steps=int(amount / 90)
    steps=steps * multiplier

    print("Started at: {},{} rotating {}".format(waypoint_horz,waypoint_vert,amount*multiplier))
    print("Steps: {}".format(steps))
    # translate left in to moves right
    if (steps < 0):
        steps=4+steps

    if steps == 4 or steps == 0:
        return

    print("Steps: {}".format(steps))

    # and now we just step round that many steps to the right
    # now 1,2 will go round to 2,-1, i.e. x,y -> y,-x
    for step in range(steps):
        temp=waypoint_vert
        waypoint_vert=(waypoint_horz*-1)
        waypoint_horz=temp

    print("Ended at: {},{}".format(waypoint_horz,waypoint_vert))

def do_ship_move(amount):
    global waypoint_horz,waypoint_vert,ship_x,ship_y
    print("Waypoint {},{}, Ship {},{}, Amount {}".format(waypoint_horz, waypoint_vert, ship_x, ship_y, amount))
    ship_x+=(amount*waypoint_horz)
    ship_y+=(amount*waypoint_vert)
    print("Ship {},{}".format(ship_x, ship_y))

def turn_right(amount):
    turn(amount, 1)

def turn_left(amount):
    turn(amount, -1)

filename="input.txt"

if len(sys.argv) > 1:
    filename=sys.argv[1]

for line in open(filename, "r"):
    line=line.rstrip()
    command=line[0]
    amount=int(line[1:])

    if command in [ "N", "S", "E", "W" ]:
        do_waypoint_move(command, amount)
    elif command == "R":
        turn_right(amount)
    elif command == "L":
        turn_left(amount)
    elif command == "F":
        do_ship_move(amount)

print("Moved to {}, {} - MD: {}".format(ship_x,ship_y,(abs(ship_x)+abs(ship_y))))
