
###################################################
## Example: what does binary counting look like? ##
###################################################

for (i in 1:1000){print(intToBits(i)); Sys.sleep(0.25)}

##########################################
## Example of Reading in the MNIST Data ## 
##########################################

imgCon = file("./train-images.idx3-ubyte", "rb")
magicNumber = readBin(imgCon, "int", n = 1, size = 4, endian = "big")
nImg = readBin(imgCon, "int", n = 1, size = 4, endian = "big")
nRow = readBin(imgCon, "int", n = 1, size = 4, endian = "big")
nCol = readBin(imgCon, "int", n = 1, size = 4, endian = "big")


numericData <- readBin(imgCon, "int", n = nRow*nCol, size = 1, endian = "big")
matrixData <- matrix(numericData, nrow = 28, ncol = 28)

imageList <- lapply(1:nImg, function(x){
  matrix(as.numeric(readBin(imgCon, "int", 
                            n = nRow*nCol, 
                            size = 1, 
                            endian = "big")),
         nrow = nRow, ncol = nCol)
})
close(imgCon)


labCon = file("./train-labels.idx1-ubyte", "rb")
magicNumber = readBin(labCon, "int", n = 1, size = 4, endian = "big")
nItems = readBin(labCon, "int", n = 1, size = 4, endian = "big")

imageLabels = sapply(1:nItems, function(x){
  readBin(labCon, "int", n = 1, size = 1, endian = "big", signed = FALSE)
})
close(labCon)

table(imageLabels)
imageList[[1]]

plotMatrix <- function(M){
  image(t(M[nrow(M):1,]))
}
for (i in 1:2){
  plotMatrix(imageList[[i]])
  Sys.sleep(0.25)
}

