calculate correct data ranges and cleaning up code