re-organized the code for simplicity and modularity.