A model for territory and group formation in a heterogeneous habitat