/*
 * The MIT License
 *
 * Copyright (c) 2008-2009 MIT 6.270 Robotics Competition
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
 * THE SOFTWARE.
 *
 */

#include <joyos.h>
#include <lib/pid.h>
#include <math.h>
#include "umain.h"

#define RightMotor 1
#define LeftMotor 0

#define RightEncoder 25
#define LeftEncoder 24

#define TargetVelocity -200
#define MaxVelocity -250

uint16_t PIDDelay;

extern int left_speed, right_speed;

void ResetEncoders()
{
	encoder_reset(RightEncoder);
	encoder_reset(LeftEncoder);
}

float EncoderDifferential()
{
	return (float)encoder_read(RightEncoder)-(float)encoder_read(LeftEncoder);
}

float BoundedVelocity(float ProposedVelocity)
{
	if (fabs(ProposedVelocity) > fabs(MaxVelocity))
	{
		return MaxVelocity;
	}
	else
	{
		return ProposedVelocity;
	}
}

void ForwardApplyMV(float MV)
{
	if (right_speed > 0) {
		drive(BoundedVelocity(left_speed+MV/2),BoundedVelocity(right_speed-MV/2));
	}
	else {
		drive(BoundedVelocity(left_speed+MV/2),BoundedVelocity(right_speed-MV/2));
	}
}

void MotorCoast(uint8_t Motor)
{
	motor_set_vel(Motor, 0);
}

void CoastMotors()
{
	MotorCoast(RightMotor);
	MotorCoast(LeftMotor);
}

void TurnApplyMV(float MV)
{
    if (left_speed > right_speed) {
        drive(BoundedVelocity(left_speed+MV/2),BoundedVelocity(right_speed+MV/2));
   
    }
    else {
        drive(BoundedVelocity(left_speed-MV/2),BoundedVelocity(right_speed-MV/2));
    }
}

