Reorganized things into functions and many improvments.