improved nested logic