rewrite with better logic and stuff