restructured code a bit