# Load dataset for synthetic tests
#
# @param type: "trid" or "clus"
# @param p: number of random variables
# @param n: number of samples
# @param normalize: TRUE or FALSE
load_data <- function(type, p, n, normalize=TRUE){
    start_time <- as.numeric(Sys.time())

    print(sprintf("# Loading Data: type=%s p=%d n=%d", type, p, n))

    folder_base=paste("squic_test_db/n_",n,sep = "")

    if (type == "trid"){

            file <- paste(folder_base, "/Theta_Trid", as.character(as.integer(p)), ".txt", sep = "")
            temp <- read.table(file, sep = " ")
            X_star <- Matrix::sparseMatrix(i = temp[, 1], j = temp[, 2], x = temp[, 3])

            file <- paste(folder_base, "/Y_Trid", as.character(as.integer(p)), ".txt", sep = "")
            data <- read.table(file, sep = " ")

        } else if (type == "clus") {

            file <- paste(folder_base, "/Theta_Clusters", as.character(as.integer(p)), ".txt", sep = "")
            temp <- read.table(file, sep = " ")
            X_star <- Matrix::sparseMatrix(i = temp[, 1], j = temp[, 2], x = temp[, 3])

            file <- paste(folder_base, "/Y_Clusters", as.character(as.integer(p)), ".txt", sep = "")
            data <- read.table(file, sep = " ")

        } else {

        stop("Unknown matrix type.")
        
    }

    finish_time <- as.numeric(Sys.time())
    print(sprintf("# Load Data, Type=%s: time=%f", type, finish_time - start_time))

    if (normalize) {
        output <- list(
            "data"   = t(scale(t(data))),
            "X_star" = X_star,
            "var"    = apply(data, 1, var)
        )
    } else {
        output <- list(
            "data"   = data,
            "X_star" = X_star
        )
    }
    return(output)
}