moved most code from app to lib