Refactor. Still has a bug to be fixed.