can you comment and annotate the following script: packages <- c(
  "tidyverse", "shiny", "shinydashboard",
  "shinyFiles", "shinyWidgets", "shinythemes","RColorBrewer","ggthemes","plotly","shinyBS","processx"
)

 #Now load or install&load all packages
 package.check <- lapply(
  packages,
  FUN = function(x) {
    if (!require(x, character.only = TRUE)) {
      #install.packages(x, dependencies = TRUE)
      library(x, character.only = TRUE,lib.loc="/home/pxl10/R/x86_64-pc-linux-gnu-library/4.2/")
    }
  }
)

#options(shiny.port = 3142)
#options(shiny.host = "10.50.156.93")
instance <- "Test"
sample_list <- ("")



ui <- dashboardPage(
  skin = "red",
  dashboardHeader(title = "Nanopore TB tNGS Assay",titleWidth = 300)
   
|>
    tagAppendChild(
      div(
        paste("DashBoard Instance",instance),
        style = "
      display: block;
      font-size: 1.5em;
      margin-block-start: 0.5em;

      color: white;
      margin-right: 50%",
        align = "left"
      ),
      .cssSelector = "nav"
    ),
  ###side tab setup
  dashboardSidebar(
  width = 300,
  
	br(),br(),

	### 
	shinyFiles::shinyDirButton("test_dir_select",label = "Select Nanopore Run Folder",title = "Directory selection",icon = shiny::icon("folder")),
	shiny::htmlOutput("test_dir_select_ready")
	 ,br(),br(),
     
     fileInput(inputId = "file_sample",label = "Select Sample Sheet",multiple = FALSE),
	 
	 br(),

	 selectizeInput(inputId = "workflow",label = "Select Amplicon Workflow",choices = c("Main AR Targets", "Extended AR Targets"),multiple = FALSE),br(),
	
	 selectizeInput(inputId = "flowcell",label = "Flow Cell type",choices = c("R9","R10"),multiple = FALSE),br(),
 
	 textInput("run_name", label="Enter Run Name", "", width = "600px"),br(),br(),br(),br(),br(),br(),br(),br(),
	
	 bsButton(inputId = "go", width = "250px",label = " Start Pipeline", icon = icon("play-circle"),  style = "success")
	 ),


  dashboardBody(
      fluidRow(
    tabBox(
      # The id lets us use input$tabset1 on the server to find the current tab
      id = "tabset1", height = "1100px",width=12,
      tabPanel(title = "tNGS AMR Targets", 
	 # Select sample
	fluidRow( column(2,   (selectInput(inputId = "sample", label = "Sample:",choices = sample_list, selected = sample_list[1])))),								
	tableOutput('fastq_count'),
	fluidRow(
	column(2, 
	h3("Loci Status:"),
	tableOutput('table'),br(),
	
	actionButton(inputId = "markdown_display", label = "Show Full Report", width = "300px",height = "100px")
	
	,br(),
	h3("Time of last Analyses:"),br(),
	tableOutput('stamp')),
	column(9,offset = 0, plotlyOutput("plot",  height = "800px", width = "100%")))),
    )
  ))
)


####################################################################################################################################
####################################################################################################################################
####################################################################################################################################


####### server side of things #######
ready_to_start <- 0
makeReactiveBinding("ready_to_start")
server <- function(input, output, session) {
whichbutton <- reactiveVal(TRUE)
cancelbutton <- reactiveVal(TRUE)
##my_run_name <<- 0
pid <- 0
fn <- ""
countstamp <- ""
timestamp <- ""
p <- ""

rundir <- "/local/tNGS_TB/FASTQ/"
shiny_save <- paste0 ("/local/tNGS_TB/data_Dashboard_",instance,".RDS")
fn <- ""
loci <- ""


if (file.exists(shiny_save)) {

	loaded_data <- readRDS(shiny_save)
	## list(ready_to_start,pid,my_run_name,whichbutton(),path,samplesheet,xworkflow,fn)
	#whichbutton <- reactiveVal(NULL)
	#whichbutton(!whichbutton())
	ready_to_start <- 3
	pid <- loaded_data[[2]]
	my_run_name <<- loaded_data[[3]]
	path <- loaded_data[[5]]
	samplesheet <- loaded_data[[6]]
	xworkflow <- loaded_data[[7]]
	fn <- loaded_data[[8]]
	path <- fn
	rundir <- (paste0(rundir,my_run_name))
	
	
	print (paste("rundir x ",rundir))
	print (paste("my_run_name x ",my_run_name))
	print (paste("path x ",path))
	print (paste("pid x ",pid))
	
}
  


###download button###
### not working   ###
def_reports_roots <- c(home = "/")
shinyFileChoose(input, 'file_outputs', roots = def_reports_roots)



observeEvent(input$download_button, {
print (paste("pushed..."))
output$file_outputs <- downloadHandler(
  filename <- function() {
    paste("output", "zip", sep=".")
  },

  content <- function(file) {
    file.copy("/home/pxl10/out.zip", file)
  },
  contentType = "application/zip"
)
})







## select directory button
def_roots <- c(home = "/local")
shinyFiles::shinyDirChoose(input, 'test_dir_select', roots = def_roots)   
test_dir_select_ready <- shiny::reactive({
if(length(input$test_dir_select) == 1) {
	  path <- "Directory not yet selected"
	} else {
	  path <- file.path(
		shinyFiles::parseDirPath(def_roots, input$test_dir_select)
	  )
	}
	return(path)
})
output$test_dir_select_ready <- shiny::renderUI({
	shiny::HTML("<font color=\"white\">", test_dir_select_ready(), "</font>")
})


## Select sample sheet button
def_sheet_roots <- c(home = "/")
shinyFileChoose(input, 'file_sample', roots = def_sheet_roots)
sample_sheet_ready <- shiny::reactive({
if(length(input$file_sample) == 1) {
  path_sheet <- "Sample Sheet not selected"
} else {
  path_sheet <- file.path(
	shinyFiles::parseFilePaths(def_sheet_roots, input$file_sample)$datapath
  )
}
return(path_sheet)
})
output$sample_sheet_ready <- shiny::renderUI({
shiny::HTML("<font color=\"white\">", sample_sheet_ready(), "</font>")
})



### Trigger event Start/Stop Button
observe({
	if ((!whichbutton()) && (ready_to_start==0)) {

		if(length(input$file_sample) == 0) {
		  samplesheet <<- "NULL"
		} else {
			samplesheet <<- input$file_sample[4]
		### need to check integrity of the sample sheet
		
		
		}
	   if(length(input$test_dir_select) == 1) {
		  path <<- "NULL"
		} else {
		  path <<- file.path(
			shinyFiles::parseDirPath(def_roots, input$test_dir_select)
		  )
		}
		if (input$workflow == "Main AR Targets") {
			xworkflow <<- "main_line"
		} else {
			xworkflow <<- "extended"
		}	
	
		if (input$run_name == "") {
			##my_run_name <- "NULL"
			### get run name from fasq path ###
			parts <- strsplit(path, "/")[[1]]
			my_run_name <<- parts[4]
			fn <<- paste0(rundir,my_run_name,"/locus_depth.txt")

		} else {
			my_run_name <<- input$run_name
			fn <<- paste0(rundir,my_run_name,"/locus_depth.txt")
		}



		# verify if fastq path given. if true, close and start pipeline
		
		if((path == "NULL")) {
			whichbutton(!whichbutton())
			
		  # show pop-up ...
		  showModal(modalDialog(
			title = "Oh no!",
			paste0("You have not selected a valid MinION FastQ repository, silly person!"),
			easyClose = TRUE,
			footer = NULL
			
		  ))    
		} else {
		
			pathcheck <<- paste0("/local/tNGS_TB/FASTQ/",my_run_name)
			script <- paste0 ("run ",my_run_name)
			# Execute the "ps aux" command and store the output in a variable
			ps_output <- system("ps aux", intern=TRUE)
			print (paste("folder name = ",pathcheck))
			# Search for "tNGS" in the output using grep
			tNGS_processes <- grep(pathcheck, ps_output, value=TRUE)
			tNGS_script <- grep(script, ps_output, value=TRUE)
			
			
			print (paste("tNGS grep = ",tNGS_processes))
			# Check if tNGS_processes is empty
			if ((length(tNGS_processes > 0)) || (length(tNGS_script > 0)))  {
		
				showModal(modalDialog(
				title = "Abort!",
				paste0("Run Name folder already active. Please choose another Run Name."),
				easyClose = TRUE,
				footer = NULL
		  		))    
				whichbutton(!whichbutton())
		
			} else {
		
		
		
			updateButton(session,inputId = "go",label = " Stop Pipeline",icon = icon("stop-circle"),style = "danger") 
			timestamp <<- paste0(rundir,my_run_name,"/timestamp.txt")
			countstamp <<- paste0(rundir,my_run_name,"/fastq_counts.txt")
			loci <<- paste0(rundir,my_run_name,"/Loci_status_main.txt")
			print (paste(timestamp))
			rundir <<- (paste0(rundir,my_run_name))
			if (dir.exists(rundir)) {
				system(paste("rm -r",rundir))
			}
			
			if(samplesheet != "NULL") {
			
				sheet_renamed <<- paste0("sample_sheet_",my_run_name,".txt")
				system(paste0("cp ",samplesheet," /local/tNGS_TB/sample_sheet_tmp/",sheet_renamed))
				#system(paste("cp ",samplesheet,sheet_renamed))
				#system (paste("rm",samplesheet))
				samplesheet <<- sheet_renamed
			}
			# Open the output file in write mode

			print(paste("/local/tNGS_TB/Real-time_wrapper/Amplicon_RT_analyzer_V0.4.4.pl -FASTQ", path ,"-Sheet",samplesheet,"-RUN", my_run_name," -Kit Auto -Flowcell", input$flowcell,"-Workflow", xworkflow,">","/local/tNGS_TB/Rlog.txt"))	
			my_command <<- c("-FASTQ", path ,"-Sheet", samplesheet,"-RUN", my_run_name,"-Kit", "Auto", "-Flowcell", input$flowcell,"-Workflow", xworkflow,">","/local/tNGS_TB/Rlog.txt","&")
			p <<- process$new("/local/tNGS_TB/Real-time_wrapper/Amplicon_RT_analyzer_V0.4.4.pl",c("-FASTQ", path ,"-Sheet", samplesheet,"-RUN", my_run_name,"-Kit", "Auto", "-Flowcell", input$flowcell,"-Workflow", xworkflow,">","/local/tNGS_TB/Rlog.txt","&"),cleanup_tree = FALSE,cleanup = FALSE)
			pid <<- p$get_pid()
			print(pid)
			
			ready_to_start <<- 2			
			whichbutton(!whichbutton())
			data_to_save <<- list(ready_to_start,pid,my_run_name,whichbutton(),path,samplesheet,xworkflow,fn)
			#data_to_save <- list(ready_to_start,pid)

		# Save the list to a file
		saveRDS(data_to_save, shiny_save)

		}
	}
	
	


}
})


observe({
	print (paste("fn: ",fn))
	if (ready_to_start==2) {
			if ((!file.exists(fn))) {
			invalidateLater(1000, session)     			
			}

		
			if ((file.exists(fn))) {			
			removeModal()
			ready_to_start<<-3
		} 

	}
	
}) 













observe ({

		if ((!whichbutton()) && ready_to_start==3)  { ### when stop button is pressed
			#whichbutton(!whichbutton())
			system (paste("rm", shiny_save))
			
			if (pid > 0) {
				system(paste("kill -9 ",pid))
				pid <<- 0
			}
			fn <<- ""
			rundir<<- ""
			ready_to_start <<- 0
			updateButton(session,inputId = "go",label = " Start Pipeline",icon = icon("play-circle"),style = "success") 
				showModal(modalDialog(
				title = "Success!",
				paste0("The pipeline has been successfully terminated.xxxx"),
				easyClose = TRUE,
				footer = NULL
		  ))    
			## stop pipeline at the system level
			session$reload()
			path <- "NULL"
	}


})

observe ({
	if ((whichbutton()) && ready_to_start==3)  {
	print (paste("starting analyses..."))
		
		updateButton(session,inputId = "go",label = " Stop Pipeline",icon = icon("stop-circle"),style = "danger") 
		

		
		
			timestamp <- paste0(rundir,"/timestamp.txt")
			loci <- paste0(rundir,"/Loci_status_main.txt")
			countstamp <- paste0(rundir,"/fastq_counts.txt")
			
			print (paste("loci = ",loci))
			
			
			data_timestamp <- reactiveFileReader(
				intervalMillis = 1000,
				session = NULL,
				filePath = timestamp,
				readFunc = function(filePath) { 
				  read.csv(filePath,header = TRUE, stringsAsFactors=FALSE)
				}
	 
			  ) 
			  loci_data_manipulated <- reactiveFileReader(
				intervalMillis = 1000,
				session = NULL,
				filePath = loci,
				readFunc = function(filePath) { 
				  read.csv(filePath,header = TRUE, stringsAsFactors=FALSE)
				}
			  )  
			
			removeModal()
			data_manipulated <- reactiveFileReader(
			intervalMillis = 1000,
			session = NULL,
			filePath = fn,
			readFunc = function(filePath) { 
			  read.csv(filePath,header = TRUE, stringsAsFactors=FALSE)
			}
		  )

  data_countstamp <- reactiveFileReader(
    intervalMillis = 1500,
    session = NULL,
    filePath = countstamp,
    readFunc = function(filePath) { 
      read.csv(filePath,header = TRUE, stringsAsFactors=TRUE,fill = TRUE)
    }) 	  




			output$stamp <- renderTable({
				data_timestamp()
			})
			
			output$fastq_count <- renderTable({
				data_countstamp()
			})
			
			
			
			output$table <- renderTable({
				xdata <- subset(loci_data_manipulated(),
     				sample %in% input$sample)
     				xdata[,3] <- as.integer(xdata[,3])
     				data <- xdata[,2:4]
			})
			sample_original <- read.csv(fn, header = TRUE, stringsAsFactors=FALSE)
			sample_list <- unique(sample_original$sample)
			updateSelectInput(session, inputId = "sample", choices = sample_list, selected = sample_list[1])


			### Original target plot     
		   # Replace the `renderPlot()` with the plotly version
		  output$plot <- renderPlotly({
			# Convert the existing ggplot2 to a plotly plot
			ggplotly({      
			  data <- subset(data_manipulated(),
							 sample %in% input$sample )     

			  p <- ggplot(data, aes(x = position, y = depth, group = sample, colour = gene)) +
				geom_line(linewidth=.3) +
				facet_wrap( ~  gene, ncol=4, nrow=4, scales = "free", shrink =  FALSE) +
				theme_few() +
				theme(legend.position="none",
					  strip.text = element_text(face="bold", size = 14),
					  plot.title = element_text(face = "bold"),
							panel.spacing.y = unit(-0.4, "lines"),
								panel.spacing.x = unit(-0.4, "lines")) + 
				scale_color_tableau("Tableau 20") +
				ylab("") +
				xlab("") +
				ggtitle(paste('Sample ',input$sample, sep='')) 
			
			}) %>% config(p, displaylogo = FALSE)       
		  })
		} 

})



observeEvent(input$markdown_display, {
	
			report <- paste0(rundir)
			filename <- paste0("my_pdf_resource/","/",input$sample,"_Report.pdf")

			addResourcePath(prefix = "my_pdf_resource", directoryPath = report)

			filecheck <- paste0(report,"/",input$sample,"_Report.pdf")
			print (paste(filecheck))
			if(file.exists((filecheck))) {			
				showModal(modalDialog(size="l",renderUI({
				tags$iframe(style="height:650px; width:100%", src = filename)}),
				easyClose = TRUE))
			}
	})


## start/stop button actions

##### Start Button blocks ######
observeEvent(input$go, {
	if (whichbutton()) {
   		showModal(modalDialog(
			title = "Retrieving data file",
			h3("Please wait for file to be generated!"),
			easyClose = FALSE,
			footer = tagList(
			  actionButton("cancel", "Cancel"))))
	}
	whichbutton(!whichbutton())  
})

### Cancel button actions #####
observeEvent(input$cancel, {
	whichbutton(!whichbutton())
	cancelbutton(!cancelbutton())
	system (paste("rm", shiny_save))
				fn <<- ""
			rundir<<- ""
	if (pid > 0) {
		system(paste("kill -9 ",pid))
		pid <<- 0
	}
	ready_to_start <<- 0
	updateButton(session,inputId = "go",label = " Start Pipeline",icon = icon("play-circle"),style = "success")
	removeModal()
	showModal(modalDialog(
			title = "Success!",
			paste0("The pipeline has been successfully terminated."),
			easyClose = TRUE,
			footer = NULL
	  ))    
	#session$reload()
	path <- "NULL"
	
})


}
shinyApp(ui, server)