Added cache functionality and restructured code