if(.Platform$OS.type=="windows") invisible(Sys.setlocale("LC_CTYPE","English_United States.utf8"))
# Base-R independent source reader/enumerator. No case/model/prior-result inputs.
args<-commandArgs(FALSE);ff<-sub("^--file=","",args[grepl("^--file=",args)]);out<-if(length(ff))dirname(normalizePath(ff))else getwd();d<-file.path(out,"econ11-sources");a<-file.path(dirname(dirname(out)),"work","textbook-rewrite-2026","source-audit-econ11")
m<-numeric();checks<-0;inputMode<-character();put<-function(k,v){m[k]<<-as.numeric(v)}
frac<-function(s){x<-strsplit(as.character(s),"/",fixed=TRUE)[[1]];if(length(x)==2)as.numeric(x[1])/as.numeric(x[2])else as.numeric(x)}
getcsv<-function(n)read.csv(file.path(d,n),colClasses="character",check.names=FALSE,stringsAsFactors=FALSE,na.strings=NULL)
pdf<-function(n){p<-file.path(a,n);if(file.exists(p)&&nzchar(Sys.which("pdftotext"))){inputMode[n]<<-"original PDF via independent pdftotext call";return(system2("pdftotext",c("-layout",shQuote(p),"-"),stdout=TRUE))};inputMode[n]<<-"selected factual CSV fallback; original unavailable";NULL}
cou<-getcsv("actual-2013-UK-auction-rounded-official-report.csv");z<-pdf("NAO-4g-auction-summary-2014.pdf")
if(!is.null(z)){rx<-"^[[:space:]]*(EE|Niche \\(BT\\) \\(new entrant\\)|O2|Three|Vodafone)[[:space:]]+([0-9]+)[[:space:]]+([0-9]+)[[:space:]]+([0-9]+)[[:space:]]*$";zz<-regmatches(z,regexec(rx,z));zz<-zz[lengths(zz)>0];stopifnot(length(zz)==5);for(i in 1:5){obs<-as.character(unlist(cou[i,c("winner_label","reported_800MHz_share_percent","reported_2_6GHz_share_percent","reported_price_million_GBP")],use.names=FALSE));stopifnot(identical(obs,zz[[i]][2:5]));checks<-checks+4}}
for(i in 1:5){key<-strsplit(cou$winner_label[i]," ",fixed=TRUE)[[1]][1];for(col in c("reported_800MHz_share_percent","reported_2_6GHz_share_percent","reported_price_million_GBP"))put(paste0("country_",key,"_",col),cou[i,col])}
put("country_total_million_GBP",sum(as.numeric(cou$reported_price_million_GBP)));put("country_800MHz_total_percent",sum(as.numeric(cou$reported_800MHz_share_percent)));put("country_2_6GHz_total_percent",sum(as.numeric(cou$reported_2_6GHz_share_percent)))
rounds<-getcsv("actual-2022-final-shootout-paired-rounds.csv");shots<-getcsv("actual-2022-final-eight-shootout-attempts.csv");tot<-getcsv("actual-2022-final-match-versus-shootout.csv");z<-pdf("FIFA-final2022-match-report.pdf")
if(!is.null(z)){start<-grep("PENALTY SHOOT-OUT",z,fixed=TRUE)[1];end<-grep("VAR",z,fixed=TRUE);end<-end[end>start][1];b<-z[seq.int(start+1,end-1)];rx<-"^[[:space:]]*([A-Z ]+[a-z][A-Za-z ]*)[[:space:]]+\\[([0-9]+)\\][[:space:]]+([0-9]+)[[:space:]]*-[[:space:]]*([0-9]+)[[:space:]]+([A-Z ]+[a-z][A-Za-z ]*)[[:space:]]+\\[([0-9]+)\\][[:space:]]*$";zz<-regmatches(b,regexec(rx,b));zz<-zz[lengths(zz)>0];stopifnot(length(zz)==4);prev<-c(0,0)
 for(i in 1:4){v<-trimws(zz[[i]][-1]);stopifnot(identical(as.character(rounds[i,c("argentina_name","argentina_shirt","argentina_cumulative","france_cumulative","france_name","france_shirt")]),v));checks<-checks+6;cc<-as.numeric(v[3:4]);for(j in 1:2){k<-2*(i-1)+j;stopifnot(as.numeric(shots$scored[k])==cc[j]-prev[j]);checks<-checks+1};prev<-cc}
 rx2<-"([0-9]+)[[:space:]]*/[[:space:]]*([0-9]+)[[:space:]]+Penalties \\(total/scored\\)[[:space:]]+([0-9]+)[[:space:]]*/[[:space:]]*([0-9]+)";vv<-regmatches(z,regexec(rx2,z));vv<-vv[lengths(vv)>0][[1]][-1];stopifnot(identical(c(tot$in_match_penalties[1],tot$in_match_scored[1],tot$in_match_penalties[2],tot$in_match_scored[2]),vv));checks<-checks+4}
for(i in seq_len(nrow(shots)))put(paste0("person_attempt_",i,"_scored"),shots$scored[i])
for(t in c("ARG","FRA")){ss<-shots[shots$team==t,];put(paste0("person_",t,"_attempts"),nrow(ss));put(paste0("person_",t,"_goals"),sum(as.numeric(ss$scored)));put(paste0("person_",t,"_frequency"),mean(as.numeric(ss$scored)))}
for(i in 1:2){put(paste0("person_",tot$team[i],"_in_match_attempts"),tot$in_match_penalties[i]);put(paste0("person_",tot$team[i],"_in_match_goals"),tot$in_match_scored[i])};put("person_all_attempts",nrow(shots));put("person_all_goals",sum(as.numeric(shots$scored)));put("person_all_frequency",mean(as.numeric(shots$scored)))
# Original game assumptions, coded independently in base R.
pay<-function(a,b)if(a>=b)c(b,12-b,0)else c(a,0,8-a)
pr<-getcsv("hypothetical-single-item-second-price-profiles.csv");nash<-0
for(i in seq_len(nrow(pr))){x<-as.numeric(pr$bid_A[i]);y<-as.numeric(pr$bid_B[i]);v<-pay(x,y);ba<-max(sapply(0:12,function(k)pay(k,y)[2]));bb<-max(sapply(0:12,function(k)pay(x,k)[3]));res<-c(price=v[1],utility_A=v[2],utility_B=v[3],A_is_best_response=as.numeric(v[2]==ba),B_is_best_response=as.numeric(v[3]==bb),pure_Nash=as.numeric(v[2]==ba&&v[3]==bb));for(k in names(res)){stopifnot(as.numeric(pr[i,k])==res[k]);checks<-checks+1;put(paste0("auction_",x,"_",y,"_",k),res[k])};nash<-nash+res["pure_Nash"]}
put("auction_pure_Nash_count",nash);put("auction_truthful_A_payoff",pay(12,8)[2]);put("auction_truthful_B_payoff",pay(12,8)[3]);put("auction_truthful_A_weak_dominance",all(sapply(0:12,function(b)all(sapply(0:12,function(a)pay(12,b)[2]>=pay(a,b)[2])))));put("auction_truthful_B_weak_dominance",all(sapply(0:12,function(a)all(sapply(0:12,function(b)pay(a,8)[3]>=pay(a,b)[3])))))
P<-matrix(c(.3,.9,.8,.4),nrow=2,byrow=TRUE);mp<-getcsv("hypothetical-kicker-keeper-payoffs.csv");for(i in 1:4){r<-match(mp$kicker_action[i],c("L","R"));c<-match(mp$keeper_action[i],c("L","R"));stopifnot(abs(frac(mp$assumed_goal_probability[i])-P[r,c])<1e-14,abs(frac(mp$assumed_keeper_payoff[i])-(1-P[r,c]))<1e-14);checks<-checks+2}
p<-solve(matrix(c(P[1,1]-P[2,1]-P[1,2]+P[2,2]),1),P[2,2]-P[2,1])[1];q<-(P[2,2]-P[1,2])/(P[1,1]-P[1,2]-P[2,1]+P[2,2]);put("kick_mixed_pL",p);put("kick_mixed_qL",q);put("kick_mixed_value",p*P[1,1]+(1-p)*P[2,1])
mix<-getcsv("hypothetical-kicker-mixing-profile.csv");for(i in seq_len(nrow(mix))){p<-frac(mix$kicker_L_probability[i]);left<-p*P[1,1]+(1-p)*P[2,1];right<-p*P[1,2]+(1-p)*P[2,2];v<-c(goal_if_keeper_L=left,goal_if_keeper_R=right,goal_against_best_responding_keeper=min(left,right));for(k in names(v)){stopifnot(abs(frac(mix[i,k])-v[k])<1e-13);checks<-checks+1;put(paste0("kick_p",mix$kicker_L_probability[i],"_",k),v[k])}}
E<-matrix(c(0,0,1,-1),2,byrow=TRUE);I<-matrix(c(4,4,2,1),2,byrow=TRUE);en<-getcsv("hypothetical-entry-normal-form.csv")
for(i in seq_len(nrow(en))){r<-match(en$entrant_plan[i],c("out","in"));c<-match(en$incumbent_contingent_plan[i],c("accommodate_if_entry","fight_if_entry"));res<-c(assumed_entrant_payoff=E[r,c],assumed_incumbent_payoff=I[r,c],entrant_best_response=as.numeric(E[r,c]==max(E[,c])),incumbent_best_response=as.numeric(I[r,c]==max(I[r,])),pure_Nash=as.numeric(E[r,c]==max(E[,c])&&I[r,c]==max(I[r,])),subgame_perfect=as.numeric(r==2&&c==1));for(k in names(res)){stopifnot(frac(en[i,k])==res[k]);checks<-checks+1;put(paste0("entry_",r-1,"_",c-1,"_",k),res[k])}}
rr<-getcsv("hypothetical-entry-response-profile.csv");for(i in seq_len(nrow(rr))){q<-frac(rr$incumbent_accommodate_probability[i]);u<-q*E[2,1]+(1-q)*E[2,2];stopifnot(abs(frac(rr$entrant_expected_payoff_if_in[i])-u)<1e-13);checks<-checks+1;put(paste0("entry_q",rr$incumbent_accommodate_probability[i],"_in_payoff"),u)}
ss<-getcsv("hypothetical-entry-sunk-constant-invariance.csv");for(i in seq_len(nrow(ss))){r<-match(ss$entrant_plan[i],c("out","in"));c<-match(ss$incumbent_contingent_plan[i],c("accommodate_if_entry","fight_if_entry"));s<-frac(ss$chosen_common_sunk_constant[i]);v<-I[r,c]-s;stopifnot(frac(ss$incumbent_payoff_net_of_chosen_constant[i])==v);checks<-checks+1;put(paste0("entry_sunk_",s,"_",r-1,"_",c-1),v)}
put("company_actual_Vodafone_reported_million_GBP",cou$reported_price_million_GBP[cou$winner_label=="Vodafone"])
write.csv(data.frame(metric=names(m),value=unname(m)),file.path(out,"econ11-r-results.csv"),row.names=FALSE)
cat("ECON11 R:",length(m),"metrics;",checks,"selected/source comparisons\n");cat(paste(names(inputMode),inputMode,sep=": "),sep="\n")
