restructured so variables are passed around properly