re-arranged code cleaned up