restructured and cleaned code