#!/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 -version </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' |
# mark some comments for special treatment later
	sed 's;/\*  *---;/*---X_X;g' |
# workaround for indent bug with 'else' handling
	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 with 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 -l75 \
		-lp -nip -npro -bbb $EXTRA_OPTS \
-TA_Const \
-TA_Expr \
-TA_Indices \
-TAbsoluteTime \
-TAcl \
-TAclId \
-TAclIdType \
-TAclItem \
-TAclMode \
-TAgg \
-TAggInfo \
-TAggState \
-TAggStatePerAgg \
-TAggStatePerAggData \
-TAggref \
-TAlgCode \
-TAllocBlock \
-TAllocBlockData \
-TAllocChunk \
-TAllocChunkData \
-TAllocPointer \
-TAllocSet \
-TAllocSetContext \
-TAlterGroupStmt \
-TAlterTableStmt \
-TAlterUserStmt \
-TAppend \
-TAppendPath \
-TAppendState \
-TArchive \
-TArchiveEntryPtr \
-TArchiveFormat \
-TArchiveHandle \
-TArchiveMode \
-TArrayRef \
-TArrayType \
-TAtom \
-TAttr \
-TAttrDefault \
-TAttrNumber \
-TAuthRequest \
-TAuthRequestPacket \
-TBOX \
-TBTBuildState \
-TBTItem \
-TBTItemData \
-TBTMetaPageData \
-TBTPageOpaque \
-TBTPageOpaqueData \
-TBTPageState \
-TBTScanOpaque \
-TBTScanOpaqueData \
-TBTSpool \
-TBTStack \
-TBTStackData \
-TBackend \
-TBackendId \
-TBitArray \
-TBitIndex \
-TBkpBlock \
-TBlock \
-TBlockId \
-TBlockIdData \
-TBlockNumber \
-TBoolPtr \
-TBoolTestType \
-TBooleanTest \
-TBpChar \
-TBucket \
-TBufFile \
-TBufFlags \
-TBuffer \
-TBufferDesc \
-TBufferLookupEnt \
-TBufferTag \
-TByte \
-TBytef \
-TCATEGORY \
-TCIRCLE \
-TCPFunction \
-TCPPFunction \
-TCancelRequestPacket \
-TCandidateList \
-TCaseExpr \
-TCaseWhen \
-TCash \
-TCatCTup \
-TCatCache \
-TCatCacheHeader \
-TChangeVarNodes_context \
-TCheckPoint \
-TCheckPointStmt \
-TChromosome \
-TCity \
-TClientData \
-TClogCtlData \
-TClogPageStatus \
-TClosePortalStmt \
-TClosePtr \
-TClusterStmt \
-TCmdType \
-TColormap \
-TColumnDef \
-TCommandDest \
-TCommandId \
-TCommentStmt \
-TCommonScanState \
-TCommonState \
-TConnStatusType \
-TConst \
-TConstrCheck \
-TConstrType \
-TConstraint \
-TConstraintsSetStmt \
-TControlFileData \
-TCopyStmt \
-TCost \
-TCostSelector \
-TCreateGroupStmt \
-TCreatePLangStmt \
-TCreateSeqStmt \
-TCreateStmt \
-TCreateStmtContext \
-TCreateTrigStmt \
-TCreateUserStmt \
-TCreatedbStmt \
-TCred \
-TCursor \
-TCustomOutPtr \
-TDBState \
-TDCHCacheEntry \
-TDCH_poz \
-TDIR \
-TDR_printtup \
-TDataDumperPtr \
-TDateADT \
-TDatum \
-TDatumPtr \
-TDatumTuple \
-TDefElem \
-TDeferredTriggerEvent \
-TDeferredTriggerEventData \
-TDeferredTriggerEventItem \
-TDeferredTriggerStatus \
-TDeferredTriggerStatusData \
-TDefineStmt \
-TDeleteStmt \
-TDepth \
-TDestReceiver \
-TDisplay \
-TDl_info \
-TDlelem \
-TDllist \
-TDrawable \
-TDropGroupStmt \
-TDropPLangStmt \
-TDropStmt \
-TDropTrigStmt \
-TDropUserStmt \
-TDropdbStmt \
-TDumpContext \
-TDynamicFileList \
-TEDGE \
-TEState \
-TEdge \
-TEndBlobPtr \
-TEndBlobsPtr \
-TEndDataPtr \
-TErrorMessagePacket \
-TExcContext \
-TExcData \
-TExcDetail \
-TExcFrame \
-TExcId \
-TExcMessage \
-TExcProc \
-TException \
-TExecScanAccessMtd \
-TExecStatus \
-TExecStatusType \
-TExplainState \
-TExplainStmt \
-TExpr \
-TExprContext \
-TExprDoneCond \
-TFILE \
-TFSMChunk \
-TFSMHeader \
-TFSMRelation \
-TFUNMAP \
-TFetchStmt \
-TFieldSelect \
-TFile \
-TFileName \
-TFindSplitData \
-TFjoin \
-TFkConstraint \
-TFmgrBuiltin \
-TFmgrInfo \
-TFont \
-TFormData_pg_aggregate \
-TFormData_pg_am \
-TFormData_pg_amop \
-TFormData_pg_amproc \
-TFormData_pg_attrdef \
-TFormData_pg_attribute \
-TFormData_pg_class \
-TFormData_pg_database \
-TFormData_pg_description \
-TFormData_pg_group \
-TFormData_pg_index \
-TFormData_pg_inherits \
-TFormData_pg_language \
-TFormData_pg_largeobject \
-TFormData_pg_listener \
-TFormData_pg_opclass \
-TFormData_pg_operator \
-TFormData_pg_proc \
-TFormData_pg_relcheck \
-TFormData_pg_rewrite \
-TFormData_pg_sequence \
-TFormData_pg_shadow \
-TFormData_pg_statistic \
-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_class \
-TForm_pg_database \
-TForm_pg_description \
-TForm_pg_group \
-TForm_pg_index \
-TForm_pg_inherits \
-TForm_pg_language \
-TForm_pg_largeobject \
-TForm_pg_listener \
-TForm_pg_opclass \
-TForm_pg_operator \
-TForm_pg_proc \
-TForm_pg_relcheck \
-TForm_pg_rewrite \
-TForm_pg_sequence \
-TForm_pg_shadow \
-TForm_pg_statistic \
-TForm_pg_trigger \
-TForm_pg_type \
-TFormatNode \
-TFromExpr \
-TFunc \
-TFuncCall \
-TFuncDetailCode \
-TFuncInfo \
-TFunction \
-TFunctionCache \
-TFunctionCachePtr \
-TFunctionCallInfo \
-TFunctionCallInfoData \
-TGC \
-TGContext \
-TGISTBuildState \
-TGISTENTRY \
-TGISTPageOpaque \
-TGISTPageOpaqueData \
-TGISTSTACK \
-TGISTSTATE \
-TGISTScanList \
-TGISTScanListData \
-TGISTScanOpaque \
-TGISTScanOpaqueData \
-TGIST_SPLITVEC \
-TGUC_yy_size_t \
-TGUC_yy_state_type \
-TGene \
-TGrantStmt \
-TGroup \
-TGroupClause \
-TGroupState \
-TGucContext \
-THASHACTION \
-THASHBUCKET \
-THASHCTL \
-THASHELEMENT \
-THASHHDR \
-THASHSEGMENT \
-THASH_SEQ_STATUS \
-THISTORY_STATE \
-THIST_ENTRY \
-THOLDER \
-THOLDERTAG \
-THTAB \
-THTSV_Result \
-THash \
-THashBuildState \
-THashItem \
-THashItemData \
-THashJoin \
-THashJoinState \
-THashJoinTable \
-THashJoinTuple \
-THashJoinTupleData \
-THashMetaPage \
-THashMetaPageData \
-THashPageOpaque \
-THashPageOpaqueData \
-THashPath \
-THashScanList \
-THashScanListData \
-THashScanOpaque \
-THashScanOpaqueData \
-THashState \
-THashTableData \
-THeapAccessStatistics \
-THeapAccessStatisticsData \
-THeapScanDesc \
-THeapScanDescData \
-THeapTuple \
-THeapTupleData \
-THeapTupleHeader \
-THeapTupleHeaderData \
-TIdList \
-TIdent \
-TIncrementVarSublevelsUp_context \
-TIndInfo \
-TIndex \
-TIndexAttributeBitMap \
-TIndexAttributeBitMapData \
-TIndexBuildCallback \
-TIndexBulkDeleteCallback \
-TIndexBulkDeleteResult \
-TIndexElem \
-TIndexInfo \
-TIndexList \
-TIndexOptInfo \
-TIndexPath \
-TIndexScan \
-TIndexScanDesc \
-TIndexScanDescData \
-TIndexScanDescPtr \
-TIndexScanState \
-TIndexStmt \
-TIndexStrategy \
-TIndexStrategyData \
-TIndexTuple \
-TIndexTupleData \
-TIndirectBlock \
-TInhInfo \
-TInhOption \
-TInhPaths \
-TInsertIndexResult \
-TInsertIndexResultData \
-TInsertStmt \
-TInstrumentation \
-TInt8TransTypeData \
-TIntArray \
-TInt_yy_size_t \
-TInt_yy_state_type \
-TInterval \
-TInvalidationChunk \
-TInvalidationListHeader \
-TIpcMemoryId \
-TIpcMemoryKey \
-TIpcSemaphoreId \
-TIpcSemaphoreKey \
-TItem \
-TItemId \
-TItemIdData \
-TItemIdFlags \
-TItemLength \
-TItemOffset \
-TItemPointer \
-TItemPointerData \
-TIter \
-TJoin \
-TJoinExpr \
-TJoinInfo \
-TJoinPath \
-TJoinState \
-TJoinType \
-TJunkFilter \
-TKEYMAP_ENTRY \
-TKEYMAP_ENTRY_ARRAY \
-TKeyCode \
-TKeySuffix \
-TKeySym \
-TKeyWord \
-TKeymap \
-TLINE \
-TLOCK \
-TLOCKMASK \
-TLOCKMETHOD \
-TLOCKMETHODCTL \
-TLOCKMETHODTABLE \
-TLOCKMODE \
-TLOCKTAG \
-TLSEG \
-TLVRelStats \
-TLWLock \
-TLWLockId \
-TLWLockMode \
-TLargeObjectDesc \
-TLimit \
-TLimitState \
-TList \
-TListenStmt \
-TLoadStmt \
-TLocationIndex \
-TLockInfo \
-TLockInfoData \
-TLockRelId \
-TLockStmt \
-TLogicalTape \
-TLogicalTapeSet \
-TMask \
-TMaterial \
-TMaterialState \
-TMdfdVec \
-TMemoryContext \
-TMemoryContextData \
-TMemoryContextMethods \
-TMergeJoin \
-TMergeJoinState \
-TMergePath \
-TMsgType \
-TNUMCacheEntry \
-TNUMDesc \
-TNUMProc \
-TNUM_poz \
-TName \
-TNameData \
-TNestLoop \
-TNestLoopState \
-TNestPath \
-TNode \
-TNodeTag \
-TNotifyStmt \
-TNullTest \
-TNullTestType \
-TNumeric \
-TNumericData \
-TNumericDigit \
-TNumericVar \
-TOffset \
-TOffsetNumber \
-TOffsetVarNodes_context \
-TOid \
-TOidOptions \
-TOldstyle_fnextra \
-TOpType \
-TOpaque \
-TOpaqueData \
-TOper \
-TOperator \
-TOprInfo \
-TOutputContext \
-TOverflowPageAddress \
-TPATH \
-TPGFInfoFunction \
-TPGFunction \
-TPGLZ_DecompState \
-TPGLZ_Header \
-TPGLZ_HistEntry \
-TPGLZ_Strategy \
-TPGShmemHeader \
-TPG_LocaleCategories \
-TPGconn \
-TPGnotify \
-TPGresult \
-TPOLYGON \
-TPQArgBlock \
-TPQExpBuffer \
-TPQExpBufferData \
-TPQconninfoOption \
-TPQnoticeProcessor \
-TPQprintOpt \
-TPROC \
-TPROC_HDR \
-TPROC_QUEUE \
-TPacket \
-TPacketDoneProc \
-TPacketLen \
-TPacketState \
-TPage \
-TPageHeader \
-TPageHeaderData \
-TPageManagerMode \
-TPageOffset \
-TParam \
-TParamExecData \
-TParamListInfo \
-TParamListInfoData \
-TParamNo \
-TParseState \
-TPasswordPacket \
-TPasswordPacketV0 \
-TPath \
-TPathKeyItem \
-TPathKeysComparison \
-TPattern_Prefix_Status \
-TPattern_Type \
-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 \
-TPixmap \
-TPlan \
-TPoint \
-TPointer \
-TPool \
-TPort \
-TPortal \
-TPortalData \
-TPortalHashEnt \
-TPostgresPollingStatusType \
-TPrintExtraTocPtr \
-TPrintTocDataPtr \
-TPrinttupAttrInfo \
-TPrivGrantee \
-TProcState \
-TProcedureStmt \
-TProcessingMode \
-TProjectionInfo \
-TProtocolVersion \
-TPsqlSettings \
-TQuery \
-TQueryDesc \
-TRI_OpreqHashEntry \
-TRI_QueryHashEntry \
-TRI_QueryKey \
-TRTBuildState \
-TRTSTACK \
-TRTSTATE \
-TRTScanList \
-TRTScanListData \
-TRTreePageOpaque \
-TRTreePageOpaqueData \
-TRTreeScanOpaque \
-TRTreeScanOpaqueData \
-TRangeQueryClause \
-TRangeSubselect \
-TRangeTblEntry \
-TRangeTblRef \
-TRangeVar \
-TRawColumnDefault \
-TReadBufPtr \
-TReadBytePtr \
-TReadExtraTocPtr \
-TRecipeStmt \
-TRegProcedure \
-TReindexStmt \
-TRelFileNode \
-TRelIdCacheEnt \
-TRelNameCacheEnt \
-TRelNodeCacheEnt \
-TRelOptInfo \
-TRelabelType \
-TRelation \
-TRelationBuildDescInfo \
-TRelationData \
-TRelationPtr \
-TRelativeTime \
-TRelids \
-TRemoveAggrStmt \
-TRemoveFuncStmt \
-TRemoveOperStmt \
-TRenameStmt \
-TResTarget \
-TResdom \
-TResolveNew_context \
-TRestoreOptions \
-TRestrictInfo \
-TResult \
-TResultRelInfo \
-TResultState \
-TRetrieveIndexResult \
-TRetrieveIndexResultData \
-TReturnSetInfo \
-TRewriteRule \
-TRmgrData \
-TRmgrId \
-TRuleLock \
-TRuleStmt \
-TSEMA \
-TSEM_MAP_ENTRY \
-TSHMEM_OFFSET \
-TSHM_QUEUE \
-TSISeg \
-TSPITupleTable \
-TSPLITCOST \
-TSPLITVEC \
-TSQLFunctionCache \
-TSQLFunctionCachePtr \
-TSaveArchivePtr \
-TScalarItem \
-TScalarMCVItem \
-TScan \
-TScanDirection \
-TScanKey \
-TScanKeyData \
-TScanKeyword \
-TScreen \
-TScreenFormat \
-TSelectStmt \
-TSelectivity \
-TSeqScan \
-TSeqTable \
-TSeqTableData \
-TSetOp \
-TSetOpCmd \
-TSetOpState \
-TSetOperation \
-TSetOperationStmt \
-TSharedInvalCatcacheMsg \
-TSharedInvalRelcacheMsg \
-TSharedInvalidationMessage \
-TShmemIndexEnt \
-TSigHandler \
-TSize \
-TSnapshot \
-TSnapshotData \
-TSockAddr \
-TSort \
-TSortClause \
-TSortFunctionKind \
-TSortGroupBy \
-TSortState \
-TSplitNumber \
-TStandardChunkHeader \
-TStartBlobPtr \
-TStartBlobsPtr \
-TStartDataPtr \
-TStartUpID \
-TStartupPacket \
-TStrategyEvaluation \
-TStrategyEvaluationData \
-TStrategyExpression \
-TStrategyExpressionData \
-TStrategyMap \
-TStrategyMapData \
-TStrategyNumber \
-TStrategyOperator \
-TStrategyOperatorData \
-TStrategyTerm \
-TStrategyTermData \
-TStrategyTransformMap \
-TStrategyTransformMapData \
-TStream \
-TStreamPtr \
-TStringInfo \
-TStringInfoData \
-TSubLink \
-TSubLinkType \
-TSubPlan \
-TSubqueryScan \
-TSubqueryScanState \
-TTAR_MEMBER \
-TTableInfo \
-TTargetEntry \
-TTcl_AppInitProc \
-TTcl_AsyncHandler \
-TTcl_AsyncProc \
-TTcl_CallFrame \
-TTcl_Channel \
-TTcl_ChannelProc \
-TTcl_ChannelType \
-TTcl_CloseProc \
-TTcl_CmdDeleteProc \
-TTcl_CmdInfo \
-TTcl_CmdProc \
-TTcl_CmdTraceProc \
-TTcl_Command \
-TTcl_DString \
-TTcl_DriverBlockModeProc \
-TTcl_DriverCloseProc \
-TTcl_DriverGetHandleProc \
-TTcl_DriverGetOptionProc \
-TTcl_DriverInputProc \
-TTcl_DriverOutputProc \
-TTcl_DriverSeekProc \
-TTcl_DriverSetOptionProc \
-TTcl_DriverWatchProc \
-TTcl_DupInternalRepProc \
-TTcl_EolTranslation \
-TTcl_Event \
-TTcl_EventCheckProc \
-TTcl_EventDeleteProc \
-TTcl_EventProc \
-TTcl_EventSetupProc \
-TTcl_ExitProc \
-TTcl_FileFreeProc \
-TTcl_FileProc \
-TTcl_FreeInternalRepProc \
-TTcl_FreeProc \
-TTcl_HashEntry \
-TTcl_HashSearch \
-TTcl_HashTable \
-TTcl_IdleProc \
-TTcl_Interp \
-TTcl_InterpDeleteProc \
-TTcl_MathProc \
-TTcl_Namespace \
-TTcl_NamespaceDeleteProc \
-TTcl_Obj \
-TTcl_ObjCmdProc \
-TTcl_ObjType \
-TTcl_PackageInitProc \
-TTcl_PathType \
-TTcl_Pid \
-TTcl_QueuePosition \
-TTcl_RegExp \
-TTcl_SetFromAnyProc \
-TTcl_TcpAcceptProc \
-TTcl_Time \
-TTcl_TimerProc \
-TTcl_TimerToken \
-TTcl_Trace \
-TTcl_UpdateStringProc \
-TTcl_Value \
-TTcl_ValueType \
-TTcl_Var \
-TTcl_VarTraceProc \
-TTempTable \
-TThingFile \
-TTidPath \
-TTidScan \
-TTidScanState \
-TTime \
-TTimeADT \
-TTimeInterval \
-TTimeIntervalData \
-TTimeTzADT \
-TTimestamp \
-TTimestampTz \
-TTk_3DBorder \
-TTk_Anchor \
-TTk_ArgvInfo \
-TTk_BindingTable \
-TTk_Canvas \
-TTk_CanvasTextInfo \
-TTk_ConfigSpec \
-TTk_Cursor \
-TTk_CustomOption \
-TTk_ErrorHandler \
-TTk_ErrorProc \
-TTk_EventProc \
-TTk_FakeWin \
-TTk_Font \
-TTk_FontMetrics \
-TTk_GenericProc \
-TTk_GeomLostSlaveProc \
-TTk_GeomMgr \
-TTk_GeomRequestProc \
-TTk_GetSelProc \
-TTk_Image \
-TTk_ImageChangedProc \
-TTk_ImageCreateProc \
-TTk_ImageDeleteProc \
-TTk_ImageDisplayProc \
-TTk_ImageFileMatchProc \
-TTk_ImageFileReadProc \
-TTk_ImageFileWriteProc \
-TTk_ImageFreeProc \
-TTk_ImageGetProc \
-TTk_ImageMaster \
-TTk_ImageStringMatchProc \
-TTk_ImageStringReadProc \
-TTk_ImageStringWriteProc \
-TTk_ImageType \
-TTk_Item \
-TTk_ItemAreaProc \
-TTk_ItemConfigureProc \
-TTk_ItemCoordProc \
-TTk_ItemCreateProc \
-TTk_ItemCursorProc \
-TTk_ItemDCharsProc \
-TTk_ItemDeleteProc \
-TTk_ItemDisplayProc \
-TTk_ItemIndexProc \
-TTk_ItemInsertProc \
-TTk_ItemPointProc \
-TTk_ItemPostscriptProc \
-TTk_ItemScaleProc \
-TTk_ItemSelectionProc \
-TTk_ItemTranslateProc \
-TTk_ItemType \
-TTk_Justify \
-TTk_LostSelProc \
-TTk_OptionParseProc \
-TTk_OptionPrintProc \
-TTk_PhotoHandle \
-TTk_PhotoImageBlock \
-TTk_PhotoImageFormat \
-TTk_RestrictAction \
-TTk_RestrictProc \
-TTk_SelectionProc \
-TTk_TextLayout \
-TTk_Uid \
-TTk_Window \
-TTmFromChar \
-TTmToChar \
-TTocEntry \
-TTocSortCompareFn \
-TTrackItem \
-TTransactionId \
-TTransactionState \
-TTransactionStateData \
-TTransactionStmt \
-TTrigInfo \
-TTrigger \
-TTriggerData \
-TTriggerDesc \
-TTriggerEvent \
-TTruncateStmt \
-TTupSortStatus \
-TTupStoreStatus \
-TTupleConstr \
-TTupleDesc \
-TTupleTable \
-TTupleTableData \
-TTupleTableSlot \
-TTuplesortstate \
-TTuplestorestate \
-TType \
-TTypeCast \
-TTypeInfo \
-TTypeName \
-TUNDO_LIST \
-TUnique \
-TUniqueState \
-TUnlistenStmt \
-TUpdateStmt \
-TUserAuth \
-TVFunction \
-TVRelList \
-TVRelListData \
-TVRelStats \
-TVTupleLink \
-TVTupleLinkData \
-TVTupleMove \
-TVTupleMoveData \
-TVacAttrStats \
-TVacPage \
-TVacPageData \
-TVacPageList \
-TVacPageListData \
-TVacRUsage \
-TVacuumStmt \
-TValue \
-TVar \
-TVarBit \
-TVarChar \
-TVariableCache \
-TVariableCacheData \
-TVariableResetStmt \
-TVariableSetStmt \
-TVariableShowStmt \
-TVariableSpace \
-TVersionStmt \
-TVfd \
-TViewStmt \
-TVisual \
-TVisualID \
-TWAIT_ORDER \
-TWindow \
-TWriteBufPtr \
-TWriteBytePtr \
-TWriteDataPtr \
-TWriteExtraTocPtr \
-TXActivateDeactivateEvent \
-TXActivateEvent \
-TXAnyEvent \
-TXArc \
-TXButtonEvent \
-TXButtonPressedEvent \
-TXButtonReleasedEvent \
-TXChar2b \
-TXCharStruct \
-TXCirculateEvent \
-TXCirculateRequestEvent \
-TXClientMessageEvent \
-TXColor \
-TXColormapEvent \
-TXConfigureEvent \
-TXConfigureRequestEvent \
-TXConnectionWatchProc \
-TXCreateWindowEvent \
-TXCrossingEvent \
-TXDeactivateEvent \
-TXDestroyWindowEvent \
-TXEDataObject \
-TXEnterWindowEvent \
-TXErrorEvent \
-TXErrorHandler \
-TXEvent \
-TXExposeEvent \
-TXExtCodes \
-TXExtData \
-TXFocusChangeEvent \
-TXFocusInEvent \
-TXFocusOutEvent \
-TXFontProp \
-TXFontSet \
-TXFontSetExtents \
-TXFontStruct \
-TXGCValues \
-TXGraphicsExposeEvent \
-TXGravityEvent \
-TXHostAddress \
-TXIC \
-TXICCallback \
-TXICProc \
-TXID \
-TXIDProc \
-TXIM \
-TXIMCallback \
-TXIMCaretDirection \
-TXIMCaretStyle \
-TXIMFeedback \
-TXIMHotKeyState \
-TXIMHotKeyTrigger \
-TXIMHotKeyTriggers \
-TXIMPreeditCaretCallbackStruct \
-TXIMPreeditDrawCallbackStruct \
-TXIMPreeditState \
-TXIMPreeditStateNotifyCallbackStruct \
-TXIMProc \
-TXIMResetState \
-TXIMStatusDataType \
-TXIMStatusDrawCallbackStruct \
-TXIMStringConversionCallbackStruct \
-TXIMStringConversionFeedback \
-TXIMStringConversionOperation \
-TXIMStringConversionPosition \
-TXIMStringConversionText \
-TXIMStringConversionType \
-TXIMStyle \
-TXIMStyles \
-TXIMText \
-TXIMValuesList \
-TXIOErrorHandler \
-TXImage \
-TXKeyEvent \
-TXKeyPressedEvent \
-TXKeyReleasedEvent \
-TXKeyboardControl \
-TXKeyboardState \
-TXKeymapEvent \
-TXLeaveWindowEvent \
-TXLogContRecord \
-TXLogCtlData \
-TXLogCtlInsert \
-TXLogCtlWrite \
-TXLogPageHeader \
-TXLogPageHeaderData \
-TXLogRecData \
-TXLogRecPtr \
-TXLogRecord \
-TXLogRelCacheEntry \
-TXLogRelDesc \
-TXLogwrtResult \
-TXLogwrtRqst \
-TXMapEvent \
-TXMapRequestEvent \
-TXMappingEvent \
-TXModifierKeymap \
-TXMotionEvent \
-TXNoExposeEvent \
-TXOC \
-TXOM \
-TXOMCharSetList \
-TXOMFontInfo \
-TXOMOrientation \
-TXOrientation \
-TXPixmapFormatValues \
-TXPoint \
-TXPointer \
-TXPointerMovedEvent \
-TXPropertyEvent \
-TXRectangle \
-TXReparentEvent \
-TXResizeRequestEvent \
-TXSegment \
-TXSelectionClearEvent \
-TXSelectionEvent \
-TXSelectionRequestEvent \
-TXSetWindowAttributes \
-TXTextItem \
-TXTextItem16 \
-TXTimeCoord \
-TXUnmapEvent \
-TXVaNestedList \
-TXVirtualEvent \
-TXVisibilityEvent \
-TXWindowAttributes \
-TXWindowChanges \
-TXidStatus \
-TXmbTextItem \
-TXwcTextItem \
-TYYSTYPE \
-TYY_BUFFER_STATE \
-TYY_CHAR \
-T_LIB_VERSION_TYPE \
-T_RuneEntry \
-T_RuneLocale \
-T_RuneRange \
-T_SPI_connection \
-T_SPI_plan \
-T_XPrivDisplay \
-Taclitem \
-Tadjust_inherited_attrs_context \
-Talloc_func \
-Tassoc_list \
-Tattribute_used_context \
-TbackslashResult \
-Tbits16 \
-Tbits32 \
-Tbits8 \
-Tbool \
-Tbool16 \
-Tbool32 \
-Tbool8 \
-Tbytea \
-Tcaddr_t \
-Tcat_t \
-Tcc_t \
-Tchar \
-Tcharf \
-Tcheck_ungrouped_columns_context \
-Tclock_t \
-Tclockid_t \
-Tcodes_t \
-Tcontain_var_reference_context \
-Tcrc64 \
-Tcset \
-Tdaddr_t \
-Tdatetkn \
-Tdeparse_context \
-Tdeparse_namespace \
-Tdev_t \
-Tdiv_t \
-Tdouble \
-TevalPlanQual \
-TexecRowMark \
-Texecution_state \
-Tf_smgr \
-Tfd_mask \
-Tfd_set \
-Tfinalize_primnode_results \
-Tfixpt_t \
-Tfloat \
-Tfloat32 \
-Tfloat32data \
-Tfloat4 \
-Tfloat64 \
-Tfloat64data \
-Tfloat8 \
-TformatLiteralOptions \
-Tfp_except \
-Tfp_rnd \
-Tfpclass_t \
-Tfpos_t \
-Tfree_func \
-Tfrom_mic_converter \
-Tfunc_ptr \
-Tgid_t \
-TgzFile \
-Thashnode \
-ThbaPort \
-Tin_addr_t \
-Tin_port_t \
-Tinet \
-Tinet_struct \
-Tino_t \
-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 \
-Tjmp_buf \
-Tjoin_references_context \
-Tkey_t \
-TlclContext \
-TlclTocEntry \
-Tldiv_t \
-Tmacaddr \
-Tmb2wchar_with_len_converter \
-Tmblen_converter \
-Tmode_t \
-Tnlink_t \
-Toff_t \
-Toidvector \
-ToptType \
-Tpg_enc \
-Tpg_enc2name \
-Tpg_encname \
-Tpg_enconv \
-Tpg_local_to_utf \
-Tpg_pwd \
-Tpg_utf_to_local \
-Tpg_wchar \
-Tpg_wchar_tbl \
-Tpgsql_thing_t \
-Tpid_t \
-Tpqbool \
-Tpqsigfunc \
-TprintQueryOpt \
-TprintTableOpt \
-TpromptStatus_t \
-Tptrdiff_t \
-Tpull_var_clause_context \
-Tpull_varnos_context \
-Tq128_t \
-Tqaddr_t \
-Tquad_t \
-TrangeTableEntry_used_context \
-Tregex_t \
-Tregister_t \
-Tregmatch_t \
-Tregoff_t \
-Tregproc \
-Treplace_vars_with_subplan_refs_context \
-Trune_t \
-Tsa_family_t \
-Tsegsz_t \
-Tsequence_magic \
-Tsig_atomic_t \
-Tsig_t \
-Tsighandler_cxt \
-Tsigjmp_buf \
-Tsigset_t \
-Tsize_t \
-Tslock_t \
-Tsmgrid \
-Tsocklen_t \
-Tsop \
-Tsopno \
-Tspeed_t \
-TsqlparseInfo \
-TsqlparseState \
-Tssize_t \
-Tstack_t \
-Tswblk_t \
-Ttcflag_t \
-Ttcp_seq \
-Ttext \
-Ttime_t \
-Tto_mic_converter \
-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 \
-Tuch \
-Tuid_t \
-Tuint \
-Tuint16 \
-Tuint32 \
-Tuint64 \
-Tuint8 \
-Tushort \
-Tva_list \
-Tvarattrib \
-Tvm_offset_t \
-Tvm_size_t \
-Tvoid \
-Tvoidp \
-Tvoidpf \
-Twchar_t \
-Tword16 \
-Tword32 \
-Tword8 \
-Txl_btree_delete \
-Txl_btree_insert \
-Txl_btree_newroot \
-Txl_btree_split \
-Txl_btreetid \
-Txl_heap_clean \
-Txl_heap_delete \
-Txl_heap_header \
-Txl_heap_insert \
-Txl_heap_update \
-Txl_heaptid \
-Txl_seq_rec \
-Txl_xact_abort \
-Txl_xact_commit \
-Tyy_size_t \
-Tyy_state_type \
-Tz_stream \
-Tz_streamp \
-TBOOKMARK \
-TBOOL \
-TBYTE \
-TBindInfoClass \
-TCOL_INFO \
-TCONN_Status \
-TColumnInfoClass \
-TConnInfo \
-TConnectionClass \
-TDATE_STRUCT \
-TDWORD \
-TDataSourceToDriverProc \
-TDriverToDataSourceProc \
-TEnvironmentClass \
-TFIELD_INFO \
-TFILE \
-TGLOBAL_VALUES \
-THDBC \
-THENV \
-THSTMT \
-THWND \
-TLO_ARG \
-TLPARAM \
-TOid \
-TPTR \
-TParameterInfoClass \
-TProtocolVersion \
-TQResultClass \
-TQueryInfo \
-TQueryResultCode \
-TRETCODE \
-TSDOUBLE \
-TSDWORD \
-TSFLOAT \
-TSIMPLE_TIME \
-TSQLBIGINT \
-TSQLCHAR \
-TSQLDOUBLE \
-TSQLFLOAT \
-TSQLGUID \
-TSQLINTEGER \
-TSQLINTERVAL \
-TSQLREAL \
-TSQLSCHAR \
-TSQLSMALLINT \
-TSQLUBIGINT \
-TSQLUINTEGER \
-TSQLUSMALLINT \
-TSQL_DATE_STRUCT \
-TSQL_DAY_SECOND_STRUCT \
-TSQL_INTERVAL_STRUCT \
-TSQL_TIMESTAMP_STRUCT \
-TSQL_TIME_STRUCT \
-TSQL_YEAR_MONTH_STRUCT \
-TSSHOR \
-TSTMT_Status \
-TSWORD \
-TSocketClass \
-TStartupPacket \
-TStartupPacket6_2 \
-TStatementClass \
-TStatementOptions \
-TTABLE_INFO \
-TTIMESTAMP_STRUCT \
-TTIME_STRUCT \
-TTupleField \
-TTupleListClass \
-TTupleNode \
-TUCHAR \
-TUDWORD \
-TUWORD \
-TWORD \
-TWPARAM \
-T_LIB_VERSION_TYPE \
-T_RuneEntry \
-T_RuneLocale \
-T_RuneRange \
-Tcaddr_t \
-Tchar \
-Tclock_t \
-Tclockid_t \
-Tdaddr_t \
-Tdev_t \
-Tdiv_t \
-Tdouble \
-Tfd_mask \
-Tfd_set \
-Tfixpt_t \
-Tfloat \
-Tfpos_t \
-Tgid_t \
-Tin_addr_t \
-Tin_port_t \
-Tino_t \
-Tint \
-Tint16_t \
-Tint16m_t \
-Tint32_t \
-Tint32m_t \
-Tint64_t \
-Tint64m_t \
-Tint8_t \
-Tint8m_t \
-Tkey_t \
-Tldiv_t \
-Tmode_t \
-Tnlink_t \
-Toff_t \
-Tpid_t \
-Tq128_t \
-Tqaddr_t \
-Tquad_t \
-Tregister_t \
-Trune_t \
-Tsa_family_t \
-Tsegsz_t \
-Tsig_atomic_t \
-Tsig_t \
-Tsigset_t \
-Tsize_t \
-Tslock_t \
-Tsocklen_t \
-Tssize_t \
-Tstack_t \
-Tswblk_t \
-Ttime_t \
-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 \
-Tuid_t \
-Tuint \
-Tushort \
-Tva_list \
-Tvm_offset_t \
-Tvm_size_t \
-Tvoid \
-Twchar_t \
/tmp/$$a >/tmp/$$ 2>&1
	if [ "$?" -ne 0 -o -s /tmp/$$ ]
	then	echo
		echo "$FILE"
		cat /tmp/$$
	fi
	cat /tmp/$$a |
	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
	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 #endif
	awk '	BEGIN	{line1 = ""; line2 = ""; skips = 0}
		{
			line2 = $0;
			if (skips > 0)
				skips--;
			if (line1 ~ "^$" &&
			    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
