#!/bin/sh

# Known bugs:
#
# Blank line is added after, seen as a function definition, no space
# after *:
#	y = (int) x *y;

trap "rm -f /tmp/$$ /tmp/$$a" 0 1 2 3 15
entab </dev/null >/dev/null
if [ "$?" -ne 0 ]
then	echo "Go to the src/tools/entab directory and do a 'make' and 'make install'." >&2
	echo "This will put the 'entab' command in your path." >&2
	echo "Then run $0 again."
	exit 1
fi
indent -? </dev/null >/dev/null 2>&1
if [ "$?" -ne 1 ]
then	echo "You do not appear to have 'indent' installed on your system." >&2
	exit 1
fi
indent -gnu </dev/null >/dev/null 2>&1
if [ "$?" -eq 0 ]
then	echo "You appear to have GNU indent rather than BSD indent." >&2
	echo "See the pgindent/README file for a description of its problems." >&2
	EXTRA_OPTS="-cdb -bli0 -npcs -cli4 -sc"
else	echo "Hope you installed /src/tools/pgindent/indent.bsd.patch." >&2
	EXTRA_OPTS="-cli1"
fi

for FILE
do
	cat "$FILE" |
# convert // comments to /* */
	sed 's;^\([ 	]*\)//\(.*\)$;\1/* \2 */;g' |
# Avoid bug that converts 'x =- 1' to 'x = -1'
	sed 's;=- ;-= ;g' |
# mark some comments for special treatment later
	sed 's;/\*  *---;/*---X_X;g' |
# workaround for indent bug with 'else' handling
# indent comment so BSD indent will move it
	sed 's;\([} 	]\)else[ 	]*\(/\*.*\)$;\1else\
    \2;g' | 
	detab -t4 -qc |
# work around bug where function that defines no local variables misindents
# switch() case lines and line after #else.  Do not do for struct/enum.
	awk '	BEGIN	{line1 = ""; line2 = ""}
		{
			line2 = $0;
	 		if (NR >= 2)
				print line1;
			if (NR >= 2 &&
			    line2 ~ /^{[ 	]*$/ &&
			    line1 !~ /^struct/ &&
			    line1 !~ /^enum/ &&
			    line1 !~ /^typedef/ &&
			    line1 !~ /^extern[ 	][ 	]*"C"/ &&
			    line1 !~ /=/ &&
			    line1 ~ /\)/)
				print "int	pgindent_func_no_var_fix;";
			line1 = line2;
		}
		END {
			if (NR >= 1)
				print line1;
		}' |
# prevent indenting of code in 'extern "C"' blocks
	awk '	BEGIN	{line1 = ""; line2 = ""; skips = 0}
		{
			line2 = $0;
			if (skips > 0)
				skips--;
			if (line1 ~ /^#ifdef[ 	]*__cplusplus/ &&
			    line2 ~ /^extern[ 	]*"C"[ 	]*$/)
			{
				print line1;
				print line2;
				if (getline && $0 ~ /^{[ 	]*$/)
					print "/* Open extern \"C\" */";
				else	print $0;
				line2 = "";
				skips = 2;
			}
			else if (line1 ~ /^#ifdef[ 	]*__cplusplus/ &&
			    line2 ~ /^}[ 	]*$/)
			{
				print line1;
				print "/* Close extern \"C\" */";
				line2 = "";
				skips = 2;
			}
			else
	 			if (skips == 0 && NR >= 2)
					print line1;
			line1 = line2;
		}
		END {
			if (NR >= 1 && skips <= 1)
				print line1;
		}' |
# protect backslashes in DATA()
	sed 's;^DATA(.*$;/*&*/;' |
# protect wrapping in CATALOG()
	sed 's;^CATALOG(.*$;/*&*/;' >/tmp/$$a

# We get the list of typedef's from /src/tools/find_typedef
	indent -bad -bap -bc -bl -d0 -cdb -nce -nfc1 -di12 -i4 -l79 \
		-lp -nip -npro -bbb $EXTRA_OPTS \
-TAES_KEY \
-TASN1_BIT_STRING \
-TASN1_BMPSTRING \
-TASN1_BOOLEAN \
-TASN1_CTX \
-TASN1_ENCODING \
-TASN1_ENUMERATED \
-TASN1_GENERALIZEDTIME \
-TASN1_GENERALSTRING \
-TASN1_HEADER \
-TASN1_IA5STRING \
-TASN1_INTEGER \
-TASN1_ITEM \
-TASN1_ITEM_EXP \
-TASN1_METHOD \
-TASN1_NULL \
-TASN1_OBJECT \
-TASN1_OCTET_STRING \
-TASN1_PRINTABLESTRING \
-TASN1_STRING \
-TASN1_STRING_TABLE \
-TASN1_T61STRING \
-TASN1_TEMPLATE \
-TASN1_TIME \
-TASN1_TLC \
-TASN1_TYPE \
-TASN1_UNIVERSALSTRING \
-TASN1_UTCTIME \
-TASN1_UTF8STRING \
-TASN1_VALUE \
-TASN1_VISIBLESTRING \
-TA_Const \
-TA_Expr \
-TA_Expr_Kind \
-TA_Indices \
-TA_Indirection \
-TAbsoluteTime \
-TAcl \
-TAclItem \
-TAclMaskHow \
-TAclMode \
-TAclObjectKind \
-TAclResult \
-TAfterTriggerEvent \
-TAfterTriggerEventData \
-TAfterTriggerEventList \
-TAfterTriggers \
-TAfterTriggersData \
-TAgg \
-TAggClauseCounts \
-TAggHashEntry \
-TAggHashEntryData \
-TAggInfo \
-TAggState \
-TAggStatePerAgg \
-TAggStatePerAggData \
-TAggStatePerGroup \
-TAggStatePerGroupData \
-TAggStrategy \
-TAggref \
-TAggrefExprState \
-TAlias \
-TAllocBlock \
-TAllocBlockData \
-TAllocChunk \
-TAllocChunkData \
-TAllocPointer \
-TAllocSet \
-TAllocSetContext \
-TAllocateDesc \
-TAllocateDescKind \
-TAlterDatabaseSetStmt \
-TAlterDomainStmt \
-TAlterFunctionStmt \
-TAlterOwnerStmt \
-TAlterRoleSetStmt \
-TAlterRoleStmt \
-TAlterSeqStmt \
-TAlterTableCmd \
-TAlterTableStmt \
-TAlterTableType \
-TAlteredTableInfo \
-TAnalyzeAttrFetchFunc \
-TAnlIndexData \
-TAppend \
-TAppendPath \
-TAppendState \
-TArchive \
-TArchiveEntryPtr \
-TArchiveFormat \
-TArchiveHandle \
-TArchiveMode \
-TArchiverStage \
-TArrayBuildState \
-TArrayExpr \
-TArrayExprState \
-TArrayMapState \
-TArrayMetaState \
-TArrayParseState \
-TArrayRef \
-TArrayRefExprState \
-TArrayTuple \
-TArrayType \
-TAttInMetadata \
-TAttrDefInfo \
-TAttrDefault \
-TAttrNumber \
-TAuthRequest \
-TBF_KEY \
-TBIGNUM \
-TBIO \
-TBIO_F_BUFFER_CTX \
-TBIO_METHOD \
-TBIO_dummy \
-TBIT_STRING_BITNAME \
-TBMS_Membership \
-TBN_BLINDING \
-TBN_CTX \
-TBN_MONT_CTX \
-TBN_RECP_CTX \
-TBOX \
-TBTBuildState \
-TBTItem \
-TBTItemData \
-TBTMetaPageData \
-TBTPageOpaque \
-TBTPageOpaqueData \
-TBTPageState \
-TBTScanOpaque \
-TBTScanOpaqueData \
-TBTSpool \
-TBTStack \
-TBTStackData \
-TBTWriteState \
-TBUF_MEM \
-TBackend \
-TBackendId \
-TBgWriterRequest \
-TBgWriterShmemStruct \
-TBitmapAnd \
-TBitmapAndPath \
-TBitmapAndState \
-TBitmapHeapPath \
-TBitmapHeapScan \
-TBitmapHeapScanState \
-TBitmapIndexScan \
-TBitmapIndexScanState \
-TBitmapOr \
-TBitmapOrPath \
-TBitmapOrState \
-TBitmapset \
-TBkpBlock \
-TBlock \
-TBlockId \
-TBlockIdData \
-TBlockNumber \
-TBlockSampler \
-TBlockSamplerData \
-TBoolExpr \
-TBoolExprState \
-TBoolExprType \
-TBoolPtr \
-TBoolTestType \
-TBooleanTest \
-TBpChar \
-TBucket \
-TBufFile \
-TBufFlags \
-TBuffer \
-TBufferDesc \
-TBufferLookupEnt \
-TBufferStrategyControl \
-TBufferTag \
-TByte \
-TBytef \
-TCAC_state \
-TCAST_KEY \
-TCATEGORY \
-TCFuncHashTabEntry \
-TCIRCLE \
-TCOMP_CTX \
-TCOMP_METHOD \
-TCPFunction \
-TCPPFunction \
-TCRYPTO_EX_DATA \
-TCRYPTO_EX_DATA_FUNCS \
-TCRYPTO_EX_DATA_IMPL \
-TCRYPTO_EX_dup \
-TCRYPTO_EX_free \
-TCRYPTO_EX_new \
-TCRYPTO_MEM_LEAK_CB \
-TCRYPTO_dynlock \
-TCacheCallbackFunction \
-TCancelRequestPacket \
-TCaseExpr \
-TCaseExprState \
-TCaseTestExpr \
-TCaseWhen \
-TCaseWhenState \
-TCash \
-TCastInfo \
-TCatCList \
-TCatCTup \
-TCatCache \
-TCatCacheHeader \
-TCatalogId \
-TCatalogIndexState \
-TChangeVarNodes_context \
-TCheckPoint \
-TCheckPointStmt \
-TChromosome \
-TCity \
-TClosePortalStmt \
-TClosePtr \
-TClusterStmt \
-TCmdType \
-TCoalesceExpr \
-TCoalesceExprState \
-TCoerceToDomain \
-TCoerceToDomainState \
-TCoerceToDomainValue \
-TCoercionCodes \
-TCoercionContext \
-TCoercionForm \
-TColumnDef \
-TColumnIOData \
-TColumnRef \
-TCommandDest \
-TCommandId \
-TCommentItem \
-TCommentStmt \
-TCompositeTypeStmt \
-TConnStatusType \
-TConst \
-TConstrCheck \
-TConstrType \
-TConstraint \
-TConstraintCategory \
-TConstraintInfo \
-TConstraintsSetStmt \
-TContainsOids \
-TControlFileData \
-TConvInfo \
-TConvertRowtypeExpr \
-TConvertRowtypeExprState \
-TCookedConstraint \
-TCopyDest \
-TCopyReadResult \
-TCopyStmt \
-TCost \
-TCostSelector \
-TCreateCastStmt \
-TCreateConversionStmt \
-TCreateDomainStmt \
-TCreateFunctionStmt \
-TCreateOpClassItem \
-TCreateOpClassStmt \
-TCreatePLangStmt \
-TCreateRoleStmt \
-TCreateSchemaStmt \
-TCreateSchemaStmtContext \
-TCreateSeqStmt \
-TCreateStmt \
-TCreateStmtContext \
-TCreateTableSpaceStmt \
-TCreateTrigStmt \
-TCreatedbStmt \
-TCred \
-TCtlCommand \
-TCustomOutPtr \
-TDBState \
-TDCHCacheEntry \
-TDCH_poz \
-TDEADLOCK_INFO \
-TDES_cblock \
-TDES_key_schedule \
-TDH \
-TDH_METHOD \
-TDIR \
-TDR_printtup \
-TDSA \
-TDSA_METHOD \
-TDSA_SIG \
-TDataDumperPtr \
-TDateADT \
-TDatum \
-TDatumPtr \
-TDatumTuple \
-TDatumTupleFields \
-TDeallocateStmt \
-TDeclareCursorStmt \
-TDefElem \
-TDefineStmt \
-TDeleteStmt \
-TDependencyType \
-TDestReceiver \
-TDistinctExpr \
-TDl_info \
-TDlelem \
-TDllist \
-TDomainConstraintState \
-TDomainConstraintType \
-TDropBehavior \
-TDropCastStmt \
-TDropPLangStmt \
-TDropPropertyStmt \
-TDropRoleStmt \
-TDropStmt \
-TDropTableSpaceStmt \
-TDropdbStmt \
-TDumpId \
-TDumpableObject \
-TDumpableObjectType \
-TDynamicFileList \
-TEDGE \
-TENGINE \
-TERR_FNS \
-TERR_STATE \
-TERR_STRING_DATA \
-TEState \
-TEVP_CIPHER \
-TEVP_CIPHER_CTX \
-TEVP_CIPHER_INFO \
-TEVP_ENCODE_CTX \
-TEVP_MD \
-TEVP_MD_CTX \
-TEVP_PBE_KEYGEN \
-TEVP_PKEY \
-TEdge \
-TEndBlobPtr \
-TEndBlobsPtr \
-TEndDataPtr \
-TEntryUpdateRecord \
-TEolType \
-TErrorContextCallback \
-TErrorData \
-TExecContext \
-TExecContextData \
-TExecScanAccessMtd \
-TExecStatus \
-TExecStatusType \
-TExecuteStmt \
-TExplainState \
-TExplainStmt \
-TExpr \
-TExprContext \
-TExprContextCallbackFunction \
-TExprContext_CB \
-TExprDoneCond \
-TExprState \
-TExprStateEvalFunc \
-TFILE \
-TFSMHeader \
-TFSMPageData \
-TFSMRelation \
-TFUNMAP \
-TFetchDirection \
-TFetchStmt \
-TFieldSelect \
-TFieldSelectState \
-TFieldStore \
-TFieldStoreState \
-TFile \
-TFileName \
-TFindSplitData \
-TFkConstraint \
-TFmgrBuiltin \
-TFmgrInfo \
-TFormData_pg_aggregate \
-TFormData_pg_am \
-TFormData_pg_amop \
-TFormData_pg_amproc \
-TFormData_pg_attrdef \
-TFormData_pg_attribute \
-TFormData_pg_auth_members \
-TFormData_pg_authid \
-TFormData_pg_cast \
-TFormData_pg_class \
-TFormData_pg_constraint \
-TFormData_pg_conversion \
-TFormData_pg_database \
-TFormData_pg_depend \
-TFormData_pg_description \
-TFormData_pg_index \
-TFormData_pg_inherits \
-TFormData_pg_language \
-TFormData_pg_largeobject \
-TFormData_pg_listener \
-TFormData_pg_namespace \
-TFormData_pg_opclass \
-TFormData_pg_operator \
-TFormData_pg_proc \
-TFormData_pg_rewrite \
-TFormData_pg_sequence \
-TFormData_pg_statistic \
-TFormData_pg_tablespace \
-TFormData_pg_trigger \
-TFormData_pg_type \
-TForm_pg_aggregate \
-TForm_pg_am \
-TForm_pg_amop \
-TForm_pg_amproc \
-TForm_pg_attrdef \
-TForm_pg_attribute \
-TForm_pg_auth_members \
-TForm_pg_authid \
-TForm_pg_cast \
-TForm_pg_class \
-TForm_pg_constraint \
-TForm_pg_conversion \
-TForm_pg_database \
-TForm_pg_depend \
-TForm_pg_description \
-TForm_pg_index \
-TForm_pg_inherits \
-TForm_pg_language \
-TForm_pg_largeobject \
-TForm_pg_listener \
-TForm_pg_namespace \
-TForm_pg_opclass \
-TForm_pg_operator \
-TForm_pg_proc \
-TForm_pg_rewrite \
-TForm_pg_sequence \
-TForm_pg_statistic \
-TForm_pg_tablespace \
-TForm_pg_trigger \
-TForm_pg_type \
-TFormatNode \
-TFromExpr \
-TFsmCacheFileHeader \
-TFsmCacheRelHeader \
-TFuncCall \
-TFuncCallContext \
-TFuncCandidateList \
-TFuncDetailCode \
-TFuncExpr \
-TFuncExprState \
-TFuncInfo \
-TFuncWithArgs \
-TFunction \
-TFunctionCallInfo \
-TFunctionCallInfoData \
-TFunctionParameter \
-TFunctionParameterMode \
-TFunctionScan \
-TFunctionScanState \
-TGEN_SESSION_CB \
-TGISTBuildState \
-TGISTENTRY \
-TGISTInsertStack \
-TGISTInsertState \
-TGISTPageOpaque \
-TGISTPageOpaqueData \
-TGISTSTATE \
-TGISTScanList \
-TGISTScanListData \
-TGISTScanOpaque \
-TGISTScanOpaqueData \
-TGISTSearchStack \
-TGIST_SPLITVEC \
-TGUC_yy_size_t \
-TGUC_yy_state_type \
-TGene \
-TGenericExprState \
-TGeqoEvalData \
-TGistBDItem \
-TGistEntryVector \
-TGistNSN \
-TGistVacuum \
-TGlobalTransaction \
-TGlobalTransactionData \
-TGrantObjectType \
-TGrantRoleStmt \
-TGrantStmt \
-TGroup \
-TGroupClause \
-TGroupState \
-TGroupVarInfo \
-TGucBoolAssignHook \
-TGucContext \
-TGucIntAssignHook \
-TGucRealAssignHook \
-TGucShowHook \
-TGucSource \
-TGucStack \
-TGucStringAssignHook \
-THASHACTION \
-THASHBUCKET \
-THASHCTL \
-THASHELEMENT \
-THASHHDR \
-THASHSEGMENT \
-THASH_SEQ_STATUS \
-THISTORY_STATE \
-THIST_ENTRY \
-THTAB \
-THTSU_Result \
-THTSV_Result \
-THash \
-THashAllocFunc \
-THashBuildState \
-THashCompareFunc \
-THashCopyFunc \
-THashItem \
-THashItemData \
-THashJoin \
-THashJoinState \
-THashJoinTable \
-THashJoinTableData \
-THashJoinTuple \
-THashJoinTupleData \
-THashMetaPage \
-THashMetaPageData \
-THashPageOpaque \
-THashPageOpaqueData \
-THashPath \
-THashScanList \
-THashScanListData \
-THashScanOpaque \
-THashScanOpaqueData \
-THashState \
-THashValueFunc \
-THeapScanDesc \
-THeapScanDescData \
-THeapTuple \
-THeapTupleData \
-THeapTupleFields \
-THeapTupleHeader \
-THeapTupleHeaderData \
-TIOFuncSelector \
-TIdList \
-TInClauseInfo \
-TIncrementVarSublevelsUp_context \
-TIndex \
-TIndexAttributeBitMap \
-TIndexAttributeBitMapData \
-TIndexBuildCallback \
-TIndexBulkDeleteCallback \
-TIndexBulkDeleteResult \
-TIndexElem \
-TIndexFSMPageData \
-TIndexInfo \
-TIndexList \
-TIndexOptInfo \
-TIndexPath \
-TIndexScan \
-TIndexScanDesc \
-TIndexScanDescData \
-TIndexScanDescPtr \
-TIndexScanState \
-TIndexStmt \
-TIndexTuple \
-TIndexTupleData \
-TIndexVacuumCleanupInfo \
-TIndirectBlock \
-TIndxInfo \
-TInhInfo \
-TInhOption \
-TInhPaths \
-TInhRelation \
-TInnerIndexscanInfo \
-TInsertStmt \
-TInstrumentation \
-TInt8TransTypeData \
-TIntArray \
-TInt_yy_size_t \
-TInt_yy_state_type \
-TInt_yysigned_char \
-TInterval \
-TInvalidationChunk \
-TInvalidationListHeader \
-TIpcMemoryId \
-TIpcMemoryKey \
-TIpcSemaphoreId \
-TIpcSemaphoreKey \
-TItem \
-TItemId \
-TItemIdData \
-TItemIdFlags \
-TItemLength \
-TItemOffset \
-TItemPointer \
-TItemPointerData \
-TJoin \
-TJoinExpr \
-TJoinHashEntry \
-TJoinPath \
-TJoinState \
-TJoinType \
-TJunkFilter \
-TKEYMAP_ENTRY \
-TKEYMAP_ENTRY_ARRAY \
-TKeySuffix \
-TKeyWord \
-TKeymap \
-TLHASH \
-TLHASH_COMP_FN_TYPE \
-TLHASH_DOALL_ARG_FN_TYPE \
-TLHASH_DOALL_FN_TYPE \
-TLHASH_HASH_FN_TYPE \
-TLHASH_NODE \
-TLINE \
-TLOCALLOCK \
-TLOCALLOCKOWNER \
-TLOCALLOCKTAG \
-TLOCK \
-TLOCKMASK \
-TLOCKMETHODID \
-TLOCKMODE \
-TLOCKTAG \
-TLSEG \
-TLVRelStats \
-TLWLock \
-TLWLockId \
-TLWLockMode \
-TLargeObjectDesc \
-TLimit \
-TLimitState \
-TLimitStateCond \
-TList \
-TListCell \
-TListenStmt \
-TLoadStmt \
-TLocalBufferLookupEnt \
-TLocationIndex \
-TLockAcquireResult \
-TLockData \
-TLockInfo \
-TLockInfoData \
-TLockMethod \
-TLockMethodData \
-TLockRelId \
-TLockStmt \
-TLockTagType \
-TLockTupleMode \
-TLogStmtLevel \
-TLogicalTape \
-TLogicalTapeSet \
-TMD2_CTX \
-TMD4_CTX \
-TMD5_CTX \
-TMDC2_CTX \
-TMaterial \
-TMaterialPath \
-TMaterialState \
-TMdfdVec \
-TMemoryContext \
-TMemoryContextData \
-TMemoryContextMethods \
-TMergeFunctionKind \
-TMergeJoin \
-TMergeJoinClause \
-TMergeJoinClauseData \
-TMergeJoinState \
-TMergePath \
-TMinMaxAggInfo \
-TMinMaxExpr \
-TMinMaxExprState \
-TMinMaxOp \
-TMsgType \
-TMultiXactId \
-TMultiXactOffset \
-TMultiXactStateData \
-TNETSCAPE_CERT_SEQUENCE \
-TNETSCAPE_SPKAC \
-TNETSCAPE_SPKI \
-TNUMCacheEntry \
-TNUMDesc \
-TNUMProc \
-TNUM_poz \
-TName \
-TNameData \
-TNamespaceInfo \
-TNestLoop \
-TNestLoopState \
-TNestPath \
-TNewColumnValue \
-TNewConstraint \
-TNewPage \
-TNode \
-TNodeTag \
-TNotifyStmt \
-TNullIfExpr \
-TNullTest \
-TNullTestType \
-TNumeric \
-TNumericData \
-TNumericDigit \
-TNumericVar \
-TOBJ_NAME \
-TObjectAddress \
-TObjectAddresses \
-TObjectClass \
-TObjectType \
-TOffset \
-TOffsetNumber \
-TOffsetVarNodes_context \
-TOid \
-TOidOptions \
-TOldstyle_fnextra \
-TOnCommitAction \
-TOnCommitItem \
-TOpClassCacheEnt \
-TOpClassMember \
-TOpExpr \
-TOpclassCandidateList \
-TOpclassInfo \
-TOperator \
-TOprInfo \
-TOutputContext \
-TPATH \
-TPBE2PARAM \
-TPBEPARAM \
-TPBKDF2PARAM \
-TPEM_CTX \
-TPEM_ENCODE_SEAL_CTX \
-TPEM_USER \
-TPGErrorVerbosity \
-TPGFInfoFunction \
-TPGFunction \
-TPGLZ_DecompState \
-TPGLZ_Header \
-TPGLZ_HistEntry \
-TPGLZ_Strategy \
-TPGPROC \
-TPGSemaphore \
-TPGSemaphoreData \
-TPGShmemHeader \
-TPGTransactionStatusType \
-TPGVerbosity \
-TPG_Lock_Status \
-TPGcancel \
-TPGconn \
-TPGnotify \
-TPGresult \
-TPKCS7 \
-TPKCS7_DIGEST \
-TPKCS7_ENCRYPT \
-TPKCS7_ENC_CONTENT \
-TPKCS7_ENVELOPE \
-TPKCS7_ISSUER_AND_SERIAL \
-TPKCS7_RECIP_INFO \
-TPKCS7_SIGNED \
-TPKCS7_SIGNER_INFO \
-TPKCS7_SIGN_ENVELOPE \
-TPKCS8_PRIV_KEY_INFO \
-TPMSignalReason \
-TPOLYGON \
-TPQArgBlock \
-TPQExpBuffer \
-TPQExpBufferData \
-TPQconninfoOption \
-TPQnoticeProcessor \
-TPQnoticeReceiver \
-TPQprintOpt \
-TPROCLOCK \
-TPROCLOCKTAG \
-TPROC_HDR \
-TPROC_QUEUE \
-TPacketLen \
-TPage \
-TPageFreeSpaceInfo \
-TPageHeader \
-TPageHeaderData \
-TPageSplitRecord \
-TPagetableEntry \
-TParam \
-TParamExecData \
-TParamListInfo \
-TParamListInfoData \
-TParamRef \
-TParseState \
-TPath \
-TPathKeyItem \
-TPathKeysComparison \
-TPattern_Prefix_Status \
-TPattern_Type \
-TPendingOperationEntry \
-TPendingRelDelete \
-TPgStat_Counter \
-TPgStat_Info \
-TPgStat_Msg \
-TPgStat_MsgActivity \
-TPgStat_MsgBestart \
-TPgStat_MsgBeterm \
-TPgStat_MsgDropdb \
-TPgStat_MsgDummy \
-TPgStat_MsgHdr \
-TPgStat_MsgResetcounter \
-TPgStat_MsgTabpurge \
-TPgStat_MsgTabstat \
-TPgStat_StatBeDead \
-TPgStat_StatBeEntry \
-TPgStat_StatDBEntry \
-TPgStat_StatTabEntry \
-TPgStat_TableEntry \
-TPg_finfo_record \
-TPlan \
-TPlanState \
-TPlannerInfo \
-TPlannerParamItem \
-TPoint \
-TPointer \
-TPool \
-TPort \
-TPortal \
-TPortalData \
-TPortalHashEnt \
-TPortalStatus \
-TPortalStrategy \
-TPostgresPollingStatusType \
-TPrepareStmt \
-TPreparedStatement \
-TPrintExtraTocPtr \
-TPrintTocDataPtr \
-TPrinttupAttrInfo \
-TPrivGrantee \
-TPrivTarget \
-TProcArrayStruct \
-TProcLangInfo \
-TProcState \
-TProcessingMode \
-TProjectionInfo \
-TProtocolVersion \
-TPsqlScanResult \
-TPsqlScanState \
-TPsqlScanStateData \
-TPsqlSettings \
-TQualCost \
-TQuery \
-TQueryDesc \
-TQuerySource \
-TRC2_KEY \
-TRC4_KEY \
-TRIPEMD160_CTX \
-TRI_QueryHashEntry \
-TRI_QueryKey \
-TRSA \
-TRSA_METHOD \
-TRTBuildState \
-TRTEKind \
-TRTSTACK \
-TRTSTATE \
-TRTScanList \
-TRTScanListData \
-TRTreePageOpaque \
-TRTreePageOpaqueData \
-TRTreeScanOpaque \
-TRTreeScanOpaqueData \
-TRangeFunction \
-TRangeQueryClause \
-TRangeSubselect \
-TRangeTblEntry \
-TRangeTblRef \
-TRangeVar \
-TRawColumnDefault \
-TReadBufPtr \
-TReadBytePtr \
-TReadExtraTocPtr \
-TRecordCacheEntry \
-TRecordIOData \
-TRegProcedure \
-TReindexStmt \
-TRelFileNode \
-TRelIdCacheEnt \
-TRelOptInfo \
-TRelOptKind \
-TRelToCheck \
-TRelToCluster \
-TRelabelType \
-TRelation \
-TRelationAmInfo \
-TRelationData \
-TRelationPtr \
-TRelativeTime \
-TRelids \
-TRemoveAggrStmt \
-TRemoveFuncStmt \
-TRemoveOpClassStmt \
-TRemoveOperStmt \
-TRenameStmt \
-TResTarget \
-TResolveNew_context \
-TResourceOwner \
-TResourceOwnerData \
-TResourceReleaseCallback \
-TResourceReleaseCallbackItem \
-TResourceReleasePhase \
-TRestoreOptions \
-TRestrictInfo \
-TResult \
-TResultPath \
-TResultRelInfo \
-TResultState \
-TReturnSetInfo \
-TRewriteRule \
-TRmgrData \
-TRmgrId \
-TRowExpr \
-TRowExprState \
-TRuleInfo \
-TRuleLock \
-TRuleStmt \
-TSHA_CTX \
-TSHMEM_OFFSET \
-TSHM_QUEUE \
-TSISeg \
-TSMgrRelation \
-TSMgrRelationData \
-TSPITupleTable \
-TSPLITCOST \
-TSPLITVEC \
-TSQLFunctionCache \
-TSQLFunctionCachePtr \
-TSSL \
-TSSL2_STATE \
-TSSL3_BUFFER \
-TSSL3_RECORD \
-TSSL3_STATE \
-TSSL_CIPHER \
-TSSL_COMP \
-TSSL_CTX \
-TSSL_METHOD \
-TSSL_SESSION \
-TSTACK \
-TSaveArchivePtr \
-TScalarArrayOpExpr \
-TScalarArrayOpExprState \
-TScalarItem \
-TScalarMCVItem \
-TScan \
-TScanDirection \
-TScanKey \
-TScanKeyData \
-TScanKeyword \
-TScanState \
-TSchemaQuery \
-TSelectStmt \
-TSelectivity \
-TSeqScan \
-TSeqScanState \
-TSeqTable \
-TSeqTableData \
-TSetConstraintState \
-TSetConstraintStateData \
-TSetConstraintTrigger \
-TSetConstraintTriggerData \
-TSetFunctionReturnMode \
-TSetOp \
-TSetOpCmd \
-TSetOpState \
-TSetOperation \
-TSetOperationStmt \
-TSetToDefault \
-TSharedInvalCatcacheMsg \
-TSharedInvalRelcacheMsg \
-TSharedInvalSmgrMsg \
-TSharedInvalidationMessage \
-TShmemIndexEnt \
-TShutdownMode \
-TSigHandler \
-TSize \
-TSlruCtl \
-TSlruCtlData \
-TSlruErrorCause \
-TSlruFlush \
-TSlruFlushData \
-TSlruPageStatus \
-TSlruShared \
-TSlruSharedData \
-TSnapshot \
-TSnapshotData \
-TSockAddr \
-TSort \
-TSortBy \
-TSortClause \
-TSortFunctionKind \
-TSortState \
-TSplitedPageLayout \
-TStackElem \
-TStandardChunkHeader \
-TStartBlobPtr \
-TStartBlobsPtr \
-TStartDataPtr \
-TStartupPacket \
-TStdAnalyzeData \
-TStrategyNumber \
-TStringInfo \
-TStringInfoData \
-TSubLink \
-TSubLinkType \
-TSubPlan \
-TSubPlanState \
-TSubTransactionId \
-TSubXactCallback \
-TSubXactCallbackItem \
-TSubXactEvent \
-TSubqueryScan \
-TSubqueryScanState \
-TSysScanDesc \
-TSysScanDescData \
-TTAR_MEMBER \
-TTBMIterateResult \
-TTBMStatus \
-TTBlockState \
-TTIDBitmap \
-TTStoreState \
-TTableDataInfo \
-TTableInfo \
-TTargetEntry \
-TThingFile \
-TTidPath \
-TTidScan \
-TTidScanState \
-TTimeADT \
-TTimeInterval \
-TTimeIntervalData \
-TTimeLineID \
-TTimeTzADT \
-TTimestamp \
-TTimestampTz \
-TTimevalStruct \
-TTmFromChar \
-TTmToChar \
-TTocEntry \
-TTrackItem \
-TTransInvalidationInfo \
-TTransState \
-TTransactionId \
-TTransactionState \
-TTransactionStateData \
-TTransactionStmt \
-TTransactionStmtKind \
-TTrigger \
-TTriggerData \
-TTriggerDesc \
-TTriggerEvent \
-TTriggerInfo \
-TTruncateStmt \
-TTupOutputState \
-TTupSortStatus \
-TTupStoreStatus \
-TTupleConstr \
-TTupleDesc \
-TTupleHashEntry \
-TTupleHashEntryData \
-TTupleHashIterator \
-TTupleHashTable \
-TTupleHashTableData \
-TTupleTable \
-TTupleTableData \
-TTupleTableSlot \
-TTuplesortstate \
-TTuplestorestate \
-TTwoPhaseCallback \
-TTwoPhaseFileHeader \
-TTwoPhaseLockRecord \
-TTwoPhaseRecordOnDisk \
-TTwoPhaseRmgrId \
-TTwoPhaseStateData \
-TType \
-TTypeCacheEntry \
-TTypeCast \
-TTypeFuncClass \
-TTypeInfo \
-TTypeName \
-TUI \
-TUI_METHOD \
-TUI_STRING \
-TUNDO_LIST \
-TUnique \
-TUniquePath \
-TUniquePathMethod \
-TUniqueState \
-TUnlistenStmt \
-TUpdateStmt \
-TUserAuth \
-TVFunction \
-TVRelStats \
-TVTupleLink \
-TVTupleLinkData \
-TVTupleMove \
-TVTupleMoveData \
-TVacAttrStats \
-TVacAttrStatsP \
-TVacPage \
-TVacPageData \
-TVacPageList \
-TVacPageListData \
-TVacRUsage \
-TVacuumStmt \
-TValue \
-TVar \
-TVarBit \
-TVarChar \
-TVariableCache \
-TVariableCacheData \
-TVariableResetStmt \
-TVariableSetStmt \
-TVariableShowStmt \
-TVariableSpace \
-TVariableStatData \
-TVfd \
-TViewStmt \
-TWAIT_ORDER \
-TWorking_State \
-TWriteBufPtr \
-TWriteBytePtr \
-TWriteDataPtr \
-TWriteExtraTocPtr \
-TX509 \
-TX509_ALGOR \
-TX509_ATTRIBUTE \
-TX509_CERT_AUX \
-TX509_CERT_FILE_CTX \
-TX509_CINF \
-TX509_CRL \
-TX509_CRL_INFO \
-TX509_EXTENSION \
-TX509_HASH_DIR_CTX \
-TX509_INFO \
-TX509_LOOKUP \
-TX509_LOOKUP_METHOD \
-TX509_NAME \
-TX509_NAME_ENTRY \
-TX509_OBJECT \
-TX509_OBJECTS \
-TX509_PKEY \
-TX509_PUBKEY \
-TX509_REQ \
-TX509_REQ_INFO \
-TX509_REVOKED \
-TX509_SIG \
-TX509_STORE \
-TX509_STORE_CTX \
-TX509_TRUST \
-TX509_VAL \
-TXLogContRecord \
-TXLogCtlData \
-TXLogCtlInsert \
-TXLogCtlWrite \
-TXLogLongPageHeader \
-TXLogLongPageHeaderData \
-TXLogPageHeader \
-TXLogPageHeaderData \
-TXLogRecData \
-TXLogRecPtr \
-TXLogRecord \
-TXLogRelCacheEntry \
-TXLogRelDesc \
-TXLogwrtResult \
-TXLogwrtRqst \
-TXactCallback \
-TXactCallbackItem \
-TXactEvent \
-TXidStatus \
-TYYSTYPE \
-TYY_BUFFER_STATE \
-TYY_CHAR \
-T_LIB_VERSION_TYPE \
-T_RuneEntry \
-T_RuneLocale \
-T_RuneRange \
-T_SPI_connection \
-T_SPI_plan \
-T_ossl_old_des_cblock \
-T_ossl_old_des_key_schedule \
-Taclitem \
-Tadjust_inherited_attrs_context \
-Talc_extra \
-Talloc_func \
-Tanyarray \
-Tassoc_list \
-Tatc_extra \
-Tattribute_used_context \
-Tauth_entry \
-Tauthmem_entry \
-TbackslashResult \
-Tbio_info_cb \
-Tbitmapword \
-Tbits16 \
-Tbits32 \
-Tbits8 \
-Tbool \
-Tbt_incomplete_split \
-Tbytea \
-Tcached_re_str \
-Tcaddr_t \
-Tcc_t \
-Tcelt \
-Tchar \
-Tcharf \
-TcheckExprHasAggs_context \
-Tcheck_parameter_resolution_context \
-Tcheck_ungrouped_columns_context \
-Tchr \
-Tclock_t \
-Tclockid_t \
-Tcolor \
-Tconst_DES_cblock \
-Tcontain_var_reference_context \
-Tdaddr_t \
-Tdatetkn \
-Tdeparse_context \
-Tdeparse_namespace \
-Tdev_t \
-Tdiv_t \
-Tdouble \
-TevalPlanQual \
-Teval_const_expressions_context \
-TexecRowMark \
-Texecution_state \
-Tf_smgr \
-Tfd_mask \
-Tfd_set \
-Tfinalize_primnode_context \
-Tfind_expr_references_context \
-Tfind_minimum_var_level_context \
-Tfixpt_t \
-Tflatten_join_alias_vars_context \
-Tfloat \
-Tfloat32 \
-Tfloat32data \
-Tfloat4 \
-Tfloat64 \
-Tfloat64data \
-Tfloat8 \
-TfmNodePtr \
-Tfp_except \
-Tfp_rnd \
-Tfpclass_t \
-Tfpos_t \
-Tfree_func \
-Tfsec_t \
-Tfunc_ptr \
-Tgenerate_series_fctx \
-Tgid_t \
-TgistIncompleteInsert \
-TgistxlogEntryUpdate \
-TgistxlogInsertComplete \
-TgistxlogPage \
-TgistxlogPageSplit \
-TgzFile \
-Thashnode \
-ThbaPort \
-Thelp_handler \
-Tin_addr_t \
-Tin_port_t \
-Tindexed_tlist \
-Tinet \
-Tinet_struct \
-Tino_t \
-Tinstr_time \
-Tint \
-Tint16 \
-Tint16_t \
-Tint16m_t \
-Tint2 \
-Tint2vector \
-Tint32 \
-Tint32_t \
-Tint32m_t \
-Tint4 \
-Tint64 \
-Tint64_t \
-Tint64m_t \
-Tint8 \
-Tint8_t \
-Tint8m_t \
-Tintf \
-TitemIdSort \
-TitemIdSortData \
-Tjmp_buf \
-Tjoin_references_context \
-Tkey_t \
-TlclContext \
-TlclTocEntry \
-Tldiv_t \
-TmXactCacheEnt \
-Tmacaddr \
-Tmb2wchar_with_len_converter \
-Tmbdisplaylen_converter \
-Tmblen_converter \
-TmixedStruct \
-Tmode_t \
-Tnlink_t \
-Tnls_uint32 \
-Toff_t \
-Toidvector \
-ToptType \
-Tpcolor \
-Tpem_password_cb \
-Tpg_crc32 \
-Tpg_enc \
-Tpg_enc2name \
-Tpg_encname \
-Tpg_local_to_utf \
-Tpg_time_t \
-Tpg_tz \
-Tpg_utf_to_local \
-Tpg_wchar \
-Tpg_wchar_tbl \
-Tpgpid_t \
-Tpgsql_thing_t \
-Tpgthreadlock_t \
-Tpid_t \
-Tpqbool \
-Tpqsigfunc \
-TprintQueryOpt \
-TprintTableOpt \
-TpromptStatus_t \
-Tpthread_attr_t \
-Tpthread_cond_t \
-Tpthread_condattr_t \
-Tpthread_key_t \
-Tpthread_mutex_t \
-Tpthread_mutexattr_t \
-Tpthread_once_t \
-Tpthread_t \
-Tptrdiff_t \
-Tpull_var_clause_context \
-Tpull_varnos_context \
-Tq128_t \
-Tqaddr_t \
-Tquad_t \
-TrangeTableEntry_used_context \
-Treduce_outer_joins_state \
-Tregex_t \
-Tregister_t \
-Tregmatch_t \
-Tregoff_t \
-Tregproc \
-Treplace_vars_with_subplan_refs_context \
-Trewrite_event \
-Trm_detail_t \
-Trune_t \
-Tsa_family_t \
-Tsegsz_t \
-Tsequence_magic \
-Tsig_atomic_t \
-Tsig_t \
-Tsighandler_cxt \
-Tsigjmp_buf \
-Tsignedbitmapword \
-Tsigset_t \
-Tsize_t \
-Tslock_t \
-Tsmgrid \
-Tsocklen_t \
-Tspeed_t \
-TsqlparseInfo \
-TsqlparseState \
-Tssize_t \
-Tssl_crock_st \
-Tstack_t \
-Tsubstitute_actual_parameters_context \
-Tswblk_t \
-Ttcflag_t \
-Ttcp_seq \
-TteReqs \
-Ttext \
-Ttime_t \
-Ttlist_vinfo \
-Tts_db_fctx \
-TuInt \
-TuIntf \
-TuLong \
-TuLongf \
-Tu_char \
-Tu_int \
-Tu_int16_t \
-Tu_int16m_t \
-Tu_int32_t \
-Tu_int32m_t \
-Tu_int64_t \
-Tu_int64m_t \
-Tu_int8_t \
-Tu_int8m_t \
-Tu_long \
-Tu_quad_t \
-Tu_short \
-Tuchr \
-Tuid_t \
-Tuint \
-Tuint16 \
-Tuint32 \
-Tuint64 \
-Tuint8 \
-Tunknown \
-Tushort \
-Tva_list \
-Tvarattrib \
-Tvm_offset_t \
-Tvm_size_t \
-Tvoid \
-Tvoidp \
-Tvoidpf \
-Twchar_t \
-Twctype_t \
-Twint_t \
-Txl_btree_delete \
-Txl_btree_delete_page \
-Txl_btree_insert \
-Txl_btree_metadata \
-Txl_btree_newmeta \
-Txl_btree_newroot \
-Txl_btree_split \
-Txl_btreetid \
-Txl_dbase_create_rec \
-Txl_dbase_create_rec_old \
-Txl_dbase_drop_rec \
-Txl_dbase_drop_rec_old \
-Txl_heap_clean \
-Txl_heap_delete \
-Txl_heap_header \
-Txl_heap_insert \
-Txl_heap_lock \
-Txl_heap_newpage \
-Txl_heap_update \
-Txl_heaptid \
-Txl_multixact_create \
-Txl_seq_rec \
-Txl_smgr_create \
-Txl_smgr_truncate \
-Txl_tblspc_create_rec \
-Txl_tblspc_drop_rec \
-Txl_xact_abort \
-Txl_xact_abort_prepared \
-Txl_xact_commit \
-Txl_xact_commit_prepared \
-Tyy_size_t \
-Tyy_state_type \
-Tyysigned_char \
-Tz_stream \
-Tz_streamp \
/tmp/$$a >/tmp/$$ 2>&1
	if [ "$?" -ne 0 -o -s /tmp/$$ ]
	then	echo
		echo "$FILE"
		cat /tmp/$$
	fi
	cat /tmp/$$a |
# restore DATA/CATALOG lines
	sed 's;^/\*\(DATA(.*\)\*/$;\1;' |
	sed 's;^/\*\(CATALOG(.*\)\*/$;\1;' |
# remove tabs and retab with four spaces
	detab -t8 -qc |
	entab -t4 -qc |
	sed 's;^/\* Open extern \"C\" \*/$;{;' |
	sed 's;^/\* Close extern \"C\" \*/$;};' |
	sed 's;/\*---X_X;/* ---;g' |
# workaround indent bug
	sed 's;^static[ 	][ 	]*;static ;g' |
	sed 's;^}	[ 	]*;}	;' |
# pull in #endif comments
	sed 's;^#endif[ 	][ 	]*/\*;#endif   /*;' |
# work around #else indenting next line if #ifdef defines variables at top
# work around misindenting of function with no variables defined
	awk '
	{
		if ($0 ~ /^[ 	]*int[ 	]*pgindent_func_no_var_fix;/)
		{
			if (getline && $0 != "")
				print $0;
		}
		else 	print $0;
	}' |
# add space after comments that start on tab stops
	sed 's;\([^ 	]\)\(/\*.*\*/\)$;\1	\2;' |
# move trailing * in function return type
	sed 's;^\([A-Za-z_][^ 	]*\)[ 	][ 	]*\*$;\1 *;' |
# remove un-needed braces around single statements
# Do not use because it uglifies PG_TRY/PG_CATCH blocks and probably
# isn't needed for general use.
#	awk '
#	{
#			line3 = $0;  
#			if (skips > 0)
#				skips--;
#			if (line1 ~ /		*{$/ &&
#			    line2 ~ /		*[^;{}]*;$/ &&
#			    line3 ~ /		*}$/)
#			{
#				print line2;
#				line2 = "";
#				line3 = "";
#				skips = 3;
#			}
#			else
#	 			if (skips == 0 && NR >= 3)
#					print line1;
#			line1 = line2;
#			line2 = line3;
#		}
#		END {
#			if (NR >= 2 && skips <= 1)
#				print line1;
#			if (NR >= 1 && skips <= 2)
#				print line2;
#		}' |
# remove blank line between opening brace and block comment
	awk '
	{
			line3 = $0;  
			if (skips > 0)
				skips--;
			if (line1 ~ /	*{$/ &&
			    line2 ~ /^$/ &&
			    line3 ~ /		*\/\*$/)
			{
				print line1;
				print line3;
				line2 = "";
				line3 = "";
				skips = 3;
			}
			else
	 			if (skips == 0 && NR >= 3)
					print line1;
			line1 = line2;
			line2 = line3;
		}
		END {
			if (NR >= 2 && skips <= 1)
				print line1;
			if (NR >= 1 && skips <= 2)
				print line2;
		}' |
# remove trailing blank lines, helps with adding blank before trailing #endif
	awk '	BEGIN	{blank_lines = 0;}
		{
			line1 = $0;
	 		if (line1 ~ /^$/)
				blank_lines++;
			else
			{
				for (; blank_lines > 0; blank_lines--)
					printf "\n";
				print line1;
			}
		}' |
# remove blank line before #else, #elif, and #endif
	awk '	BEGIN	{line1 = ""; line2 = ""; skips = 0}
		{
			line2 = $0;
			if (skips > 0)
				skips--;
			if (line1 ~ /^$/ &&
			    (line2 ~ /^#else/ ||
			     line2 ~ /^#elif/ ||
			     line2 ~ /^#endif/))
			{
				print line2;
				line2 = "";
				skips = 2;
			}
			else
	 			if (skips == 0 && NR >= 2)
					print line1;
			line1 = line2;
		}
		END {
			if (NR >= 1 && skips <= 1)
				print line1;
		}' |
# add blank line before #endif if it is the last line in the file
	awk '	BEGIN	{line1 = ""; line2 = ""}
		{
			line2 = $0;
	 		if (NR >= 2)
				print line1;
			line1 = line2;
		}
		END {
			if (NR >= 1 && line2 ~ /^#endif/)
				printf "\n";
			print line1;
		}' |
#  Move prototype names to the same line as return type.  Useful for ctags. 
#  Indent should do this, but it does not.  It formats prototypes just
#  like real functions.
	awk '	BEGIN	{paren_level = 0}  
	{
		if ($0 ~ /^[a-zA-Z_][a-zA-Z_0-9]*[^\(]*$/)
		{
			saved_len = 0;
			saved_lines[++saved_len] = $0;
			if ((getline saved_lines[++saved_len]) == 0)
				print saved_lines[1];
			else
			if (saved_lines[saved_len] !~ /^[a-zA-Z_][a-zA-Z_0-9]*\(/ ||
			    saved_lines[saved_len] ~  /^[a-zA-Z_][a-zA-Z_0-9]*\(.*\)$/ ||
			    saved_lines[saved_len] ~  /^[a-zA-Z_][a-zA-Z_0-9]*\(.*\);$/)
			{
				print saved_lines[1];
				print saved_lines[2];
			}
			else
			{
				while (1)
				{
					if ((getline saved_lines[++saved_len]) == 0)
						break;
					if (saved_lines[saved_len] ~ /^[^ 	]/ ||
					    saved_lines[saved_len] !~ /,$/)
						break;
				}
				for (i=1; i <= saved_len; i++)
				{
					if (i == 1 && saved_lines[saved_len] ~ /\);$/)
					{
						printf "%s", saved_lines[i];
						if (substr(saved_lines[i], length(saved_lines[i]),1) != "*")
							printf " ";
					}
					else	print saved_lines[i];
				}
			}
		}
		else	print $0;
	}' |
	cat >/tmp/$$ && cat /tmp/$$ >"$FILE"
done

# The 'for' loop makes these backup files useless so delete them
rm -f *a.BAK
