Modified main R function to deal with disk-write