Refined code according to @jalperin's feedback