#!/bin/bash
#	$Id: mgd77_codes.sh 17328 2016-11-08 20:38:56Z pwessel $
#
#	Convert the trkdas.cod file into two usable files:
#	1. mgd77_codes.h for inclusion by mgd77info.c
#	2. mgd77_codes.txt for inclusion by man page mgd77info.txt

#rm -f trkdas.cod
#curl http://www.ngdc.noaa.gov/mgg/dat/geodas/inventories/trkdas.cod --remote-name

sed -e 's/ *$//g' < trkdas.cod > $$.dat
awk '{if (length($1) == 2) {printf "\t{\"%s\", \"%s\"},\n", $1, substr($0, 6)}}' $$.dat > $$.1
awk 'BEGIN {code = -1; last = "--"}; {if (length($1) > 2) {printf "\t{ %d, \"%s\", \"%s\"},\n", code, $1, substr($0, 6)} else {code++}}' $$.dat > $$.2
awk '{if (length($1) == 2) {printf "(%s) %s,\n", $1, substr($0, 6)}}' $$.dat > $$.4
n_agencies=`cat $$.1 | wc -l | awk '{printf "%d\n", $1}'`
n_vessels=`cat $$.2 | wc -l | awk '{printf "%d\n", $1}'`
awk -F, '{if (NR == "'${n_agencies}'") {printf "%s.\n", $1} else {printf "%s,\n", $1}}' $$.4 > mgd77_codes.txt

YEAR=$(date +%Y)

cat << EOF > mgd77_codes.h
/* \$Id:\$
 *
 * Code automatically generated by mgd77_codes.sh
 * To be included by mgd77info.c
 *
 * Copyright (c) 2005-$YEAR by P. Wessel
 * See README file for copying and redistribution conditions.
 */

#define MGD77_N_AGENCIES ${n_agencies}
#define MGD77_N_VESSELS ${n_vessels}

struct MGD77_AGENCY {
	char code[4];
	char name[80];
};

static struct MGD77_AGENCY MGD77_agency[MGD77_N_AGENCIES] = {
EOF
cat $$.1 >> mgd77_codes.h
cat << EOF >> mgd77_codes.h
};

struct MGD77_VESSEL {
	int agent;
	char code[8];
	char name[80];
};

static struct MGD77_VESSEL MGD77_vessel[MGD77_N_VESSELS] = {
EOF
cat $$.2 >> mgd77_codes.h
echo "};"  >> mgd77_codes.h
rm -f $$.*
