everything done except prettification
refactored for clarity