Help with software PWM

I’m having some trouble with implementing a software PWM function, specifically getting it to work with multiple pins. Below is the code I’m using, it works perfectly with just one pin, but, rather obviously, it fails when used with multiple pins. This makes sense if you look at the code. My question is how would I alter the program to use multiple pins?

int PWM = 50; //out of 255 for 1khz or 3.9khz, out of 100 for 9.6khz
boolean state = false;                 // this is absolutely required

unsigned long previousMicros = 0;      // so are these
unsigned long previousMillis = 0;

const byte LED = (1<<PB4);
const byte POT = A0;

void setup() {
  DDRB = LED;
}

void loop() {
// PWM = AinFunction(POT);
 PWMfunction(LED, PWM);
}

//This is the actual function for the softPWM
void PWMfunction(int ledPin, int PWM) {
  PWM = PWM * 4; //if using 1023 delay
  unsigned int intervalLow = 1023 - PWM; //use 1023 delay for 1khz frequency, 255 for 3.9khz, 100 for 9.6khz
  unsigned int intervalHigh = 1023 - intervalLow; //use 1023 delay for 1khz, 255 for 3.9khz, 100 for 9.6 khz
  unsigned long currentMicros = micros();
if(intervalHigh != 0) {
 if(state == false) {
  if(currentMicros - previousMicros >= intervalLow) {
    previousMicros = currentMicros;   
    state = true;
    PORTB = ledPin; //this would be digitalWrite as long as the frequency is below 2 khz
  }
 }
 if(state == true) {
  if(currentMicros - previousMicros >= intervalHigh) {
    previousMicros = currentMicros;   
    state = false;
    PORTB = !ledPin; //this would be digitalWrite as well
   }
  }
 }
}

int AinFunction(byte pin) {
  if(millis() - previousMillis >= 100) {
    int val = analogRead(pin);
    val = map(val, 0, 1023, 0, 100);
    previousMillis = millis();
    return val;
  }
}

You could add extra pins with this method only you do screw yourself for doing anything very much else in the code if you want stable PWM.

The best way to do this is rather advanced. It involves using a timer to generate an interrupt, then have the interrupt service routine handle as many pins as you want, rather like the servo drivers do.

If you search I think you will find some one has written a soft PWM library.