Fix crashes, improve code to readibility.