Prevented a Type Error and cleaned up logic