Code now functions as desired