photosensor reverse min and max.

hello
this little test code makes the led goes fully on when its dark
and off when its light, in reverse.

and i want to set a min and max lvl, so when the lvl are below(or abow) X the led goes fully on,
and when its abow(or below) X the leds go fully off,
and anything in between is dimmed according to light in the room.

however, now this works like a on / off switch.
on when covered, off when not, nothing in between.

#define photoSensorPin A0

void setup()
{
  Serial.begin(9600);
}
void loop() {
    int val = analogRead(photoSensorPin);
    val = map(val, 100, 900, 0, 255);
      if(val < 50) {
        val = 0;
      }
      else if(val <800) {
        val = 255;
      }
    analogWrite(9, 255-val);     
    Serial.println(val);
//    Serial.println(photoSensorPin);
    delay(50);
  }