x=c(355,355,355,355,355,355,355,355,355,355,355,355,355,355,355,355,355,355,355,355,355,355,355,355,355,355,354,354,354,354,354,354);
x=c(221,220,220,220,220,220,220,220,220,220,220,220,220,220,220,220,220,220,220,220,220,220,220,220,220,220,220,220,220,220,220,233);
x=c(246,246,246,246,246,246,246,246,246,246,246,246,245,245,245,245,245,245,245,245,245,245,245,245,245,245,245,245,245,245,245,245,245,245,245,245,245,245,245,245,245,245,245)


		span = 30;			
		threshold = 3;			
		discard = 10;			
						
		maxX = 512;			
		maxY = 384;			
		cat('(', length(x), '): ', x[length(x)]);				
						
		if( length(x) < discard || sd(x) == 0) {
			n<-  x[ length( x ) ];	
		} else {									
			which.predict <- max( 1, length(x) - span):length(x);			
			time.1 <- 1:length( which.predict );					
			x.1    <- x[ which.predict ];						
												
			resid  <- x.1 - predict( lm( x.1 ~ time.1 ), data.frame( time.1 = time.1 ) );	
			x.outlier <- abs( resid ) > threshold * sd( resid );			
												
			time.1   <- time.1[!x.outlier];						
			x.1      <- x.1   [!x.outlier];						
		
			if( is.na(sd(x.1)) ) {
				n<-  x[ length( x ) ];	
			} else {
				n<- round (								
					predict( lm( x.1 ~ time.1 ), newdata = data.frame( time.1 = length( time.1 ) + 1 ) ) 	
				);									
			}
		}				



	span = 30 / length(x);	
		threshold = 3;		
		discard = 10;	
				
		if( length(x) < discard || sd(x) == 0) {			
			n <- x[ length( x ) ];					
		} else {							
   			time <- 1:length(x) 					
										
			resid <- x - predict( loess(x ~ time, span = span), time );	
			x.outlier <- abs(resid) > threshold * sd(resid);	
										
			time.1   <- time[!x.outlier];				
			x.1      <- x   [!x.outlier];				
										
			n <- predict( loess(x.1 ~ time.1, span = span), time ); 
		}		




