The Buddhist doctrine of egolessness seems to be a bit confusing to westerners. I think this is because there is some confusion as to what is meant by ego. Ego, in the Buddhist sense, is quite different from the Freudian ego. The Buddhist ego is a collection of mental events classified into five categories, called skandhas, loosely translated as bundles, or heaps.
If we were to borrow a western expression, we could say that "in the beginning" things were going along quite well. At some point, however, there was a loss of confidence in the way things were going. There was a kind of primordial panic which produced confusion about what was happening. Rather than acknowledging this loss of confidence, there was an identification with the panic and confusion. Ego began to form. This is known as the first skandha, the skandha of form.
After the identification with confusion, ego begins to explore how it feels about the formation of this experience. If we like the experience, we try to draw it in. If we dislike it, we try to push it away, or destroy it. If we feel neutral about it, we just ignore it. The way we feel about the experience is called the skandha of form; what we try to do about it is known as the skandha of impulse/perception.
The next stage is to try to identify, or label the experience. If we can put it into a category, we can manipulate it better. Then we would have a whole bag of tricks to use on it. This is the skandha of concept.
The final step in the birth of ego, is called the skandha of consciousness. Ego begins to churn thoughts and emotions around and around. This makes ego feel solid and real. The churning around and around is called samsara -- literally, to whirl about. The way ego feels about its situation (skandha of feeling) determines which of the six realms of existence it creates for itself.