if(.Platform$OS.type=="windows") try(Sys.setlocale("LC_CTYPE","English_United States.UTF-8"),silent=TRUE)
# ECON19 standalone base-R reproduction. All numeric results are binary64
# approximations,compared with separately written Fraction/Decimal80 Python.
# Input: public selected CSVs only. No original ZIP/XML reading is claimed.
args <- commandArgs(trailingOnly=FALSE)
script <- sub('^--file=','',args[grepl('^--file=',args)])[1]
HERE <- dirname(normalizePath(script,winslash='/',mustWork=TRUE))
S <- file.path(HERE,'econ19-sources')
read <- function(name) read.csv(file.path(S,name),colClasses='character',check.names=FALSE,na.strings=NULL,fileEncoding='UTF-8',stringsAsFactors=FALSE)
Q <- function(x) { parts <- strsplit(x,'/',fixed=TRUE)[[1]];if(length(parts)==1)as.numeric(parts[1]) else as.numeric(parts[1])/as.numeric(parts[2]) }
M <- list()
put <- function(key,value) { M[[key]] <<- if(is.null(value))'undefined' else if(value==0)'0' else sprintf('%.17g',value) }
monthly <- read('actual48-US-bread-milk-monthly-price-observations.csv')
people <- read('actual3613-person-raw-wage1976-original-fields.csv')
retail <- read('actual2-first-same-invoice-original8-fields.csv')
stopifnot(nrow(monthly)==48,nrow(people)==3613,nrow(retail)==2)
means <- list()
for(good in c('bread','milk')) {
 rs <- monthly[monthly$good==good,,drop=FALSE]
 stopifnot(nrow(rs)==24)
 for(year in c(2023,2024)) {
  ys <- rs[substr(rs$date,1,4)==as.character(year),,drop=FALSE]
  stopifnot(nrow(ys)==12,identical(ys$date,sprintf('%d-%02d-01',year,1:12)))
  value <- mean(vapply(ys$value_original,Q,numeric(1)))
  means[[paste0(good,year)]] <- value
  put(paste('country',good,year,'mean',sep='.'),value)
 }
 for(i in seq_len(nrow(rs)))put(paste('country',good,rs$date[i],sep='.'),Q(rs$value_original[i]))
}
put('country.originalMonthlyValues',48);put('country.monthsPerSelectedYear',12)
available <- people$raw_wage1976_cents_original!='.'
stopifnot(sum(available)==3017,identical(as.integer(people$source_row),1:3613))
wages <- as.numeric(people$raw_wage1976_cents_original[available])/100
put('person.originalRows',3613);put('person.availableRawWages',sum(available));put('person.missingRawWages',sum(!available))
put('person.meanRawWageUSD1976',mean(wages));put('person.minRawWageUSD1976',min(wages));put('person.maxRawWageUSD1976',max(wages))
firstWage <- as.numeric(people$raw_wage1976_cents_original[1])/100
put('person.firstHourlyWageUSD1976',firstWage);put('person.assumedTwoHourBudget',2*firstWage)
edges <- c(0,5,10,15,20,40,Inf)
for(i in 1:6)put(paste0('person.bin',i-1,'.count'),sum(wages>=edges[i] & wages<edges[i+1]))
stopifnot(identical(retail$InvoiceNo,c('536365','536365')),identical(as.integer(retail$source_row),1:2),identical(as.integer(retail$original_excel_row),2:3))
prices <- vapply(retail$UnitPrice,Q,numeric(1));quant <- vapply(retail$Quantity,Q,numeric(1));amount <- sum(prices*quant)
for(i in 1:2)for(key in c('Quantity','UnitPrice','InvoiceDate'))put(paste0('company.line',i,'.',key),Q(retail[[key]][i]))
put('company.partialTwoLineAmount',amount)
# Source decimal input scale is10000000000000000 at most. For this finite
# integer enumeration use the original decimal digits as strings,not a
# binary64 boundary test. Products of these tiny item counts are compared
# by a base10 digit addition routine,which handles integer lengths exactly.
strip0 <- function(s) { z <- sub('^0+','',s);if(z=='')'0'else z }
addInt <- function(a,b) { aa<-rev(as.integer(strsplit(a,'')[[1]]));bb<-rev(as.integer(strsplit(b,'')[[1]]));n<-max(length(aa),length(bb));length(aa)<-n;length(bb)<-n;aa[is.na(aa)]<-0;bb[is.na(bb)]<-0;out<-integer(n);carry<-0;for(k in seq_len(n)){v<-aa[k]+bb[k]+carry;out[k]<-v%%10;carry<-v%/%10};if(carry>0)out<-c(out,carry);paste(rev(out),collapse='') }
scaleInt <- function(a,n) { out<-'0';if(n>0)for(k in seq_len(n))out<-addInt(out,a);out }
cmpInt <- function(a,b) { a<-strip0(a);b<-strip0(b);if(nchar(a)!=nchar(b))sign(nchar(a)-nchar(b))else if(a==b)0 else if(a>b)1 else -1 }
tokens <- retail$UnitPrice
stopifnot(all(grepl('^[0-9]+(\\.[0-9]+)?$',tokens)))
pieces <- strsplit(tokens,'.',fixed=TRUE)
places <- vapply(pieces,function(x)if(length(x)==2)nchar(x[2])else 0L,integer(1));commonScale<-max(places)
scaled <- vapply(seq_along(pieces),function(i)strip0(paste0(pieces[[i]][1],if(length(pieces[[i]])==2)pieces[[i]][2]else'',paste(rep('0',commonScale-places[i]),collapse=''))),character(1))
pScaled <- scaled[1];qScaled <- scaled[2]
stopifnot(all(quant==as.integer(quant)),all(quant>=0))
budgetScaled<-addInt(scaleInt(pScaled,as.integer(quant[1])),scaleInt(qScaled,as.integer(quant[2])))
count<-0;maximum<-0
for(i in 0:13)for(j in 0:10)if(cmpInt(addInt(scaleInt(pScaled,i),scaleInt(qScaled,j)),budgetScaled)<=0){count<-count+1;maximum<-max(maximum,i*j)}
put('company.integerAffordableBundles',count);put('company.integerProductMaximum',maximum)
anchors <- list(country=list(p=c(means$bread2023,means$milk2023),q=c(means$bread2024,means$milk2024),m=20),person=list(p=c(1,1),q=c(2,1),m=2*firstWage),company=list(p=prices,q=c(prices[1]*1.1,prices[2]),m=amount))
fit <- function(family,p,m) {
 if(family=='product')return(list(u=m*m/(4*prod(p)),x=m/(2*p),dimension=0))
 if(family=='leontief'){u<-m/sum(p);return(list(u=u,x=c(u,u),dimension=0))}
 ratio<-1/p
 if(ratio[1]==ratio[2] && m>0)return(list(u=m*max(ratio),x=NULL,dimension=1))
 list(u=m*max(ratio),x=if(ratio[1]>ratio[2])c(m/p[1],0)else c(0,m/p[2]),dimension=0)
}
profile <- function(kind,family,p,q,m,key) {
 old<-fit(family,p,m);new<-fit(family,q,m)
 put(paste0(key,'.oldUtility'),old$u);put(paste0(key,'.newUtility'),new$u);put(paste0(key,'.oldSetDimension'),old$dimension);put(paste0(key,'.newSetDimension'),new$dimension)
 for(i in 1:2){put(paste0(key,'.oldDemand',i),if(is.null(old$x))NULL else old$x[i]);put(paste0(key,'.newDemand',i),if(is.null(new$x))NULL else new$x[i])}
 if(family=='product'){
  ratio<-prod(q)/prod(p)
  if(ratio==1){cv<-0;ev<-0}else{rr<-sqrt(ratio);cv<-m*(rr-1);ev<-m*(1-1/rr)}
 }else{
  oldcost<-old$u*(if(family=='linear')min(q)else sum(q));newcost<-new$u*(if(family=='linear')min(p)else sum(p));cv<-oldcost-m;ev<-m-newcost
 }
 put(paste0(key,'.CV'),cv);put(paste0(key,'.EV'),ev)
}
for(kind in names(anchors)) {
 a<-anchors[[kind]]
 for(family in c('product','linear','leontief'))profile(kind,family,a$p,a$q,a$m,paste('conditional',kind,family,sep='.'))
 labels<-c('1/2','3/4','1','5/4','3/2');scales<-c(.5,.75,1,1.25,1.5)
 for(i in 1:5)profile(kind,'product',a$p,c(a$p[1]*scales[i],a$p[2]),a$m,paste('sensitivity',kind,labels[i],sep='.'))
}
out<-data.frame(key=names(M),value=unlist(M,use.names=FALSE),stringsAsFactors=FALSE)
write.csv(out,file.path(HERE,'econ19-r-results.csv'),row.names=FALSE,na='undefined',fileEncoding='UTF-8')
cat(sprintf('Base R selected-CSV reproduction: %d metrics; %d undefined;originalZIPnotread\n',nrow(out),sum(out$value=='undefined')))
