Cleaned up code a little, made it generic