rewrite using class to avoid global variables