Cleaned up my code. Tried to make it more fundamentally generic.