divided into functions, comments added