function(                                                      # PLOT ACTIVITY/STATE OVER TIME FOR A SPATIAL LAYER
  df=factor(NULL,levels=dataframes(eN))[[1]],                                                     # Settings                     # data frame to plot
  template=factor(NULL,levels=eN_colnamesplit(word.list)$levels),                                 # Settings                     # Word to use as template (enclose in "")
  plot_type=factor("SWD",levels=c("SWD","SWD and Superposition","Superposition"))[[1]],           # Settings                     # Plot signal-weight differences and/or superposition function   
  tm=factor("0",levels=df["time"])[[1]]                                                           # Settings                     # Time slice to plot
) {
#  word.list=factor(eN["(words default_observer)"],levels=dataframes(eN))[[1]],      # Dataframes                   # Dataframe with word list
  
  tryCatch(
    {
            
        require(lattice)
      #  word.list=factor(eN["(words default_observer)"],levels=dataframes(eN))[[1]],      # Dataframes                   # Dataframe with word list
        
        myquit <- function(msg) { print("Quitting"); plot(0,0,type="n"); text (0,0,msg,cex=2); stop() }
        

        
        
        print("Starting")
        time=as.character(tm)
        # print("19")
        if (time=="0") { tm=df$time[nrow(df)-1]; time=df$time[tm]}
        # print("20")
        tm=which(df$time==time)[1]
        nr<-nrow(df) - 2
        if (nr>0)
          if(sum(unlist(df[tm,-c(1)]))>0) print(paste("time=",time)) else { 
            print(paste("Error: no data for time=",time,". Quitting")); myquit(paste("Error: no data for time=",time))
          }
        # print("26")
        scaler<- function(sigma) { return (dnorm(0,0,sigma)) }
        cols<-eN_colnamesplit(df)$levels
        cols<-c("",cols) # adjust for time column
        # print("line 29")
        
        #df<-df[which(df$time==tm),]
        
        d<-data.frame(location=NULL,amplitude=NULL,sigma=NULL,time=NULL,title=NULL)
        
        for(i in 2:length(cols)) {
          if(sum(unlist(df[,i]))>0){
            for (r in 1:length(t(df[,i][[tm]])))
              d<-rbind(d,
                       cbind(
                         (t(df[,i][[tm]][[r]])),tm,
                         data.frame(title=cols[i])
                       )
              )
          }
        }
        
        # print("line 47")
        #  d=na.omit(d)
        names(d) = c("location","amplitude","sigma","time","title")
        d=d[order(d$location),]
        print(head(d))
        stim<-paste0(d$title[order(d$location)],collapse="")
        if (is.null(template)) template=stim
        if ((length(template)==0)||(template=="")) { words<-eN_colnamesplit(word.list)$levels; template = words[1]; print(paste("template=",template))} 
        template <- toupper(template)
        # tail(d)
        
        Mode <- function(x) {
          ux <- unique(x)
          ux[which.max(tabulate(match(x, ux)))]
        }
        
        ##############################################################################
        letter.signals=d$title # levels(d$title)
        
        
        rec = data.frame(matrix(ncol=nchar(template),nrow=nrow(d)))
        tlist=unlist(strsplit(template,split=""))
        d=d[d$title %in% tlist,]
        c=1; order=NULL; to.add=data.frame(letter=rep(NA,length(tlist)),pos=rep(NA,length(tlist)))
        input.copy <- d$title
        for (letter in tlist)
        {
          n <- which (input.copy  == letter) # [1]
          if (length(which(!is.na(n)))>0) 
          {
            order <- c(order,n)
            rec[n,c] = round(d$location[n],digits=1) - c + 1
            #      input.copy[n]=NA
          } else {to.add$letter[c]=letter; to.add$pos[c]=c-1} 
          c <- c+1
        }
        to.add=na.omit(to.add)
        
        # testing! get rid of rows where there was no match
        for (r in seq(length(tlist),1,by=-1))
        {
          if (length(which(!is.na(rec[r,])))==0) rec <- rec[-r,]
        }
        
        
        
        v <- c(t(rec)); v <- v[!is.na(v)]; rec2 = (rec - Mode(v)) # subtract mode from swds
        if (length(which(!is.na(rec)))>0)
        {
          for (c in 1:ncol(rec))
            #    if (sum(!is.na(rec2[r,1:length(tlist)])) > 0) 
            # print(rec2[,c])
          if (sum(!is.na(rec2[,c])) > 0) 
            rec2[which(min(abs(rec2[,c]),na.rm=T) != abs(rec2[,c])),c]=NA # competition within banks
          rec2$swd=NA
          rec2$swd=as.numeric(rec2$swd)
        }
        # print("line 108")
        if (length(which(!is.na(rec2)))>0)
          for (r in 1:nrow(rec2))
          {  
            if (length(which(!is.na(rec2[r,])))>0) rec2[r,which(min(abs(rec2[r,]),na.rm=T) != abs(rec2[r,]))]=NA # competition between banks
            if (length(which(!is.na(rec2[r,])))>0) rec2$swd[r] = max(rec2[r,],na.rm = T) else rec2$swd[r] = NA
          }  
        df=d
        if (length(which(!is.na(rec2)))>0) 
          df=cbind(df,rec2[1:nrow(d),]) 
        nm=names(df)
        
        # testing! get rid of rows where there was no match
        for (r in seq(length(tlist),1,by=-1))
        {
          if (is.na(df[r,ncol(df)])) df <- df[-r,]
        }
        
        #add any letters missing from template
        df$title=as.character(df$title)
        if(nrow(to.add)>0)
          for (i in 1:nrow(to.add))
          {
            df=rbind(df,rep(NA,ncol(df)))
            df[nrow(df),1]=to.add$pos[i]
            df[nrow(df),5]=to.add$pos[i]
            df[nrow(df),which(nm=="title")]=to.add$letter[i]
          }
        
        #   for (i in 0:(-1+length(tlist)))
        #   {
        #     if(!(i %in% df[,5]))
        #     {
        #     df=rbind(df,rep(NA,ncol(df)))
        #     df[nrow(df),5]=i
        #     df[nrow(df),which(nm=="title")]=tlist[i+1]
        #     }
        #   }
        #    df=df[-duplicated(df[,5]),]  
        
        names(df)=nm
        if (length(which(!is.na(rec2)))==0) df$swd = NA
        
        df=df[order(match(df$title, tlist)),]
        #  df=df[order(df[,5]),]
        ##############################################################################
        
        num=nrow(df)
        
        op <- par(oma = c(5,6,0,0) + 0.1,
                  mar = c(0,1,2,1) + 0.1)
        
#         print("line 160")
        if (plot_type=="SWD")
          plot.superposition=F else plot.superposition=T
        if (plot_type=="Superposition")
          plot.SWD=F else plot.SWD=T
        
        
        m = matrix(nrow=max(plot.superposition,(plot.SWD)*num),ncol=plot.SWD+plot.superposition)
        if (plot.SWD) m[,1]=1:num ; 
        if (plot.superposition) m[,(1+plot.SWD)] = (plot.SWD)*num+1
        layout(m)
        
        if (length(which(!is.na(df$swd)))>0) {
          xrange=seq(-5 + median(df$swd,na.rm = T),5 + median(df$swd,na.rm = T),by=0.1)
          xrange2 = c(round(-5 + median(df$swd,na.rm = T)):round(5 + median(df$swd,na.rm = T)))
        } else {  
          xrange <- seq(-5 ,5 ,by=0.1)
          xrange2 <- -5:5
        }
        
        yvals=data.frame(matrix(0,nrow=num,ncol=length(xrange)))
        for (i in 1:num)
        {  
          if (! is.na(df$swd[i])) yvals[i,] = df$amplitude[i]/scaler(df$sigma[i]) * dnorm(xrange,df$swd[i],df$sigma[i])
        } 
        superpos = colSums(yvals)
        peak_x = xrange[which(superpos == max(superpos))[1]]
        peak_y = max(superpos)
        
        if (plot.SWD) 
        {    
          # print(num)
            for (i in 1:num)
            {  
#               print(xrange)
#               print(yvals[i,] )
              plt <- plot(xrange,yvals[i,] ,type="l", lwd=2, col="blue",
                          axes = FALSE, 
                          xlab="",ylab="",ylim=c(0,1),
                          xaxt="n")
              if (i==1) mtext(paste("Template =",template),cex=1.5,side=3, line=0, at=par("usr")[1]+0.5*diff(par("usr")[1:2]))
              plt <- axis(side = 1,
                          at=xrange2, cex.axis=1.5, #6/min(4,num),
                          labels = if (i == num) xrange2 else FALSE)
              axis(side = 2, at=seq(0,1,by=.25),las=1, cex.axis=1.5, labels = T)
              plt <- box(which = "plot", bty = "l")
              if (i==num) 
                mtext("Signal-Weight Difference",side=1, cex=1.5, line= 4, at=par("usr")[1]+0.5*diff(par("usr")[1:2]))
              #    plt <- grid()
              if (peak_y>.0001) plt <- abline (v = peak_x,lty=2,col="red")
              if (is.na(df$swd[i])) plt <- text(min(xrange) + num/4,0.2*num/4,df$title[i],cex=12/num) else plt <- text(df$swd[i],0.2,df$title[i],cex=12/num)
            }
            
            #   plt <- title(xlab = "Signal-Weight Difference", cex.lab=12/num,
            #         ylab = "Amplitude",
            #         outer = TRUE, line = 3)
        }
        
        if (plot.superposition)
        {  
          plt <- plot(xrange,superpos,type="l", lwd=2, col="blue",
                      axes = FALSE, 
                      xlab="",ylab="",ylim=c(0,num)
                      #xaxt="n")
          )
          plt <- axis(side = 1,
                      at=xrange2, cex.axis=1.5,
                      labels = if (i == num) xrange2 else FALSE)
          plt <- axis(side = 2, las=1, cex.axis=1.5, labels = T)
          plt <- box(which = "plot", bty = "l")
          plt <- title(cex.lab=3, # 9/min(4,num),
                       ylab = "Amplitude",
                       outer = TRUE, line = 3)
          if (peak_y>.0001) plt <- abline (v = peak_x,lty=2,col="red")
          plt <- abline (h = peak_y,lty=2,col="red")
          mtext("Superposition",side=1, cex=1.5, line= 4, # outer=TRUE, 
                at=par("usr")[1]+0.5*diff(par("usr")[1:2]))
          
          text(xrange[20],peak_y - .3*((peak_y>(num-.05)) -.5),paste("Match =",format(peak_y/num,digits=2)), cex=1.75)
          
        }
    }, warning = function(w) { print(w); plt <- plot(0,0,"n",xaxt="n",yaxt="n",xlab="",ylab=""); return
      
    }, error = function(e) { print(e); plt <- plot(0,0,"n",xaxt="n",yaxt="n",xlab="",ylab=""); return
      
    }, finally = { print ("done"); # plt <- plot(0,0,"n",xaxt="n",yaxt="n",xlab="",ylab="")
      
    }
  )
  
}
