Cleaned up the code a little, but will probably edit it further