code re-structured and cleaned up