Code cleaned up and re-organized