corrected varible names, part of the code is moved to the functions