import kotlinx.cinterop.*
import platform.posix.*

class Loader(path: String) {
    private val inputString = read(path)

    /**
     * Preprocesses the plain source code
     * TODO: Add preprocessor managing imports and comments
     */
    fun preprocess(): String {
        return inputString
    }

    /**
     * Reads a file via the [path] into a string representation
     */
    private fun read(path: String): String {
        setlocale(LC_CTYPE, "en_US.UTF-8")

        val file = fopen(path, "r")
        if (file == null) {
            perror("Couldn't open file: $path")
        }

        memScoped {
            val bufferLength = 64 * 1024
            val buffer = allocArray<ByteVar>(bufferLength)

            var content = ""
            var nextLine = fgets(buffer, bufferLength, file)?.toKString()
            while (nextLine != null) {
                content += nextLine
                nextLine = fgets(buffer, bufferLength, file)?.toKString()
            }
            fclose(file)
            return content
        }
    }
}