I have an android app I'd like to edit. It currently has one page. It can set times to send text messages between. The way it works is you load a csv file with phone numbers and set times to send between. You set a delay so the messages don't get sent all at once, and once you press start sending, it will send messages until it runs out. I can provide the current code for reference. I'd like to make a few edits. Can you help me? 

Here is the current code in MainActivity: package com.example.smsautosender

import android.Manifest
import android.app.TimePickerDialog
import android.content.Intent
import android.content.pm.PackageManager
import android.net.Uri
import android.os.Bundle
import android.os.Handler
import android.os.Looper
import android.provider.OpenableColumns
import android.telephony.SmsManager
import android.util.Log
import android.widget.Button
import android.widget.EditText
import android.widget.ProgressBar
import android.widget.TextView
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import java.io.BufferedReader
import java.io.InputStreamReader
import java.text.SimpleDateFormat
import java.util.*

class MainActivity : AppCompatActivity() {
    private var isSending = false
    private val messagesToSend = mutableListOf<Pair<String, String>>()
    private val handler = Handler(Looper.getMainLooper())
    private var messagesSentCount = 0
    private lateinit var messageCount: TextView
    private lateinit var startButton: Button
    private lateinit var progressBar: ProgressBar
    private lateinit var csvFileName: TextView
    private var startTime = ""
    private var endTime = ""
    private var delayMinutes: Long = 0L

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        messageCount = findViewById(R.id.messageCount)
        startButton = findViewById(R.id.startButton)
        progressBar = findViewById(R.id.progressBar)
        csvFileName = findViewById(R.id.csvFileName)

        val loadCsvButton = findViewById<Button>(R.id.loadCsvButton)
        val stopButton = findViewById<Button>(R.id.stopButton)
        val startTimeButton = findViewById<Button>(R.id.startTimeButton)
        val endTimeButton = findViewById<Button>(R.id.endTimeButton)
        val delayMinutesInput = findViewById<EditText>(R.id.delayMinutes)

        loadCsvButton.setOnClickListener { openFilePicker() }
        startTimeButton.setOnClickListener { showTimePickerDialog("start") }
        endTimeButton.setOnClickListener { showTimePickerDialog("end") }

        startButton.setOnClickListener {
            if (messagesToSend.isEmpty()) {
                Toast.makeText(this, "No messages loaded.", Toast.LENGTH_SHORT).show()
                return@setOnClickListener
            }
            delayMinutes = delayMinutesInput.text.toString().toLongOrNull() ?: 10L

            if (validateInputs(delayMinutes)) {
                progressBar.max = messagesToSend.size
                updateUIState()
                startSendingMessages(startTime, endTime)
            } else {
                Toast.makeText(this, "Please select valid times and delay.", Toast.LENGTH_SHORT).show()
            }
        }

        stopButton.setOnClickListener {
            stopSendingMessages()
            messagesSentCount = 0
            messageCount.text = "Messages Sent: $messagesSentCount/${messagesToSend.size}"
            startButton.text = "Start Sending SMS"
            progressBar.progress = messagesSentCount
            progressBar.visibility = ProgressBar.INVISIBLE
        }
    }

    private fun showTimePickerDialog(type: String) {
        val calendar = Calendar.getInstance()
        val hour = calendar.get(Calendar.HOUR)
        val minute = calendar.get(Calendar.MINUTE)
        val is24Hour = false

        val timePickerDialog = TimePickerDialog(this, { _, selectedHour, selectedMinute ->
            val selectedAMPM = if (selectedHour >= 12) "PM" else "AM"
            val hourOfDay = if (selectedHour > 12) selectedHour - 12 else if (selectedHour == 0) 12 else selectedHour
            val selectedTime = String.format("%02d:%02d %s", hourOfDay, selectedMinute, selectedAMPM)

            if (type == "start") {
                startTime = selectedTime
                findViewById<Button>(R.id.startTimeButton).text = "Start Time: $selectedTime"
            } else {
                endTime = selectedTime
                findViewById<Button>(R.id.endTimeButton).text = "End Time: $selectedTime"
            }
        }, hour, minute, is24Hour)

        timePickerDialog.show()
    }

    private fun openFilePicker() {
        val intent = Intent(Intent.ACTION_OPEN_DOCUMENT).apply {
            addCategory(Intent.CATEGORY_OPENABLE)
            type = "*/*"
            putExtra(Intent.EXTRA_MIME_TYPES, arrayOf("text/csv", "text/comma-separated-values", "application/vnd.ms-excel"))
        }
        startActivityForResult(intent, REQUEST_CODE_OPEN_CSV)
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if (requestCode == REQUEST_CODE_OPEN_CSV && resultCode == RESULT_OK) {
            data?.data?.also { uri ->
                displayFileName(uri)
                handleFile(uri)
            }
        }
    }

    private fun displayFileName(uri: Uri) {
        var fileName = "Unknown"
        contentResolver.query(uri, null, null, null, null)?.use { cursor ->
            if (cursor.moveToFirst()) {
                val nameIndex = cursor.getColumnIndex(OpenableColumns.DISPLAY_NAME)
                if (nameIndex != -1) {
                    fileName = cursor.getString(nameIndex)
                }
            }
        }
        csvFileName.text = "Selected File: $fileName"
    }

    private fun handleFile(uri: Uri) {
        messagesToSend.clear()
        contentResolver.openInputStream(uri)?.use { inputStream ->
            val reader = BufferedReader(InputStreamReader(inputStream))
            reader.lineSequence().forEach { line ->
                val columns = line.split(",")
                val phoneNumber = columns.getOrNull(0)?.trim() ?: ""
                val message = columns.getOrNull(1)?.trim() ?: ""
                if (phoneNumber.isNotEmpty() && message.isNotEmpty()) {
                    messagesToSend.add(phoneNumber to message)
                }
            }
            Toast.makeText(this, "${messagesToSend.size} messages loaded from CSV.", Toast.LENGTH_SHORT).show()
        }
    }

    private fun startSendingMessages(startTimeStr: String, endTimeStr: String) {
        checkAndRequestPermissions()
        if (checkSelfPermission(Manifest.permission.SEND_SMS) == PackageManager.PERMISSION_GRANTED) {
            isSending = true
            Log.d("StartSending", "Scheduled Start Time: $startTimeStr, End Time: $endTimeStr")

            val timeFormat = SimpleDateFormat("hh:mm a", Locale.getDefault())

            try {
                val startTimeParsed = timeFormat.parse(startTimeStr) ?: throw Exception("Invalid start time format")
                val endTimeParsed = timeFormat.parse(endTimeStr) ?: throw Exception("Invalid end time format")

                val startHour = startTimeParsed.hours
                val startMinute = startTimeParsed.minutes
                val endHour = endTimeParsed.hours
                val endMinute = endTimeParsed.minutes

                var lastSentTimeInMillis = 0L

                val handlerTask = object : Runnable {
                    override fun run() {
                        val now = Calendar.getInstance()
                        val currentHour = now.get(Calendar.HOUR_OF_DAY)
                        val currentMinute = now.get(Calendar.MINUTE)
                        val currentTimeInMillis = now.timeInMillis

                        Log.d("TimeCheck", "Current time: $currentHour:$currentMinute, Start: $startHour:$startMinute, End: $endHour:$endMinute")

                        if (isSending) {
                            if (
                                (currentHour > startHour || (currentHour == startHour && currentMinute >= startMinute)) &&
                                (currentHour < endHour || (currentHour == endHour && currentMinute < endMinute))
                            ) {
                                startButton.text = "Sending in Progress"
                                if (messagesSentCount < messagesToSend.size) {
                                    if (currentTimeInMillis - lastSentTimeInMillis >= delayMinutes * 60 * 1000) {
                                        val (phoneNumber, message) = messagesToSend[messagesSentCount]
                                        sendSMS(phoneNumber, message)
                                        Log.d("SendingMessage", "Sent to $phoneNumber")
                                        messagesSentCount++
                                        updateUIState()
                                        lastSentTimeInMillis = currentTimeInMillis  // Update the last sent time
                                    }
                                } else {
                                    Log.d("Completion", "All messages sent for today.")
                                    startButton.text = "ALL DONE!"
                                    isSending = false
                                }
                            } else {
                                startButton.text = "Waiting to Send"
                                Log.d("StateCheck", "Waiting to send messages...")
                            }

                            handler.postDelayed(this, 60 * 1000) // Check every minute
                        }
                    }
                }
                handler.post(handlerTask)

            } catch (e: Exception) {
                Toast.makeText(this, "Error in time setup: ${e.message}", Toast.LENGTH_SHORT).show()
                Log.e("TimeParseError", "Error parsing time", e)
            }
        }
    }

    private fun updateUIState() {
        messageCount.text = "Messages Sent: $messagesSentCount/${messagesToSend.size}"
        progressBar.progress = messagesSentCount
        if (messagesSentCount >= messagesToSend.size) {
            startButton.text = "ALL DONE!"
            progressBar.visibility = ProgressBar.INVISIBLE
        }
    }

    private fun stopSendingMessages() {
        isSending = false
        handler.removeCallbacksAndMessages(null)
        Toast.makeText(this, "Message sending stopped.", Toast.LENGTH_SHORT).show()
    }

    private fun sendSMS(phoneNumber: String, message: String) {
        try {
            val smsManager: SmsManager = SmsManager.getDefault()
            smsManager.sendTextMessage(phoneNumber, null, message, null, null)
            Toast.makeText(this, "SMS sent successfully to $phoneNumber!", Toast.LENGTH_SHORT).show()
        } catch (e: Exception) {
            Toast.makeText(this, "SMS sending failed: ${e.message}", Toast.LENGTH_LONG).show()
            e.printStackTrace()
        }
    }

    private fun validateInputs(delay: Long): Boolean {
        return try {
            SimpleDateFormat("hh:mm a", Locale.getDefault()).parse(startTime) != null &&
                    SimpleDateFormat("hh:mm a", Locale.getDefault()).parse(endTime) != null &&
                    delay > 0
        } catch (e: Exception) {
            false
        }
    }

    private fun checkAndRequestPermissions() {
        if (checkSelfPermission(Manifest.permission.SEND_SMS) != PackageManager.PERMISSION_GRANTED) {
            requestPermissions(arrayOf(Manifest.permission.SEND_SMS), REQUEST_SMS_PERMISSION)
        }
    }

    override fun onRequestPermissionsResult(requestCode: Int, permissions: Array<String>, grantResults: IntArray) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults)
        if (requestCode == REQUEST_SMS_PERMISSION) {
            if (grantResults.isNotEmpty() && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                Toast.makeText(this, "SMS permission granted.", Toast.LENGTH_SHORT).show()
            } else {
                Toast.makeText(this, "SMS permission denied.", Toast.LENGTH_SHORT).show()
            }
        }
    }

    companion object {
        const val REQUEST_CODE_OPEN_CSV = 1
        const val REQUEST_SMS_PERMISSION = 2
    }
}