refactor serial code and use less globals