Refacted and cleaned up code