if(.Platform$OS.type=="windows") invisible(Sys.setlocale("LC_CTYPE","English_United States.utf8"))
# Independently read official originals or explicitly available public selections.
args<-commandArgs(FALSE);f<-sub("^--file=","",args[grepl("^--file=",args)]);o<-if(length(f))dirname(normalizePath(f))else getwd();d<-file.path(o,"econ14-sources");w<-file.path(dirname(dirname(o)),"work","textbook-rewrite-2026");a<-file.path(w,"source-audit-econ14");m<-numeric();checks<-0
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)};near<-function(x,y)all(abs(x-y)<=1e-10*pmax(1,abs(x),abs(y)));getcsv<-function(n)read.csv(file.path(d,n),colClasses="character",check.names=FALSE,stringsAsFactors=FALSE,na.strings=NULL)
pdf<-function(name){p<-file.path(a,name);if(!file.exists(p)||!nzchar(Sys.which("pdftotext")))return(NULL);tmp<-tempfile(fileext=".txt");status<-system2("pdftotext",c("-layout",shQuote(p),shQuote(tmp)));stopifnot(status==0);text<-readChar(tmp,file.info(tmp)$size,useBytes=TRUE);unlink(tmp);strsplit(text,"\f",fixed=TRUE)[[1]]}
lf<-getcsv("actual-Canada-LFS-November-December2024-historical-release.csv");pages<-pdf("StatisticsCanada-LFS-December2024-release.pdf");periods<-c("November2024","December2024");ls<-matrix(NA_real_,9,2,dimnames=list(lf$measure,periods))
if(!is.null(pages)){
 block<-strsplit(strsplit(pages[13],"15 years and over, both sexes",fixed=TRUE)[[1]][2],"15 to 24 years, both sexes",fixed=TRUE)[[1]][1];lines<-strsplit(block,"\n",fixed=TRUE)[[1]]
 for(i in seq_len(nrow(lf))){line<-lines[startsWith(trimws(lines),paste0(lf$source_label[i]," "))][1];v<-regmatches(line,gregexpr("-?[0-9][0-9,]*\\.[0-9]|\\.\\.\\.",line,perl=TRUE))[[1]];ls[i,]<-as.numeric(gsub(",","",v[1:2],fixed=TRUE));stopifnot(all(ls[i,]==as.numeric(lf[i,periods])));checks<-checks+2}
}else{for(t in periods)ls[,t]<-as.numeric(lf[[t]]);message("LFS public-selection fallback")}
for(k in lf$measure)for(t in periods)put(paste0("country_LFS_",k,"_",t),ls[k,t])
ld<-getcsv("derived-Canada-LFS-denominators-and-published-rounding.csv")
for(i in seq_len(nrow(ld))){t<-ld$period[i];pop<-ls["population",t];lab<-ls["labour_force",t];emp<-ls["employment",t];u<-ls["unemployment",t];stopifnot(near(emp+u,lab));vals<-c(population_thousand=pop,labour_force_thousand=lab,employed_thousand=emp,unemployed_thousand=u,derived_not_in_labour_force_thousand=pop-lab,unemployment_rate_from_rounded_levels_percent=100*u/lab,participation_rate_from_rounded_levels_percent=100*lab/pop,employment_rate_from_rounded_levels_percent=100*emp/pop,full_plus_part_minus_employment_rounding_thousand=ls["full_time_employment",t]+ls["part_time_employment",t]-emp);for(k in names(vals)){stopifnot(near(frac(ld[[k]][i]),vals[k]));checks<-checks+1;put(paste0("country_LFS_",t,"_",k),vals[k])}}
cp<-getcsv("actual-Canada-CPI-major-components-NSA-versus-SA.csv");pages<-pdf("StatisticsCanada-CPI-December2024-release.pdf");valueFields<-c("basket_importance_percent","December2023_index","October2024_index","November2024_index","December2024_index","published_month_change_percent","published_year_change_percent");cv<-list()
for(i in seq_len(nrow(cp))){key<-cp$category[i];adj<-cp$adjustment[i];values<-setNames(vapply(valueFields,function(k)if(nzchar(cp[[k]][i]))as.numeric(cp[[k]][i])else NA_real_,numeric(1)),valueFields)
 if(!is.null(pages)){
  page<-pages[if(adj=="NSA")7 else 8];block<-paste0("All-items",strsplit(strsplit(page,"All-items",fixed=TRUE)[[1]][2],"Special aggregates",fixed=TRUE)[[1]][1]);lines<-strsplit(block,"\n",fixed=TRUE)[[1]];label<-if(key=="alcohol_tobacco_cannabis")"recreational cannabis"else cp$source_label[i];line<-lines[startsWith(trimws(lines),paste0(label," "))][1];nums<-as.numeric(regmatches(line,gregexpr("-?[0-9]+\\.[0-9]+",line,perl=TRUE))[[1]])
  names<-if(adj=="NSA")c("basket_importance_percent","December2023_index","November2024_index","December2024_index","published_month_change_percent","published_year_change_percent")else c("October2024_index","November2024_index","December2024_index","unused","published_month_change_percent");stopifnot(length(nums)==length(names));for(j in seq_along(nums))if(names[j]!="unused"){stopifnot(values[names[j]]==nums[j]);values[names[j]]<-nums[j];checks<-checks+1}
 }
 cv[[paste(key,adj)]]<-values;for(k in valueFields)if(!is.na(values[k]))put(paste0("country_CPI_",key,"_",adj,"_",k),values[k])
}
cd<-getcsv("derived-Canada-CPI-period-and-adjustment-comparisons.csv")
for(i in seq_len(nrow(cd))){key<-cd$category[i];adj<-cd$adjustment[i];v<-cv[[paste(key,adj)]];month<-100*(v["December2024_index"]/v["November2024_index"]-1);stopifnot(near(frac(cd$month_change_from_rounded_levels_percent[i]),month));checks<-checks+1;put(paste0("country_CPI_",key,"_",adj,"_derived_month_percent"),month);if(!is.na(v["December2023_index"])){year<-100*(v["December2024_index"]/v["December2023_index"]-1);stopifnot(near(frac(cd$year_change_from_rounded_levels_percent[i]),year));checks<-checks+1;put(paste0("country_CPI_",key,"_",adj,"_derived_year_percent"),year)}}
s<-getcsv("actual9876-ACS2024-Delaware-employment-status-fields.csv");z<-file.path(w,"source-audit-econ13","Census-ACS2024-1year-Delaware-person.zip");fields<-c("SERIALNO","SPORDER","STATE","AGEP","ESR","PWGTP")
if(file.exists(z)){con<-unz(z,"psam_p10.csv",open="r");rows<-read.csv(con,colClasses="character",check.names=FALSE,stringsAsFactors=FALSE,na.strings=NULL);close(con);stopifnot(nrow(rows)==nrow(s),identical(s$source_row_id,as.character(seq_len(nrow(rows)))));for(k in fields){stopifnot(identical(rows[[k]],s[[k]]));checks<-checks+nrow(rows)}}else{rows<-s;message("ACS public-selection fallback")}
codes<-c("","1","2","3","4","5","6");n<-setNames(vapply(codes,function(k)sum(rows$ESR==k),numeric(1)),codes);wt<-setNames(vapply(codes,function(k)sum(as.numeric(rows$PWGTP[rows$ESR==k])),numeric(1)),codes);st<-getcsv("derived-ACS-employment-status-counts-and-person-weights.csv")
for(i in seq_along(codes)){k<-codes[i];stopifnot(as.numeric(st$source_rows[i])==n[i],as.numeric(st$person_weight_sum[i])==wt[i]);checks<-checks+2;put(paste0("person_status_",i-1,"_rows"),n[i]);put(paste0("person_status_",i-1,"_weights"),wt[i])}
empN<-sum(n[2:3]);unN<-n[4];labN<-empN+unN;civN<-labN+n[7];emp<-sum(wt[2:3]);u<-wt[4];lab<-emp+u;civilian<-lab+wt[7]
# unname prevents source code names becoming suffixes of the public metrics.
v<-c(source_rows=nrow(rows),source_age16plus_rows=sum(as.numeric(rows$AGEP)>=16),source_under16_not_applicable_rows=unname(n[1]),source_armed_forces_rows=sum(n[5:6]),civilian_age16plus_source_rows=unname(civN),civilian_employed_source_rows=unname(empN),unemployed_source_rows=unname(unN),civilian_labour_force_source_rows=unname(labN),civilian_not_in_labour_force_source_rows=unname(n[7]),civilian_population_person_weight=unname(civilian),employed_person_weight=unname(emp),unemployed_person_weight=unname(u),labour_force_person_weight=unname(lab),not_in_labour_force_person_weight=unname(wt[7]),weighted_unemployment_fraction=unname(u/lab),weighted_employment_fraction=unname(emp/civilian),weighted_participation_fraction=unname(lab/civilian),unweighted_unemployment_fraction=unname(unN/labN));ss<-getcsv("derived-ACS-civilian16plus-labour-denominators.csv");for(k in names(v)){stopifnot(near(frac(ss[[k]]),v[k]));checks<-checks+1;put(paste0("person_",k),v[k])};stopifnot(all((as.numeric(rows$AGEP)<16)==(rows$ESR=="")))
groups<-getcsv("actual-Southwest2024-active-FTE-composition.csv");stocks<-getcsv("actual-Southwest-employment-stocks-FTE-versus-headcount.csv");file<-file.path(w,"source-audit-econ10","Southwest-2024-official10K.html");active<-as.numeric(stocks$amount[stocks$metric=="active_FTE"&stocks$date=="2024-12-31"]);prior<-as.numeric(stocks$amount[stocks$metric=="active_FTE"&stocks$date=="2023-12-31"]);leave<-as.numeric(stocks$amount[stocks$metric=="on_leave_employees"])
if(file.exists(file)){
 text<-paste(readLines(file,warn=FALSE,encoding="UTF-8"),collapse="\n");text<-gsub("(?si)<(script|style|head)\\b[^>]*>.*?</\\1>"," ",text,perl=TRUE);text<-gsub("<[^>]+>"," ",text);text<-gsub("&nbsp;|&#160;"," ",text);text<-gsub("\\x{00a0}"," ",text,perl=TRUE);text<-gsub("[[:space:]]+"," ",text);parts<-strsplit(text,"As of December 31, 2024, the Company had ",fixed=TRUE)[[1]][-1];start<-Filter(function(x)grepl("^[0-9,]+ active full-time equivalent",x),parts);stopifnot(length(start)==1);block<-strsplit(start[[1]],"Labor Union Activity",fixed=TRUE)[[1]][1]
 extract<-function(pattern,input){a<-regmatches(input,regexec(pattern,input,perl=TRUE))[[1]];stopifnot(length(a)>=2);as.numeric(gsub(",","",a[2],fixed=TRUE))}
 stopifnot(active==extract("^([0-9,]+) active full-time equivalent",block),leave==extract("an additional ([0-9,]+) Employees as of December 31, 2024",block));comparison<-regmatches(text,regexec("Active full-time equivalent Employees ([0-9,]+) ([0-9,]+) \\(3.1\\) %",text,perl=TRUE))[[1]];stopifnot(prior==as.numeric(gsub(",","",comparison[3],fixed=TRUE)))
 labels<-c("air operations","ground operations","Customer Representatives","maintenance and engineering","additional");for(i in seq_len(nrow(groups))){stopifnot(as.numeric(groups$active_FTE[i])==extract(paste0("([0-9,]+) ",labels[i]),block));checks<-checks+1}
}else message("Company public-selection fallback")
for(i in seq_len(nrow(groups)))put(paste0("company_group_",groups$category[i],"_FTE"),groups$active_FTE[i]);for(i in seq_len(nrow(stocks)))put(paste0("company_",stocks$metric[i],"_",stocks$date[i]),stocks$amount[i]);stopifnot(sum(as.numeric(groups$active_FTE))==active)
change<-getcsv("derived-Southwest-active-FTE-year-change.csv");delta<-active-prior;growth<-100*(active/prior-1);stopifnot(delta==as.numeric(change$change_FTE),near(growth,frac(change$change_percent_exact)));put("company_change_FTE",delta);put("company_change_percent_exact",growth)
h<-getcsv("hypothetical-Southwest-equal-FTE-different-headcounts.csv");for(i in seq_len(nrow(h))){pt<-as.numeric(h$assumed_part_time_headcount[i]);ft<-active-pt/2;head<-ft+pt;v<-c(assumed_full_time_headcount=ft,fixed_active_FTE=active,assumed_active_headcount=head,reported_on_leave_headcount=leave,assumed_all_employee_headcount=head+leave);for(k in names(v)){stopifnot(near(frac(h[[k]][i]),v[k]));checks<-checks+1;put(paste0("hypothetical_",i-1,"_",k),v[k])}}
write.csv(data.frame(metric=names(m),value=sprintf("%.17g",m)),file.path(o,"econ14-r-results.csv"),row.names=FALSE,quote=TRUE);cat("ECON14 base-R:",length(m),"metrics;",checks,"checks\n")
