Reduce loops and cleanup code