Help with BGE scripts

I have run into a game breaking problem with my movement mechanic. The issue is with the horizontal (left-right) mouselook. This is the current module;


def hmouse():
    sensitivity = 0.001
    hlimit = math.radians(0)
    own = bge.logic.getCurrentController().owner
    mouse = own.sensors['mouse']
    mid = Vector([200,200])
    mpos = Vector(mouse.position)

    if not "ml_angle" in own:
        own["ml_start_mat"] = own.localOrientation.copy() 
        own["ml_angle"] = Vector([0,0])
        mpos = mid.copy()
        bge.render.showMouse(0)

    if (("mouselook_active" in own and own["mouselook_active"]) or not "mouselook_active" in own):
        own["ml_angle"] += (mpos - mid)*sensitivity

    own["ml_angle"][1] = max(min(own["ml_angle"][1],hlimit),-hlimit)
    xmat = Matrix.Rotation(-own["ml_angle"][1],3,"X")
    zmat = Matrix.Rotation(-own["ml_angle"][0],3,"Z")
    own.localOrientation = own["ml_start_mat"]*zmat*xmat
    bge.render.setMousePosition(int(mid[0]),int(mid[1]))

It breaks when used in conjunction with this module;


def movement(): 
    cont = bge.logic.getCurrentController() 
    player = cont.owner 
    keyboard = bge.logic.keyboard 
    mouse = bge.logic.mouse 
    scene = bge.logic.getCurrentScene()

    if bge.logic.KX_INPUT_ACTIVE == keyboard.events[bge.events.WKEY]: player.applyMovement((0, 1, 0), True) 


This is supposed to cause the player to move along the local +Y axis, which it does. However, as soon as you rotate left or right, the movement locks on to the direction you were facing prior to rotation. I can’t seem to figure out why and there are no errors reported in the terminal. Any ideas?

My best guess is that I have to update the mouse position every frame to account for the new direction. Can anyone take a look and let me know where this would go?