Seems like adding if $k and swapping the sections in your original if should fix it. Maybe?