re-arranged the code to simplify the .cpp file