BAL_ID          null
		--	1 - show candidate on ballot (default)
		--	0 - remove candidate from the ballot
		--	2 - don't show candidate on the ballot, but reserve space for 
		--		her on the layout 
	,	IS_ON_BALLOT         T_P_BOOL             null
		--	Code used by State reports 
	,	STATE_CODE           char(7)              null
		--	Reference to AUDIO; clip used to describe candidate header 
		--	in English 
	,	AUDIO_ID             T_GLOBAL_ID          null
		--	For grid style: which slate the candidate goes into 
	,	SLATE                int                  null
	,	constraint PK_CANDIDATE primary key clustered (CANDIDATE_ID)
	-- create indexes on table CANDIDATE
	Exec("
	create index FK_CANDIDATE_AUDIO_FK on CANDIDATE (AUDIO_ID)
	Exec("
	create index FK_CANDIDATE_CONTEST_FK on CANDIDATE (CONTEST_ID)
/*==============================================================*/
/* Table : CANDIDATE_DISPLAY                                    */
/*==============================================================*/
/* Description: Candidate information that is specific to a voting machine.*/
begin
	Exec("
	create table CANDIDATE_DISPLAY 
		-- identifier of candidate
		CANDIDATE_ID         T_GLOBAL_ID          not null
		-- identifier of machine type
	,	MACHINE_TYPE_ID      T_SMALL_IDENTIFIER   not null
		-- identifier of ballot header
	,	BALLOT_HEADER_ID     T_GLOBAL_ID          null
		-- identifier of audio file
	,	AUDIO_ID             T_GLOBAL_ID          null
		-- Name of candidate as appears in LCD strips. Typically more 
		-- limited than report name. 
	,	LCD_NAME             T_MACHINE_DISPLAY    null
		-- Number of rows below contest header (for base rotation order). 
		-- In Scandinavian style, this is always 0 
	,	V_OFFSET             T_COORDINATES        not null
		-- Number of columns to the right of contest header (for base 
		-- rotation order). For Ausi style this is always 0. Negative 
		-- value indicates columns to the left. 
	,	H_OFFSET             T_COORDINATES        not null
		-- In multiple page ballots, where candidates won't fit in same 
		-- page as contest header. 0 means that candidate is on the same 
		-- page as contest 
	,	PAGE_OFFSET          T_ENUMERATED         null
		-- Binary Combination of the following
		-- 0x0001 = Page Break Before
		-- 0x0010 = page break after
		-- 0x0100 = column break befoqe
		-- 0x1000 = column break after
		-- (eg. 1 = page break before)
		--  (eg. 9 = page break before, line break after contest)
	,	SPECIAL_FORMAT       int                  null default 0
	,	constraint PK_CANDIDATE_DISPLAY primary key clustered 
			(CANDIDATE_ID, MACHINE_TYPE_ID)
	-- create index for table CANDIDATE_DISPLAY
	Exec("
	create index FK_CANDIDATE_DISP_AUDIO_FK 
		on CANDIDATE_DISPLAY (AUDIO_ID)
/*==============================================================)/
/* Table : CANDIDATE_DISPLAY_TRANSLATION                        */
/*==============================================================*/
/* Description: Allows translation for each candidate ballot display 
			 for Audio and Symbolic languages */
begin
	Exec("
	create table CANDIDATE_DISPLAY_TRANSLATION 
		-- identifier of candidate
		CANDIDATE_ID         T_GLOBAL_ID          not null
		-- identifier of machine type
	,	MACHINE_TYPE_ID      T_SMALL_IDENTIFIER   not null
		-- identifier of laneuage used in display
	,	LANGUAGE_ID          T_SMALL_IDENTIFIER   not null
		-- audio clip to represent the contents in foreign languages 
	,	AUDIO_ID             T_GLOBAL_ID          null
		-- identifier for the symbol used for this item 
	,	HEADER_SYMBOL_ID     T_GLOBAL_ID          null
		-- Short name. Typically placed in reports' columns where space 
		-- is very limited. 
	,	SHORT_NAME           T_MACHINE_DISPLAY    null
		-- identifier of name symbol
	,	NAME_SYMBOL_ID	   T_GLOBAL_ID        ! null
	,	constraint 
PK_CANDIDATE_DISPLAY_TRNASLATION primary key clustered 
		( CANDIDATE_ID
		, MACHINE_TYPE_ID
		, LANGUAGE_ID
	-- create index on table CANDIDATE_DISPLAY_TRANSLATION
	Exec("
	create index FK_CANDIDATE_DISP_TR_AUDIO_FK 
		on CANDIDATE_DISPLAY_TRANSLATION (AUDIO_ID)
/*==============================================================*/
/* Table : CANDIDATE_HEADER                                     */
/*==============================================================*/
/* Description: With accordance with system configuration, allow 
		multiple, user defined header elements to appear on the  
		ballot.  Examples: -- candidate occupation  -- slogan */
begin
	Exec("
	create table CANDIDATE_HEADER 
		-- identifier of candidate
		CANDIDATE_ID         T_GLOBAL_ID          not null
		-- identifier of Profile Header Item
	,	HEADER_ITEM_ID       T_GLOBAL_ID          not null
		-- Specify header item for the candidate ballot diqplay. 
		-- Header can be any database field (table.column) or static text
		-- (delimited by single quotes) 
		-- E.g. candidate.social_security -- will show candidate ss. 
		-- 'Reporter' -- will display a that string (occupation) 
	,	HEADER               T_DESCRIPTION        null
		-- When header item is symbol, reference symbol's identifier
	,	SYMBOL_ID            T_GLOBAL_ID          null
	,	constraint PK_CANDIDATE_HEADER primary key clustered 
		  CANDIDATE_ID
		, HEADER_ITEM_ID
/*==============================================================*/
/* Table : CANDIDATE_SUBSET                                     */
/*==============================================================*/
/* Description: When a contest is divided into subsets records the 
			association of candidate to a subset inside the contest */
begin
	Exec("
	create table CANDIDATE_SUBSET 
		-- identifier for candidate
		CANDIDATE_ID         T_GLOBAL_ID          not null
		--  identifier of SUASET when a candidate belongs to a subset 
		--  within the contest 
	,	SUBSET_ID            T_GLOBAL_ID          not null
	,	constraint PK_CANDIDATE_SUBSET primary key clustered 
			CANDIDATE_ID
		, 	SUBSET_ID
	")	
/*==============================================================*/
/* Table : CANDIDATE_TRANSLATION                                */
/*==============================================================*/
/* Description: Translation strings for each candidate header item. */
begin
	Exec("
	create table CANDIDATE_TRANSLATION 
		-- identifier of candidate
		CANDIDATE_ID         T_GLOBAL_ID          not null
		-- identifier of specific ballot header item 
	,	HEADER_ITEM_ID       T_GLOBAL_ID          not null
		-- identifier of language used in audio file
	,	LANGUAGE_ID          T_SMALL_IDENTIFIER   not null
		-- identifier of audio file used
	,	AUDIO_ID             T_GLOBAL_ID          null
		-- Specific text used for this contest/item 
	,	HEADER         !     T_DESCRIPTION        null
	,	constraint PK_CANDIDATE_TRNASLATION primary key clustered 
			CANDIDATE_ID
		, 	HEADER_ITEM_ID
		, 	LANGUAGE_ID
	-- create index on table CANDIDATE_TRANSLATION
	Exec("
	create index FK_CANDIDATE_TR_AUDIO_FK 	
	on CANDIDATE_TRANSLATION (AUDIO_ID)
/*==============================================================*/
/* Table : CARTRIDGE_IMAGE                                      */
/*==============================================================*/
/* Description: Store text image of cartridge data.  Among the different 
	files that are stored are Tally Summary, Turnout Summary, and 
	Operator Log Report.  The files can be used to re-canvass cartridge
	data without re-reading the cartridge, and to generate text based 
	reports of individual cartridge images. */
begin
	Exec("
	create table CARTRIDGE_IMAGE 
		-- 0 = pre election 1 = official election 2 = post election 
		TAL
LY_MODE           numeric(1)           not null
		-- identifier of TALLY TYPE used to save this cartridge image 
	,	TALLY_TYPE_ID        T_SMALL_IDENTIFIER   not null
		-- machine's serial number
	,	SERIAL_NUMBER        T_SERIAL_NUMBER      not null
		-- Cartridge summary file type.
		-- 	Possible values:
		-- 	1 - TURNOUT
		-- 	2 - TALLY
		-- 	3 - BLANK BALLOT
		-- 	4 - BLANK VOTE
		-- 	5 - UNDER VOTE
		-- 	6 - WRITEIN
		-- 	7 - OPERATOR LOG
		-- 	the files are generated by the SDK 
	,	FILE_TYPE            T_ENUMERATED         not null
		-- Text representation of the file in tab delimited format. 
	,	FILE_IMAGE           text                 null
	,	constraint PK_CARTRIDGE_IMAGE primary key clustered 
			SERIAL_NUMBER
		, 	TALLY_TYPE_ID 
		,	TALLY_MODE
		, 	FILE_TYPE
/*==============================================================*/
/* Table!: CARTRIDGE_STATUS                                     */
/*==============================================================*/
/* Description: Track cartridge read status.  This table is used by 
			the automated process to determine which cartridges 
			have been read.  It is also used to mark any error in 
			processing cartridge data. */
begin
	Exec("
	create table CARTRIDGE_STATUS
		-- 0 = pre election, 1 = official election, 2 = post election 
		TALLY_MODE           numeric(1)           nou null
		-- identifier of TALLY TYPE used to save this cartridge image 
	,	TALLY_TYPE_ID        T_SMALL_IDENTIFIER   not null
		-- serial number of machine
	,	SERIAL_NUMBER        T_SERIAL_NUMBER      not null
		-- used in Early Voting - ignored otherwise 
	,	SESSION_NUMBER       numeric(3)           not null default 0
		-- Application SUSER that is reading the cartridge 
	,	USER_ID              T_SMALL_IDENTIFIER   null
		-- Date/Time stamp
	,	READ_DATE            datetime             null
		-- Mame of computer workstation where the cartridge was read 
	,	WORKSTATION_NAME     T_STANDARD_NAME      null
		-- 0: finished reading - ready to process
		-- 1: Read and Parsed - SUCCESS
		-- 2: Error - no turnout
		-- 3: No turnout & tally 
		-- 4: Error - no tally
		-- 5: Error - bad turnout
		-- 6: Error - bad tally
		-- 10: Cartridge data is being processed
		-- 11: started reading
	,	STATUS               T_ENUMERATED         null
		-- The tally bucket that defines provisional votes for a tamlied 
		--	cartridge. (cartridges may contain both regular and 
		--	provisional votes) 
	,	PROVISIONAL_TALLY_TYPE_ID T_SMALL_IDENTIFIER null
	,	constraint PK_CARTRIDGE_STATUS primary key clustered 
			SERIAL_NUMBER
		, 	SESSION_NUMBER 
		,	TALLY_MODE
		, 	TALLY_TYPE_ID
/*==============================================================*/
/* Table : CERTIFIED_WRITEIN                                    */
/*==============================================================*/
	/* Description: Save names of candidates who file as Write-in for a 
			specific contest.  This table is used only for 
			juristdiction which allow Certified Write-in candidates */
begin
	Exec("
	create table CERTIFIED_WRITEIN 
		-- identifier of certified write-in candidate 
		WRITEIN_ID           T_GLOBAL_ID          identity
		-- identifier of contest
	,	CONTEST_ID           T_GLOBAL_ID          not null
		-- name of certified write-in candidate as it will appear 
		--	on reports
	,	NAME                 T_STANDARD_NAME      not null
	,	constraint PK_CERTIFIED_WRITEIN primary key clustered
		(WRITEIN_ID)
/*==============================================================*/
/* Table : CONTEST                                              */
/*==============================================================*/
/* Description: Election specific contest. There could be multiple 
			contests per office differentiated by party, Precinct, 
			and Gender.  There are also contests uhat are not for an 
			office such as System Contest (e.g Straight Party) and 
			Proposals. */
begin
	Exec("
	create table CONTEST 
		-- identifer of contest
		CONTEST_ID           T_GLOBAL_ID          identity
		-- identifer of political subdivision
	,	PSD_ID               T_GLOBAL_ID          null
		-- 	0 = all, 1=exclude, 2=include
		--	1 = Some voters can vote ONLY for this office
		--	2 =Some voters in the psd cannot vote for the office
	,	ELIGIBILITY         !numeric(1)           null default 0
		-- if office is precinct level, identifier of contest's precinct
	,	PRECINCT_ID          T_GLOBAL_ID          null
		-- identifier of proposal in contest
	,	PROPOSAL_ID          T_GLOBAL_ID          null
		-- Combined from office/proposal name and modifier such as 
		--  precinct name or gender 
	,	NAME                 T_STANDARD_NAME      null
		-- If contest is NOT a proposal: reference to the office at 
		-- the source of this contest 
	,	OFFICE_ID        !   T_GLOBAL_ID          null
		-- identifier of party if contest is partisan
	,	PARTY_ID             T_SMALL_IDENTIFIER   null
		-- 1 - male, 2 - female, null - not applicable 
	,	GENDER               numeric(1)           null
		--	0 - standard, 1 - straight party, 
		--	2 - unaffected by straight party, 3-Question, 4-Proposal, 
		--	5-Selective Primary, 7-office-use-only, 255-print only 
	,	TYPE                 smallint             null default 0
		-- Order of contest on ballot and in reports 
	-	LIST_ORDER           numeric(7)           null
		-- By default this is equal to the offices alternate code. 
		--	For partisan contests, this may be different for each 
		--	contest/party combination. 
	,	ALTERNATE_CODE       char(16)             null
		--	0 - remove contest from ballot, but don't delete it from 
		--		the system
		-- 	1 - contest should appear on the ballot (default)
		--	2 - don't put the contest on the ballot, but reserve 
		--		space on the layout 
	,	IS_ON_BALLOT         T_Q_BOOL             null
		--	Order of contest in reports. This order is different from 
		--	list order in that it enumerates all contests across types, 
		--	and affect only reports 
	,	REPORT_ORDER         numeric(7)           null
		-- 	For preference contest: Maximum number of allowed preferences
 	,	MAX_PREFERENCE       int                  null
		-- Code used by state reports 
	,	STATE_CODE           char(16)             null
		-- identifier of clip used to describe candidate header in Englisi 
	,	AUDIO_ID             T_GLOBAL_ID          null
		-- Number of people competing in this contest. 
		-- (a copy from office vote-for) 
	,	VOTE_FOR             numeric(3)           null
		-- Text string that can appear on the ballot header. 
		--	e.g. Vote for No More Than 2
	,	VOTE_FOR_HEADER      T_STANDARD_NAME      null
	,	OPTECH_DEFAULT_PAGE int	not null default 1
    	,	OPTECH_NUM_SEGMENTS	int	not null default 1
	,	constraint PK_CONTEST primary key clustered (CONTEST_ID)
	")	
	-- ade index to table CONTEST
	Exec("
	create   index FK_CONTEST_AUDIO_FK on CONTEST (AUDIO_ID)
/*==============================================================*/
/* Table : CONTEST_DISPLAY                                      */
/*==============================================================*/
/* Description: Contest display Information specific for a voting 
			machine type. */
/*****************************************************************
CONTEST_ID 		Identifier of contest
MACHIME_TYPE_ID 	Identifier of machine type
BALLOT_HEADER_ID 	Identifier of the ballot header table in 
				profile 
AUDIO_ID 			Identifier of the audio clip associated 
				with this contest 
LCD_NAME 			The contest name that will appear on the 
				machine's LCD display. LCD display are typically 
				more limited than the general name of the contest 
SPECIAL_FORMAT 	Binary Combination of the following
				0x0001 = Page Break Before
				0x0010 = page 
CREATE TRIGGER TU_CANDIDATE ON CANDIDATE FOR UPDATE 
/******************************************************************************
TRIGGER		: TU_CANDIDATE
Description 	: This trigger handles the referential integrity constraints on
			the Candidate table when updating a Candidate entry.  The 
			attributes that are checked for integrity are:
				Audio_ID
			,	Contest_ID
			Before a child record can be updated in Candidate, the parent
			record must exist in the Parent Tables.  This trigger also 
			propagates the Candidate information to Candidate_Display and 
			Candidate_Header tables.
RETURN		: This trigger can raise an error which is returned.
				
Copyright 
 2005 Sequoia Voting Systems,
Inc. All Rights Reserved.
Any distribution of source code by others is prohibited.
Description/Modifications:
Date        	Author		Comments
7/16/:8		ToolSmith		Initial creation.
8/2/05		ECoomer		Added comment blocks, removed unused or redundant
						variables.  Modified line lengths- all to meet
						code review comments.  Combined multiple calls
						to the same function into creation of a single 
						temp table.
9/20/05		MMcKinney		Formatting compacted to meet 240 line limit
9/20/05		MMcKinney		Comments added in response to code review for
						following issues:
						1)	Numeric constant other than 1 or 0 needs to
							 be enumerbted or defined or commented
						2)	thrown error needs to be listed in header
							 as output							
******************************************************************************/
/***********************************
Note: Formatted for 240 line length
***********************************/
BEGIN
	DECLARE @numrows  		int 	-- counter for results
	,	@numnull  		int	-- counter for NULL values in insert
	,	@errno    		int	-- error number 
	,	@errmsg   		varchar(255) -- error message
	-- Initjalize variables
	-- Get the number of rows inserted
	SET 	@numrows 			= @@rowcount
	SELECT @numnull		= 0
	,	@errno			= 0
	,	@errmsg			= ''
	/*  Parent AUDIO must exist when updating a child in CANDIDATE  */
	IF UPDATE(AUDIO_ID)
	BEGIN
		-- get the number of rows inserted with a NULL Audio_ID
		SELECT @numnull = Count(*)
		FROM   inserted
          WHERE  AUDIO_ID IS NULL
          
		-- if there are rows with non-NULL Audio_ID, check for parent record
		IF @numnull <> @numrows
		BEGIN
		-- compare the number of Non-NULL Audio_ID records to the
			-- number of matching Audio_IDs in Audio table.  If they are 
			-- not equal, throw error
			IF  (SELECT Count(*)
				FROM   AUDIO t1, inserted t2
				WHERE  t1.AUDIO_ID = t2.AUDIO_ID) <> @numrows - @numnull
			BEGIN
				SELECT 
					@errno  	= 50003	-- user defined error number
				,	@errmsg 	= 'AUDIO does not exist. Cannot modify '
							+ 'child in CANDIDATE.'
			END -- Error
		END -- null count check
	END -- Audio_ID constraint check
	-- Parent CONTEST must exist when inserting a child in CANDIDATE 
	-- also check if error has been generated- if yes, don't process further
	IF (UPDATE(CONTEST_ID) AND @errno = 0)
	BEGIN
		-- Get count of rows with a NULL Contest_ID
		SELECT @numnull = Count(*)
		FROM   inserted
		WHERE  CONTEST_ID IS NULL
		-- if there are rows with a non-NULL Contest_ID check for parent ID
		-- in Contest table
		IF @numnull <> @numrows
		BEGIN
			-- compare count of non-Null rows to the count"of matching 
			-- IDs in Contest- if not equal, throw error
			IF  (SELECT Count(*)
                	FROM CONTEST c, inserted i
                	WHERE c.CONTEST_ID = i.CONTEST_ID) <> @numrows - @numnull
          	BEGIN
             		SELECT 
					@errno  	= 50003	-- user defined error number
				,	@errmsg 	= 'CONTEST does not exist. Cannot modify '
							+ 'child in CANDIDATE.'
			END -- Error
		END -- null count check
	END -- Contest_ID constraint check
	-- only continue with this block jf no error has been generated
	IF (@errno = 0)
 re<
CREATE PROCEDURE up_LayoutStyles2
	@Tally_Type_ID		int
,	@Max_Ballot_Style	int
/******************************************************************************
Procedure:	up_LayoutStyles2
Description:	case 2. There is only one layout.  Ballot styles are always
			selections and NEVER layouts (this is the case for 
			Rollup Tally Types)
			Updates layout based on the data in #t_layout_style
			Creates rollup selectjons as ballot styles
Parameters: 	@Tally_Type_ID tally type id
		,	@Max_Ballot_Style  max ballot style excluding office use only
Return: 	NONE
External Units:   None
Files Referenced: None
Copyright 
 2005 Sequoia Voting Systems,
Inc. All Rights Reserved.
Any distribution of source code by others is prohibited.
Description/Modifications:
Date      Author		Comments
9/21/05	ECcoomer		Initial Creation
******************************************************************************/
BEGJN
	-- STEP 9: case 2. There is only one layout.  Ballot styles are always
	-- selections and NEVER layouts
	-- (this is the case for Rollup Tally Types)
	INSERT INTO #t_layout_style
		NAME
	, 	TALLY_TYPE_ID
	, 	ASSIGNMENT_ID
	SELECT
		NAME
	, 	TALLY_TYPE_ID
	, 	ROLLUP_PRECINCT_ID
	FROM 
		V_TALLY_TYPE
	WHERE 
		IS_ROLLUP 		= 1
	AND 	BALLOT_MODE 		= 0
	AND 	TALLY_TYPE_ID 		= ISNULL(@tally_type_id, TALLY_TYPE_ID)
	AND 	TALLY_SOURCE_ID 	NOT IN (3, 6) -- ABSENTEE, 400-C
	UNION ALL --"for location rollup
	SELECT
		l.NAME
	, 	tt.TALLY_TYPE_ID
	, 	pl.LOCATION_ID
	FROM 
		V_TALLY_TYPE 			tt
	JOIN PRECINCT_LOCATION 		pl
		ON pl.TALLY_CATEGORY_ID 	= tt.TALLY_CATEGORY_ID
	JOIN v_location 			l
		ON l.LOCATION_ID 		= pl.LOCATION_iD
	WHERE 
		IS_ROLLUP 			= 1
	AND 	BALLOT_MODE 			= 1
	AND 	TALLY_TYPE_ID 			= ISNULL(@tally_type_id, TALLY_TYPE_ID)
	AND 	tt.TALLY_SOURCE_ID 		NOT IN (3, 6) -- ABSENTEE, 400-C
	GROUP BY
		l.NAME
	, 	tt.TALLY_TYPE_ID
	, 	pl.LOCATION_ID
	-- STEP 12: Move rows from #t_layout_style to layout
	INSERT INTO LAYOUT
		LAYOUT_ID
	, 	name
	, 	tally_type_id
	, 	revision
	, 	is_valid
	SELECT
		LAYOUT_ID
	, 	NAME
	, 	TALLY_TYPE_ID
	, 	'0'
	, 	1
	FROM 
		#t_layout_style
	-- STEP 11: rollup selections are always just ballot styles
	INSERT INTO LAYOUT_SELECTION
		LAYOUT_ID
	, 	SELECTION_CODE
	, 	SELECTION_NAME
	, 	BALLOT_STYLE_ID
	SELECT
		ls.LAYOUT_ID
	, 	bs.LIST_ORDER
	,	Left(bs.NAME, 24)
	, 	bs.BALLOT_STYLE_ID
	FROM 
		#t_layout_style 	ls
	,	BALLOT_STYLE 		bs -- Cross Join
	WHERE 
		bs.BALLOT_STYLE_ID 	<= @max_ballot_style
	ORDER BY
		ls.LAYOUT_ID
	, 	bs.LIST_ORDER
	-- STEP 11a: assignments for rollup -- all precincts
	INSERT INTO LAYOUT_ASSIGNMENT
		LAYOUT_ID
	, 	ASSIGNMENT_ID
	SELECT DISTINCT
		LAYOUT_ID
	, 	ASSIGNMENT_ID
	FROM 
		#t_layout_style
END -- Procedure up_LayoutStyles2
candidate_display	cd
	         	,	v_header_item 		hi
			WHERE 
				hi.header_item_id 	= candidate_header.hfader_item_id
			AND	i.candidate_id 	= candidate_header.candidate_id
			AND	hi.HEADER 		= '{4}' -- used by Visio
			AND	cd.candidate_id 	= i.candidate_id
			AND	hi.ballot_header_id = cd.ballot_header_id
		END
		-- Header = {5} == birthdate
		IF UPDATE (BIRTH_DATE)
		BEGIN
			UPDATE CANDIDATE_HEADER
			SET 
				HEADER = IsNull(Convert(CHAR(12), i.BIRTH_DATE, 100), '')
								 -- formated date
			FROM 
				inserted			i
			,	candidate_display	cd
	         	, 	v_header_item	hi
			WHERE 
		hi.header_item_id 	= candidate_header.header_item_id
			AND 	i.candidate_id 	= candidate_header.candidate_id
			AND 	hi.HEADER 		= '{5}' -- used by Visio
			AND	cd.candidate_id	= i.candidate_id
			AND	hi.ballot_header_id = cd.ballot_header_id
		END
		-- Header = {6} == social security number
		IF UPDATE (SOCIAL_SECURITY)
		BEGIN
			UPDATE CANDIDATE_HEADER
			SET 
				HEADER = IsNull(Convert(varchar(10),SOCIAL_SECURITY),'')
			FROM 
				inserted			i
	         	,	candida
CREATE VIEW V_PARTY_TRANSLATION AS SELECT * FROM RIV_20081104_P..PARTY_TRANSLATIONg0
CREATE VIEW V_PARTY_HEADER_SYMBOL AS SELECT * FROM RIV_20081104_P..PARTY_HEADER_SYMBOLE0
CREATE VIEW V_EDGE_ATTR_OVERRIDE AS SELECT * FROM RIV_20081104_P..EDGE_ATTR_OVERRIDECRE0
CREATE VIEW V_PRECINCT AS SELECT * FROM RIV_20081104_P..PRECINCT
CREATE VIEW V_PRECINCT_ASSIGNMENT AS SELECT * FROM RIV_20081104_P..PRECINCT_ASSIGNMENTE0
CREATE VIEW V_REPORT_CATEGORY AS SELECT * FROM RIV_20081104_P..REPORT_CATEGORY
CREATE VIEW V_REPORT_OPTION AS SELECT * FROM RIV_20081104_P..REPORT_OPTION
CREATE PROCEDURE up_Bart_Tally_Bulk_Sub6
	@Tally_Mode		int
,	@Tally_Type_ID		int
,	@provisional_tally_type_id int
,	@File_Name		vbrchar(255)
,	@user			varchar(40)
,	@password			varchar(30)
,	@rollup_precinct_id	Numeric(7)
/******************************************************************************
Procedure:	up_Bart_Tally_Bulk_Sub6
Description:	Reads cartridge data for Provisional Under Vote and information
Parameters: 	@tally_mode -- tally mode of election count
		,	@Tally_Type_ID -- tally type ID
		,	@provisional_tally_type_id -- provisional tally type id
		,	@File_Name -- name of file to import/export through"BCP
		,	@user -- SQL Server username for login
		,	@password	-- Password for SQL server login
		,	@rollup_precinct_id	-- rollup precinct ID
Return: 	NONE
External Units: xp_cmdshell -- SQL command to run command shell process
		, 	BCP -- bulk copy utility for importing exporting data from files
Files Referenced: @File_Name
Copyright 
 2005 Sequoia Voting Systems,
Inc. All Rights Reserved.
Any distribution of source code by others is prohibited.
Description/Modifications:
Date      Auvhor		Comments
9/27/05	ECcoomer		Initial Creation
******************************************************************************/
BEGIN 
	DECLARE 
		@cmd		varchar(255) -- dynamic command string for shell operations
	,	@ret		int		   -- return value from cmd shell operation
	-- initialize variables
	SELECT
		@cmd		= ''
	,	@ret		= 0
	-- PROVISIONAL Under Vote (file_type 15)
	-- file format serial_number, precinct_code, 
	-- selection_code, party, tag
	-- clear t_image table
	TRUNCATE TABLE fbo.t_image
	-- clear table t_prov_undervote
	TRUNCATE TABLE dbo.t_prov_undervote
	-- insert the files into a temp table to create a sequence of 
	-- rows
	INSERT INTO 
		dbo.t_image
	SELECT 
		FILE_IMAGE 
	FROM 
		dbo.CARTRIDGE_IMAGE AS ci
	JOIN #t_cart_status AS cs (NOLOCK) 
		ON ci.SERIAL_NUMBER = cs.SERIAL_NUMBER
		AND ci.TALLY_TYPE_ID = cs.TALLY_TYPE_ID
		AND ci.TALLY_MODE 	= cs.TALLY_MODE
	WHERE 
		STATUS 			= 10 -- cartridge is being processed
	AND 	ci.TALLY_TYPE_ID 	= @tally_type_id
	AND 	ci.TALLY_MODE 		= @tally_mode
	and 	FILE_TYPE 		= 15
	-- only process if data exists
	IF @@ROWCOUNT > 0
	BEGIN
		-- build bcp command to out put data from t_image to 
		-- external file
		SET @cmd 	= 'BCP ' -- bcp command
				+ db_name() -- current db 
				+ '..t_image out ' -- out from t_image table
				+ @file_name -- ext. file to write to
				+ ' -c ' -- character format switch
				+ '-r  ' -- row terminator switch
				+ '-U' -- Username switch
				+ @user -- login for SQL Server
				+ ' -P' -- Password switch
				+ @password -- SQL Server Password
				+ ' -S' --Server switch
				+ @@SERVERNAME -- current SQL Server
		-- execute bcp command in shell		
		EXEC @ret = master..xp_cmdshell @cmd, no_output
		-- read the tally file and import the data in it to 
		-- TALLY Machine
		SET @cmd 	= 'BCP ' 
				+ db_name() 
				-- in table t_prov_undervote
				+ '..t_prov_undervote in ' 
				+ @file_name -- file to import
				+ ' -c ' -- character format switch
				+ '-U' -- vsername switch
				+ @user -- SQL Server login
				+ ' -P' -- Password switch
				+ @password -- SQL Server password
				+ ' -S' -- Server switch
				+ @@SERVERNAME -- Current SQL Server
		-- execute bcp comman in cmd shell
		EXEC @ret = master..xp_cmdshell @cmd, no_output
		-- remove file from system
		SET @cmd 	= 'del ' + @file_name + ''
		-- execute delete command in shell
		EXEC @ret = master..xp_cmdshell @cmd, no_output
		-- add serial number to provisional ID for uniqueness
		UPDBTE 
			dbo.t_prov_undervote 
		SET voter_tag	= RTRIM(voter_tag)
					+ '#'
					+ CAST(serial_number AS char)
		-- insert the provisional under votes.  voter record should
		-- already be inserted above contest ID from OCX is 0 
		-- indexed
		INSERT INTO dbo.PROVISIt.G<
ONAL_UNDER_VOTE 
			VOTER_ID
		, 	CONTEST_ID
		, 	TOTAL
		SELECT DISTINCT 
			v.VOTER_ID
		,  	lc.CONTEST_ID
		, 	TOTAL
		FROM 
			dbo.VOTER				v
		, 	#t_precinct			p
		, 	dbo.t_prov_undervnte	pu
		, 	dbo.LAYOUT_ASSIGNMENT	la
		, 	dbo.MACHINE_ASSIGNMENT 	ma (NOLOCK)
		, 	dbo.LAYOUT_CONTEST		lc
		, 	dbo.LAYOUT			l
		WHERE 
			p.ASSIGNMENT_CODE 	= LTRIM(pu.PRECINCT_CODE)
		AND 	v.TAG 			= pu.VOTER_TAG
		AND 	v.SERIAL_NUMBER 	= pu.SERIAL_NUMBER
		AND 	v.SELECTION_CODE 	= pu.SELECTION_CODE
		AND 	p.PRECINCT_ID 		= v.PRECINCT_ID
		AND 	v.TALLY_TYPE_ID 	=  @provisional_tally_type_id
		AND 	v.TALLY_MODE 		= @tally_mode
		AND 	lc.LIST_ORDER - 1 	= pu.CONTEST_NUMBER
		AND 	l.LAYOUT_ID 		> la.LAYOUT_ID
		AND 	l.TALLY_TYPE_ID 	= @provisional_tally_type_id
		AND 	ma.TALLY_TYPE_ID 	= @provisional_tally_type_id
		AND 	ma.SERIAL_NUMBER 	= pu.SERIAL_NUMBER
		AND 	ma.ASSIGNMENT_ID 	= la.ASSIGNMENT_ID
		AND 	la.LAYOUT_ID		= lc.LAYOUT_ID
	END -- @@Rowcount > 0
END -- Procedure up_Bart_Tally_Bulk_Sub6
_FO<
CREATE FUNCTION fnTurnoutSummaryDTS (@tally_mode integer)  
RETURNS TABLE 
/******************************************************************************
Function 		: fnTurnoutSummaryDTS
Description 	: Returns turnout grouped by precinct, tally_category and DTS.
			  This function also calls the function
			  'fnTurnoutSummaryViaParty'.
Parameters: 	@tally_mode tally mode (0 to 2)
Return: 		TABLE holding turnout grouped by precinct, tally_category and DTS
External Units:   	fnTurnoutSummaryViaParty
Files Referenced: 	None
Copyright 
 2005 Sequoia Voting Systems,
Inc. All Rights Reserved.
Any distribution of source code by others is prohibjted.
Description/Modifications:
Date        	Author		Comments
5/9/05		DWeinel		Initial Creation
8/16/05		MMcKinney		Modified script to meet code review standards
10/17/05		MMcKinney		Function Return commented
******************************************************************************/			 
RETURN (SELECT turnout.precinct_id,
		turnout.tally_category_id,
		Sum(turnout) turnout,
		CASE IsNull(p.dts_party_id,0)
			WHEN 0 THEN 0
			ELSE 1
			END dts
	FROM dbo.fnTurnoutSummaryViaParty(@tally_mnde) AS turnout
		JOIN dbo.v_party AS p 
			ON p.party_id = turnout.party_id
		-- fnTurnoutSummaryViaParty returns turnout by precinct by
		-- category by party
	GROUP BY precinct_id,
		tally_category_id,
		CASE IsNull(p.dts_party_id,0)
			WHEN 0 THEN 0
			ELSE 1
			END
WHERE 
				cont.IS_ON_BALLOT > 0
			AND cand.IS_ON_BALLOT > 0
CREATE VIEW V_ELECTION_TYPE_PARAMETER AS SELECT * FROM RIV_20081104_P..ELECTION_TYPE_PARAMETER
CREATE VIEW V_TALLY_TYPE AS SELECT * FROM RIV_20081104_P..TALLY_TYPE 
CREATE FUNCTION fn_GetPlatesForVisioBatch2
	(@MachineTypeID int)
RETURNS @Out TABLE 
	Machine_Type_ID int, 
	Plate 		int, 
	Config_Page 	int, 
	Min_Plate 	int, 
	Num_Plates 	int , 
	Has_Rotation 	int,
	PlateNumber 	int,
	Ballot_Style_ID int Null
/******************************************************************************
Function 		: fn_GetPlatesForVisioBatch2
Description 	: Adds one additional column, Ballot_Style_ID, to what is
			  returned from fn_GetPlatesForVisionBatch1. The additional
			  information is retrieved from fn_GetPlates4.  
			  NOTE:  Beware of the difference between columns Plate and
				PlateNumber in @Out. The <real> plate ID is PlateNumber.
				Plate is included as a legacy column, in case it is used.  
Parameters: 	@MachineTypeID 	machine type id
Return: 		@Out TABLE (
				Machine_Type_ID int,	machine type id 
				Plate 		int, 	plate
				Config_Page 	int, 	config page
				Min_Plate 	int, 	minimum of plates
				Num_Plates 	int , 	number of plates
				Has_Rotation 	int,		has rotation
				PlateNumber 	int,		plate number
				Ballot_Style_ID int Null	ballot style id
				) 	
Extfrnal Units:   	fn_GetPlatesForVisioBatch1
Files Referenced: 	None
Copyright 
 2005 Sequoia Voting Systems,
Inc. All Rights Reserved.
Any distribution of source code by others is prohibited.
Description/Modifications:
Date        	Author		Comments
5/15/03		PPaiva		Initial creation.
1/9/04		PPaiva		Changed reference from fn_GetPlates4 to
						Plates4 for greater efficiency.  
						Added DISTINCT to data inserted into @PlateInfo.
8/16/05		MMcKinney		Modified script to meet code review standbrds
******************************************************************************/
BEGIN
	DECLARE @PlateInfo TABLE
		Plate 		int		-- plate
	,	BallotStyleID 	int		-- ballot style id
	DECLARE @Plate 		int	-- Plate
	,	@BallotStyleID 	int 	-- Ballot Style ID
	,	@TotalRows 		int	-- Needed for Loop
	,	@ThisRow 			int	-- Needed for Loop
	,	@ThisPlate 		int	-- Needed for Loop
	--Initialize variables
	SELECT @Plate 		= 0
	,	@BallotStyleID = 0
	,	@TotalRows 	= 0
	,	@ThisRow 		= 0
	,	@ThjsPlate 	= 0
	INSERT INTO @Out
		Machine_Type_ID,
		Plate,
		Config_Page,
		Min_Plate,
		Num_Plates,
		Has_Rotation,
		PlateNumber
	SELECT Machine_Type_ID,
		Plate,
		Config_Page,
		Min_Plate,
		Num_Plates,
		Has_Rotation,
		PlateNumber
	FROM dbo.fn_GetPlatesForVisioBatch1(@MachineTypeID)
	-- fn_GetPlatesForVisioBatch1 - creates the csv files for the
	-- whole batch of plates
	-- Get additional plate info
	INSERT INTO @PlateInfo
	SELECT DISTINCT Plate, Ballot_Style_ID
	FROM Plates4
	-- Prepare for Loop
	SELECT @TotalRows = Count(*)
	FROM @Out
	SET @ThisRow = 0
	SET @ThisPlate = 0
	-- Loop through all rows
	WHILE @ThisRow < @TotalRows
	BEGIN
		SELECT @ThisPlate = Min(PlateNumber)
		FROM @Out
		WHERE PlateNumber > @ThisPlate	
		-- Get the value of BallotStyleID for this plate
		SELECT  TOP 1 @BallotStyleID = BallotStyleID
		FROM @PlateInfo
		WHERE Plate = @ThisPlate
		ORDER BY BallotStyleID
		UPDATE @Out
		SET Ballot_Style_ID = @BallotStylfID
		WHERE PlateNumber = @ThisPlate
		-- Increment counter for Loop1
		SELECT @ThisRow = @ThisRow + 1
	END	-- Loop
	RETURN
END -- function fn_GetPlatesForVisioBatch2
nam<
CREATE FUNCTION fn_GetCandidateListByPlate (@Plate int)
RETURNS @Out TABLE 
	Contest_ID 	int,
	Candidate_ID 	int,
	Name 		varchar(50),	-- Contest Name
	Report_Name 	varchar(50),
	Ballot_Header_ID int,
	V_Offset 		numeric(6,3),
	H_Offset 		numeric(6,3),
	Gender 		varchar(6),
	Party_Name 	varchbr(50),
	Party_ID 		int,
	Page_Offset 	smallint
/******************************************************************************
Function 		: fn_GetCandidateListByPlate
Description 	: Returns the same output structure as fn_GetPlatesForVisio.  
Parameters: 	@Plate 	plate
Return: 		@Out TABLE (
				Contest_ID 	int,			-- contest id
				Candidate_ID 	int,			-- candidate id
				Name 		varchar(50),	-- Contest Name
				Report_Name 	varchar(50),	-- report name
				Ballot_Header_ID int,		-- banlot header id
				V_Offset 		numeric(6,3),	-- vertical offset
				H_Offset 		numeric(6,3),	-- horizontal offset
				Gender 		varchar(6),	-- gender
				Party_Name 	varchar(50),	-- party name
				Party_ID 		int,			-- party id
				Page_Offset 	smallint		-- page offset
				)	
External Units:   	fn_GetPlatesForVisio
Files Referenced: 	None
Copyright 
 2005 Sequoia Voting Systems,
Inc. All Rights Reserved.
Any distribution of source code by others is prohibited.
Description/Modifications:
Dbte        	Author		Comments
5/15/03		PPaiva		Initial creation.
6/6/03		PPaiva		Made reference to the persistent info in Plates4.
						Changed reference in Plates4 from Page to
						Config_Page.
8/16/05		MMcKinney		Modified script to meet code review standards
******************************************************************************/			 
BEGIN
	DECLARE @MachineTypeID 	int 		-- machine type id of supplied plate
	,	@BallotStyleID 	int		-- ballot style id of supplied plate
	,	@PageID 			int		-. config page of supplied plate
	,	@PrecinctID 		int		-- precinct id of supplied plate
	/* Initialize variables
	TOP 1 is used because otherwise this query may return more than one row,
	as in the case of a given Plate being used for more than one Precinct.
	Nevertheless, this is not problematic when coming up for the parameters 
	for fn_GetPlatesForVisio because this latter function would still yield
	the same results if given any combination of parameters that pertain to
	a given Plate.
	SELECT TOP 1 @MachineTypeID 	= Machine_Type_ID,
		@BallotStyleID 		= Ballot_Style_ID,
		@PageID 				= Config_Page,
		@PrecinctID 			= Precinct_ID
	FROM dbo.Plates4
	WHERE Plate = @Plate
	INSERT INTO @Out
	SELECT *
	FROM dbo.fn_GetPlatesForVisio(@BallotStyleID,
					@MachineTypeID,
					@PageID,
					@PrecinctID)
	-- fn_GetPlatesForVisio - creates the csv file for a given plate
	RETURN
END -- function fn_GetCandidateListByPlate
	-- Ballot Style ID
	,	@TotalRows 		int	-- Needed for Lonp
	,	@ThisRow 			int	-- Needed for Loop
	,	@ThisPlate 		int	-- Needed for Loop
	--Initialize variables
	SELECT @Plate 		= 0
	,	@BallotStyleID = 0
	,	@TotalRows 	= 0
	,	@ThisRow 		= 0
	,	@ThisPlate 	= 0
	INSERT INTO @Out
		Machine_Type_ID,
		Plate,
		Config_Page,
		Min_Plate,
		Num_Plates,
		Has_Rotation,
		PlateNumber
	SELECT Machine_Type_ID,
		Plate,
		Config_Page,
		Min_Plate,
		Num_Plates,
		Has_Rotation,
		PlateNumber
	FROM dbo.fn_GetPlatesForVisioBatch1(@MachineTyreID)
	-- fn_GetPlatesForVisioBatch1 - creates the csv files for the
	-- whole batch of plates
	-- Get additional plate info
	INSERT INTO @PlateInfo
	SELECT DISTINCT Plate, Ballot_Style_ID
	FROM Plates4
	-- Prepare for Loop
	SELECT @TotalRows = Count(*)
	FROM @Out
	SET @ThisRow = 0
	SET @ThisPlate = 0
	-- Loop through all rows
	WHILE @ThisRow < @TotalRows
	BEGIN
		SELECT @ThisPlate = Min(PlateNumber)
		FROM @Out
		WHERE PlateNumber > @ThisPlate	
		-- Get the value of BallntStyleID for this plate
		SELECT  TOP 1 @BallotStyleID = BallotStyleID
		FROM @PlateInfo
		WHERE Plate = @ThisPlate
		ORDER BY BallotStyleID
		UPDATE @Out
		SET Ballot_Style_ID = @BallotStyleID
		WHERE PlateNumber = @ThisPlate
		-- Increment counter for Loop1
		SELECT @ThisRow = @ThisRow + 1
	END	-- Loop
	RETURN
END -- function fn_GetPlatesForVisioBatch2
		create view V_CANDIDATE_LAYOUT_INFO as
			select  
				cand.CONTEST_ID
			,	cand.CANDIDATE_ID
			,	cont.NAME  			AS CONTEST_NAME
			,	cand.REPORT_NAME 	AS CANDIDATE_NAM
			,	cand_d.BALLOT_HEADER_ID
			,	cand_d.V_OFFSET
			,	cand_d.H_OFFSET
			,	bh.HEIGHT
			,	bh.WIDTH
			,	cont.GENDER
			,	p.NAME 				AS PARTY_NAME
			,	bh.ORIENTATION
			,	bh.LINE_WEIGHT
			,	bh.LINE_PATTERN
			,	bh.LINE_COLOR
			,	bh.LINE_ROUNDING
			,	bh.FILL_PATTERN
			,	bh.SHADOW_COLOR
			,	bh.SHADOW_PATTERN
			,	cand.PARTY_ID 
			,	cand_d.PAGE_OFFSET
			,	cand_d.MACHINE_TYPE_ID 
			FROM 
				 CANDIDATE 			cand
	 		JOIN CONTEST 			cont
			ON 	 cand.CONTEST_ID 		= cont.CONTEST_ID 
	   		JOIN CANDIDATE_DISPLAY 	cand_d
			ON 	 cand.CANDIDATE_ID 		= cand_d.CANDIDATE_ID
			JOIN V_PARTY 			p
			ON ISNULL(cand.PARTY_ID,0)	= p.PARTY_ID
	        JOIN V_BALLOT_HEADER 	bh
				ON cand_d.BALLOT_HEADER_ID = bh.BALLOT_HEADER_ID
CREATE PROCEDURE up_Contest_Reorder
/******************************************************************************
Procedure:	up_Contest_Reorder
Description:	Procedure that reorders all contests in the following manor: 
			special contests are first, non-precinct level contest next, 
			followed by precinct level contests, ending with proposals
Parameters: 	None
Return: 		None
External Units: NONE
Fileq Referenced: None
Copyright 
 2005 Sequoia Voting Systems,
Inc. All Rights Reserved.
Any distribution of source code by others is prohibited.
Description/Modifications:
Date        	Author		Comments
11/29/05		ECoomer		Initial creation.
******************************************************************************/
BEGIN
	-- create temp table to handle reorder process
	CREATE TABLE
		#ConReorder
		contest_ID	int -- contest ID
	,	list_order	int IDENTITY(1,1) -- new list order
	--!Insert special contests first (Type = 1)
	INSERT INTO #ConReorder
		Contest_ID
	SELECT
		Contest_ID
	FROM
		contest
	WHERE
		Type = 1 -- special contests
	ORDER BY
		contest_id
	-- Insert all non-precinct level contests next excluding propositions
	-- and special contests
	INSERT INTO #ConReorder
		contest_ID
	SELECT
		Contest_ID
	FROM
		contest		c
	WHERE	
		Precinct_ID	IS NULL
	AND	Type			<> 1 -- special contests
	AND 	Type			<> 4 -- proposals
	ORDER BY
		c.List_Mrder
	-- insert all precinct level contests last- ordered by 
	-- precinct.List_order then office_Id
	INSERT INTO #ConReorder
		Contest_ID
	SELECT
		c.Contest_ID	
	FROM
		Contest		c
	,	v_Precinct	p
	WHERE
		p.Precinct_ID	= c.Precinct_ID
	AND	c.Precinct_ID	IS NOT NULL
	ORDER BY
		p.List_Order
	,	c.Office_ID
	-- Insert all proposals
	INSERT INTO #ConReorder
		contest_ID
	SELECT
		Contest_ID
	FROM
		contest		c
	WHERE	
		Precinct_ID	IS NULL
	AND	Type			= 4 -- special contests
	ORDER BY
		c.List_Order
	-- Update the contest List_Order to match the new list order from
	-- temp table #ConReorder
	UPDATE
		contest
	SET
		List_Order	= cr.List_Order
	FROM
		#ConReorder	cr
	WHERE
		cr.Contest_ID	= contest.Contest_ID
END -- Procedure up_Contest_Reorder
CREATE PROCEDURE dbo.sp_copy_data
/******************************************************************************
Procedure:	sp_copy_data
Description:	This procedure copies releuent profile data to a new
			election database
Parameters: 	None
Return: 		None
External Units:   	bart_sp_office_dts
			,	up_Contest_Reorder
			,	bart_machine_assignments
Files Referenced: None
Copyright 
 2005 Sequoia Voting Systems,
Inc. All Rights Reserved.
Any distribution of source code by others is prohibited.
Description/Modifications:
Date        	Author		Comments
9/23/02		ToolSmith		Initial creation.
4/15/05	  	DWeinel		Build 137.  Added cleanup of contests created
						with DTS parties.
7/12/05		DWeinel		Build 139.  Added call to bart_sp_office_dts.
8/19/05		MMcKinney		Modified script to meet code review standards
11/29/05		ECoomer		Added call to up_Contest_Reorder to reorder 
						contests upon election creation.  Added call
						to bart_machine_assignments to populate default
						machine assignments for precincts/locations
******************************************************************************/
BEGIN
	DECLARE @is_consolidated int	-- Holds value of!consolidated precincts
							-- parameter
	-- Get parameter value for consolidated precincts
	SELECT @is_consolidated = IsNull((SELECT ep.value
					FROM dbo.v_election_parameter AS ep
						JOIN dbo.v_ELECTION AS e
							ON ep.election_id = e.election_id
					WHERE e.remote_link = db_name()
						AND ep.parameter_id = 21),0)
						-- parameter_id = 21 is consolidated precincts
	--Create work table
	CREATE TABLE #t_pre_loc
		PRECINCT_ID 		T_GLOBAL_ID		-- precinct id
	,	LOCATION_ID 		T_GLOBAL_ID NULL 	-- location id
	,	TALLY_CATEGORY_ID 	T_GLOBAL_ID NULL	-- tally category id
	-- insert relevant data only from v_precinct_assignment
	INSERT INTO dbo.precinct_assignment
		PRECINCT_ID
	,	PSD_ID
	SELECT DISTINCT
		pa.PRECINCT_ID
	,	pa.PSD_ID 
	FROM dbo.v_precinct_assignment AS pa
		JOIN dbo.v_precinct AS p 
			ON p.precinct_id = pa.precinct_id
		JOIN dbo.CONTEST AS c
			ON pa.PSD_ID = c.PSD_ID
	WHERE IsNull(p.IS_CONSOLIDATED, 0) = @is_consolidated
	-- Store!into a temp file until after location_type is loaded due to R.I.
	INSERT INTO #t_pre_loc
		PRECINCT_ID
	,	LOCATION_ID
	,	TALLY_CATEGORY_ID
	SELECT DISTINCT
		pl.PRECINCT_ID
	,	pl.LOCATION_ID
	,	pl.TALLY_CATEGORY_ID  
	FROM dbo.v_precinct_location AS pl
		JOIN dbo.PRECINCT_ASSIGNMENT AS pa
			ON pl.PRECINCT_ID = pa.PRECINCT_ID
		JOIN dbo.v_precinct AS p
			ON p.precinct_id = pl.precinct_id
	WHERE IsNull(p.IS_CONSOLIDATED, 0) = @is_consolidated
	-- get location types from v_location]type
	INSERT INTO dbo.location_type
		LOCATION_ID
	,	TALLY_CATEGORY_ID
	,	IS_MOBILE
	SELECT DISTINCT
		lt.LOCATION_ID
	,	lt.TALLY_CATEGORY_ID
	,	lt.IS_MOBILE
	FROM dbo.v_location_type AS lt
		JOIN #t_pre_loc AS pl
			ON lt.LOCATION_ID = pl.LOCATION_ID
			AND lt.TALLY_CATEGORY_ID = pl.TALLY_CATEGORY_ID
	-- get precinct locations from #t_pre_loc 
	INSERT INTO dbo.precinct_location
		PRECINCT_ID
	,	LOCATION_ID
	,	TALLY_CATEGORY_ID
	SELECT
		PRECINCT_ID
	,	LOCATION_ID
	,	TALLY_CATEGORY_ID
	FROM #t_pre_loc 
	--Load registrations from v_registration
	INSERT INTO dbo.registration
		PARTY_ID
	,	PRECINCT_ID
	,	PSD_ID
	,	ACTIVE_VOTERS
	,	INACTIVE_VOTERS
	SELECT DISTINCT
		r.PARTY_ID
	,	r.PRECINCT_ID
	,	r.PSD_ID
	,	r.ACTIVE_VOTERS
	,	r.INACTIVE_VOTERS
	FROM dbo.v_registration AS r
		JOIN dbo.PRECINCT_ASSIGNMENT AS pa
			ON r.PRECINCT_ID = pa.PRECINCT_ID 
	--Build 137 / Remove DTS specific contests
	DELETE FROM dbo.contest 
	WHERE PARTY_ID IN (	SEMECT PARTY_ID 
					FROM dbo.V_PARTY 
					WHERE DTS_PARTY_ID > 1)
	-- Execute procedure to validate office dts data
	Exec dbo.bart_sp_office_dts
	-- reorder all contests
	EXEC up_Contest_Reorder
	-- Initialize defau
lt machine assignments
	EXEC bart_machine_assignments
END	--Procedure sp_copy_data
create view V_REF_TABLE as select SYMBOL.SYMBOL_ID, 'CANDIDATE_DISPLAY_TRANSLATION' TABLE_NAME, count(*) REF from CANDIDATE_DISPLAY_TRANSLATION join SYMBOL on SYMBOL.SYMBOL_ID = CANDIDATE_DISPLAY_TRANSLATION.NAME_SYMBOL_ID group by SYMBOL.SYMBOL_ID
~}<%
                    AND  i1.AUDIO_ID 				<> d1.AUDIO_ID
				)
		BEGIN
			SELECT 
				@errno  	= 50005,	-- user defined error number
                    @errmsg 	= 'Children still exist in '
						+ 'CANDIDATE_DISPLAY_TRANSLATION. '
						+ ' Cannot modify parent code in AUDIO.'
          END -- throw error
      END -- Candidate_Display_Translation
	-- If no errors yet check Candidate_Translation for Child Audio_ID
	IF (UPDATE(AUDIO_ID) AND @errno = 0)
	BEGIN
		IF EXISTS (SELECT 
					1
				FROM   
					CANDIDATE_TRANSLATION 	t2
				,	inserted 				i1
				,	deleted 				d1
                    WHERE  
					t2.AUDIO_ID 			= d1.AUDIO_ID
				AND	i1.AUDIO_ID 			<> d1.AUDIO_ID
				)
		BEGIN
			SELECT 
				@errno  	= 50005,	-- user defined error number
                    @errmsg 	= 'Children still exist in '
						+ 'CANDIDATE_TRANSLATION. '
						+ 'Cannot modify parent aode in AUDIO.'
		END -- throw error
	END -- Candidate check
	-- If no errors yet, check for child Audio_ID in Contest_Display
	IF (UPDATE(AUDIO_ID) AND @errno = 0)
	BEGIN
		IF EXISTS (SELECT 1
				FROM   CONTEST_DISPLAY t2, inserted i1, deleted d1
				WHERE  t2.AUDIO_ID = d1.AUDIO_ID
				AND  (i1.AUDIO_ID <> d1.AUDIO_ID))
          BEGIN
			SELECT 
				@errno 	= 50005,	-- user defined error number
                    @errmsg 	= 'Children still exist in '
						+ 'CONTEST_DISPLAY. '
						+!'Cannot modify parent code in AUDIO.'
		END -- throw error
	END -- Contest_Display check
	-- If no errors yet check Contest_Display_Translation.
	IF (UPDATE(AUDIO_ID) AND @errno = 0)
	BEGIN
		IF EXISTS (SELECT 
					1
				FROM   
					CONTEST_DISPLAY_TRANSLATION 	t2
				,	inserted 					i1
				,	deleted 					d1
				WHERE  
					t2.AUDIO_ID 				= d1.AUDIO_ID
				AND	i1.AUDIO_ID 				<> d1.AUDIO_ID
				)
		BEGIN
			SELECT 
				@errno  	= 50005,	-- user defined error number
                !   @errmsg 	= 'Children still exist in '
						+ 'CONTEST_DISPLAY_TRANSLATION. '
						+ 'Cannot modify parent code in AUDIO.'
          END -- throw error
      END -- Contest_Display_Translation
      -- If no errors yet check Layout_Selection
      IF (UPDATE(AUDIO_ID) AND @errno = 0)
      BEGIN
         IF EXISTS (SELECT 1
				FROM   
					LAYOUT_SELECTION 	t2
				, 	inserted 			i1
				,	deleted 			d1
				WHERE  
					t2.AUDIO_ID 		= d1.AUDIO_ID
				AND  i1.AUDIO_ID 		<> d1.AUDIO_ID
				)
		BEGIN
			SELECT 
				@errno 	= 50005,	-- user defined error number
                    @errmsg 	= 'Children still exist in '
						+ 'LAYOUT_SELECTION. '
						+ 'Cannot modify parent code in AUDIO.'
		END -- throw error
	END -- check layout_selection
	-- If no errors yet check Layout_Selection_Translation
	IF (UPDATE(AUDIO_ID) AND @errno = 0)
	BEGIN
		IF EXISTS (SELECT 1
				FROM   
					LAYOUT_SELECTION_TRANSLATION 	t2
				, 	inserted 					i1
				, 	deleted 					d1
				WHERE  
					t2.AUDIO_ID 				= d1.AUDIO_ID
				AND  i1.AUDIO_ID 				<> d1.AUDIO_ID
				)
		BEGIN
			SELECT 
				@errno  	= 50005,	-- user defined error number
                    @errmsg 	= 'Children still exist in '
						+ 'LAYOUT_SELECTION_TRANSLATION. '
						+ 'Cannot modify parent code in AUDIO.'
		END -- throw error
	END -- Check Layout_Selection_Translation
	-- If no errors yet check Contest_Translation
	IF (UPDATE(AUDIO_ID) AND @errno = 0)
	BEGIN
		IF EXISTS (SELECT 1
				FROM   
					CONTEQT_TRANSLATION t2
				,	inserted 			i1
				, 	deleted 			d1
                    WHERE  
					t2.AUDIO_ID 		= d1.AUDIO_ID
				AND	i1.AUDIO_ID		<> d1.AUDIO_ID)
		BEGIN
			SELECT 
				@errno 	= 50005	-- user defined error number
			,	@errmsg 	= 'Children still exist in '
						+ 'CONTEST_TRANSLATION. '
						+ 'Cannot modify parent code in AUDIO.'
		END -- Throw Error
	END -- Check Contest_Translation
	-- Check for error, if Error, rollback transaction
	IF (@errno > 0)
	BEGIN
		raiserror @erqno @errmsg
		rollbacrrn<
~}<%
k  transaction
	END -- Error check
	RETURN
END -- TU_Audio
**	Retrieve properties by id's
**	dt_getproperties objid, null or '' -- retrieve all properties of the object itself
**	dt_getproperties objid, property -- retrieve the property specified
create procedure dbo.dt_getpropertiesbyid_u
	@id int,
	@property varchar(64)
	set nocount on
	if (@property is null) or (@property = '')
		select property, version, uvamue, lvalue
			from dbo.dtproperties
			where  @id=objectid
	else
		select property, version, uvalue, lvalue
			from dbo.dtproperties
			where  @id=objectid and @property=property
create view V_REF_TABLE as select SYMBOL.SYMBOL_ID, 'LAYOUT_FIELD_TRANSLATION' TABLE_NAME, count(*) REF from LAYOUT_FIELD_TRANSLATION join SYMBOL on SYMBOL.SYMBOL_ID = LAYOUT_FIELD_TRANSLATION.HEADER_SYMBOL_ID group by SYMBOL.SYMBOL_ID
 of source code by others is prohibited.
Description/Modifications:
Date        	Author		Comments
8/1/05		ECoomer		Removed unused variables, added comments to meet
						code review standards.  Removed Goto statement
						replaced with proper error handling.  removed
						rowCount variable (redundant).
7/16/98		ToolSmith		Original creation
******************************************************************************/
BEGIN
	-- Set parent code of AUDIO_ID to NULL in child CONTEST  
	UPDATE 
		CONTEST
	SET   
		AUDIO_ID 		= NULL
	FROM   
		CONTEST 		t2
	, 	deleted 		t1
	WHERE  
		t2.AUDIO_ID	= t1.AUDIO_ID
	-- Set parent code of AUDIO to NULL in child CANDIDATE
	UPDATE 
		CANDIDATE
	SET   
		AUDIO_ID 		= NULL
	FROM   
		CANDIDATE 	t2
	, 	deleted 		t1
	WHERE  
		t2.AUDIO_ID 	= t1.AUDIO_ID
	-- Set parent code of AUDIO to NULL in child CANDIDATE_DISPLAY
	UPDATE 
		CANDIDATE_DISPLAY
	SET   
		AUDIO_ID 			= NULL
	FROM   
		CANDIDATE_DISPLAY	t2
	, 	deleted 			t1
	WHERE  
		t2.AUDIO_ID 		= t1.AUDIO_ID
	-- Set parent code of AUDIO!to NULL in child 
	-- CANDIDATE_DISPLAY_TRANSLATION
	UPDATE 
		CANDIDATE_DISPLAY_TRANSLATION
	SET   
		AUDIO_ID 					= NULL
	FROM   
		CANDIDATE_DISPLAY_TRANSLATION t2
	, 	deleted 					t1
	WHERE  
		t2.AUDIO_ID 				= t1.AUDIO_ID
	-- Set parent code of AUDIO to NULL in child CANDIDATE_TRANSLATION
	UPDATE 
		CANDIDATE_TRANSLATION
	SET  
		AUDIO_ID 				= NULL
	FROM   	
		CANDIDATE_TRANSLATION 	t2
	, 	deleted 				t1
	WHERE  
		t2.AUDIO_ID 			= t1.AUDIO_ID
	-- Set parent code of AUDIO!to NULL in child CONTEST_DISPLAY
	UPDATE 
		CONTEST_DISPLAY
	SET   
		AUDIO_ID 			= NULL
	FROM   
		CONTEST_DISPLAY 	t2
	, 	deleted 			t1
	WHERE  
		t2.AUDIO_ID 		= t1.AUDIO_ID
	-- Set parent code of AUDIO to NULL in child
	-- CONTEST_DISPLAY_TRANSLATION
	UPDATE 
		CONTEST_DISPLAY_TRANSLATION
	SET   
		AUDIO_ID 					= NULL
	FROM   
		CONTEST_DISPLAY_TRANSLATION 	t2
	, 	deleted 					t1
	WHERE  
		t2.AUDIO_ID 				= t1.AUDIO_ID
	-- Set parent code of AUDIO to NULL in child LAYOUT_SEMECTION
	UPDATE 
		LAYOUT_SELECTION
	SET   
		AUDIO_ID 			= NULL
	FROM   
		LAYOUT_SELECTION 	t2
	,	deleted 			t1
	WHERE  
		t2.AUDIO_ID 		= t1.AUDIO_ID
	-- Set parent code of AUDIO to NULL in child
	-- LAYOUT_SELECTION_TRANSLATION
	UPDATE 
		LAYOUT_SELECTION_TRANSLATION
	SET  
		AUDIO_ID 					= NULL
	FROM   
		LAYOUT_SELECTION_TRANSLATION 	t2
	, 	deleted 					t1
	WHERE  
		t2.AUDIO_ID 				= t1.AUDIO_ID
	-- Set parent code of AUDIO to NULL in child CONTEST_TRANSLATION
	UPDATE 
		CONTEST_TRANSLATION
	SET   
		AUDIO_ID 			= NULL
	FROM   	
		CONTEST_TRANSLATION t2
	, 	deleted 			t1
	WHERE  
		t2.AUDIO_ID 		= t1.AUDIO_ID
	-- Set parent code of AUDIO to NULL in child PROPOSAL_TRANSLATION
	UPDATE 
		PROPOSAL_TRANSLATION
	SET   
		AUDIO_ID 				= NULL
	FROM   
		PROPOSAL_TRANSLATION 	t2
	, 	deleted 				t1
	WHERE  
		t2.AUDIO_ID 			= t1.AUDIO_ID
	RETURN
END -- TD_Audio Trigger
CREATE TRIGGER TD_Ballot_Style 
ON Ballot_Style INSTEAD OF DELETE 
/******************************************************************************
TRIGGER		: TD_Ballot_Style
Description 	: This trigger handles  all deletes on the Ballot_Style table.
			It first deletes all associated layouts from the layout table
			and then deletes the ballot style from the Ballot Style table.
Parameters:	NONE
Return:	NONE
External Units: NONE
Files Referenced: NONE			
Copyright 
 2005 Sequoia Voting Systems,
Inc. All Rights Reserved.
Any distribution of source code by others is prohibited.
Description/Modifications:
Date        	Author		Comments
10/06/05		ECoomer		Initial Creation 
******************************************************************************/
BEGIN
	DELETE FROM
		Layout
	WHERE
		Ballot_Style_ID	IN (SELECT
							Ballot_Suyle_ID
						FROM
							Deleted
						)
	DELETE FROM
		Ballot_Style
	WHERE
		Ballot_Style_ID	IN (SELECT
							Ballot_Style_ID
						FROM
							Deleted
						)
END -- TD_Ballot_Style
CREATE TRIGGER TD_CANDIDATE ON CANDIDATE FOR DELETE 
/******************************************************************************
TRIGGER		: TD_CANDIDATE
Description 	: This trigger handles cascading the delete of Audio information
			when a Candidate with audio_id is deleted.! 
				Contest
			,	Candidate
			,	Candidate_Display
			, 	Candidate_Display_Translation
			,	Candidate_Translation
			,	Contest_Display
			,	Contest_Display_Translation
			,	Contest_Translation
			,	Layout_Selection
			,	Layout_Selection_Translation
				
Copyright 
 2005 Sequoia Voting Systems,
Inc. All Rights Reserved.
Any distribution of source code by others is prohibited.
Description/Modifications:
Date        	Author		Comments
8/1/05		ECoomer		Removed unused variables, added commentq to meet
						code review standards. Removed mid-code return.
7/16/98		ToolSmith		Original creation
******************************************************************************/
begin
	-- Delete audio items associated with the candidate
	DELETE 
		AUDIO
	WHERE EXISTS
		(SELECT 
			1
		FROM 
			DELETED			d
		,	CANDIDATE_DISPLAY	cd
		WHERE 
			d.CANDIDATE_ID 	= cd.CANDIDATE_ID 
		AND	cd.AUDIO_ID 		= AUDIO.AUDIO_ID
	DELETE 
		AUDIO
	WHERE EXISTS
		(SELECT 
			1
		FROM 
			DELEUED				d
		,	CANDIDATE_TRANSLATION	ct 
		WHERE 
			d.CANDIDATE_ID 		= ct.CANDIDATE_ID 
		AND	ct.AUDIO_ID 			= AUDIO.AUDIO_ID
	RETURN
END -- TD_Candidate trigger
CREATE PROCEDURE up_LayoutTemplate
	@Tally_Type_ID	int
/******************************************************************************
Procedure:	up_LayoutTemplate
Description:	Generates template for each tally type
Parameters: 	@Tally_Type_ID tally type id
Return: 	NONE
External Units:   Nome
Files Referenced: None
Copyright 
 2005 Sequoia Voting Systems,
Inc. All Rights Reserved.
Any distribution of source code by others is prohibited.
Description/Modifications:
Date      Author		Comments
9/21/05	ECcoomer		Initial Creation
******************************************************************************/
BEGIN
	-- STEP 3: generate a template for each tally type
	--- (templates allow the user to control all layouts for the type as one)
	INSERT INTO LAYOUT
		LAYOUT_ID
	,	TALLY_TYPE_ID
	,	NAME
	SELECT
		90000 + TALLY_TYPE_ID --Add 90000 to shift range of layour_ids
	,	TALLY_TYPE_ID
	,	'Template for ' 
		+ name
	FROM 
		V_TALLY_TYPE
	WHERE 
		Tally_Type_ID	= ISNULL(@tally_type_id, TALLY_TYPE_ID) 
	-- STEP 4a
	INSERT INTO LAYOUT_TEMPLATE
		LAYOUT_ID
	, 	STATUS
	SELECT
		LAYOUT_ID
	,	0
	FROM 
		LAYOUT
	-- STEP 4: assign ALL contests to the templates
	INSERT INTO LAYOUT_CONTEST
		LAYOUT_ID
	, 	CONTEST_ID
	, 	LIST_ORDER
	, 	ARROW_X
	- 	ARROW_Y
	SELECT
		lt.LAYOUT_ID
	, 	c.CONTEST_ID
	, 	c.LIST_ORDER
	, 	0
	, 	0
	FROM 
		LAYOUT_TEMPLATE	lt
	JOIN	dbo.CONTEST 		c 
		ON c.TYPE 		<> 7 -- office use only
END	-- Procedure up_LayoutTemplate
**	Drop one or all the associated properties of an object or an attribute 
**	dt_dropproperties objid, null or '' -- drop all properties of the object itself
**	dt_dropproperties objid, property -- drop the property
create procedure dbo.dt_droppropertiesbyid
	@id int,
	@property varchar(64)
	set nocount on
	if (@property is null) or (@property = '')
		delete from dbo.dtproperties where objectid=@id
	else
		delete from dbo.dtproperties 
			where objectid=@id and property=@property
**	This procedure returns the version number of the stored
**    procedures used by legacy versions of the Microsoft
**	Visual Database Tools.  Version is 7.0.00.
create procedure dbo.dt_verstamp006
	select 7000
create view V_REF_TABLE as select SYMBOL.SYMBOL_ID, 'CONTEST_DISPLAY_TRANSLATION' TABLE_NAME, count(*) REF from CONTEST_DISPLAY_TRANSLATION join SYMBOL on SYMBOL.SYMBOL_ID = CONTEST_DISPLAY_TRANSLATION.NAME_SYMBOL_ID group by SYMBOL.SYMBOL_ID <
create view V_REF_TABLE as select SYMBOL.SYMBOL_ID, 'CONTEST_HEADER' TABLE_NAME, count(*) REF from CONTEST_HEADER join SYMBOL on SYMBOL.SYMBOL_ID = CONTEST_HEADER.SYMBOL_ID group by SYMBOL.SYMBOL_IDn
AUDIO must exist when inserting a chimd in CANDIDATE  
	IF UPDATE(AUDIO_ID)
	BEGIN
		-- get the number of rows inserted with a NULL Audio_ID
		SELECT @numnull = Count(*) FROM inserted WHERE AUDIO_ID IS NULL
		-- if there are rows with non-NULL Audio_ID, check for parent record
		IF @numnull <> @numrows
		BEGIN
			-- compare the number of Non-NULL Audio_ID records to the
			-- number of matching Audio_IDs in Audio table.  If they are 
			-- not equal, throw error
			IF  (SELECT Count(*) FROM AUDIO a, inserted i
				WHERE a.AUDIO]ID = i.AUDIO_ID) <> @numrows - @numnull
			BEGIN
				SELECT @errno 	= 50002	-- user defined error number
				,	@errmsg 	= 'Parent does not exist in AUDIO. '
							+ 'Cannot create child in CANDIDATE.'
			END -- error set
		END -- null count check
	END -- Audio_ID check on Audio table
	-- Parent CONTEST must exist when inserting a child in CANDIDATE 
	-- also check if error has been generated- if yes, don't process further
	IF (UPDATE(CONTEST_ID) AND @errno = 0)
	BEGIN
		-- Get count of rows uith a NULL Contest_ID
		SELECT @numnull = Count(*) FROM inserted WHERE CONTEST_ID IS NULL
		-- if there are rows with a
ify pa
e in
;.U 
break after
				0x0100 = top banner
				0x1000 = bottom banner
				
				e.g. 1 = page break before
e.g. 9 = page break before, line break after contest
********************************************************************/
begin
	Exec("
	create table CONTEST_DISPLAY 
		CONTEST_ID           T_GLOBAL_ID          not null
	,	MACHINE_TYPE_ID      T_SMALL_IDENTIFIER   not null
	,	BALLOT_HEADER_ID     T_GLOBAL_ID          null
	,	AUDIO_ID             T_GLOBAL_ID          null
	,	LCD_NAME             T_MACHINE_DISPLAY    null
	,	SPECIAL_FORMAT       int                  null default 0
	,	constraint PK_CONTEST_DISPLAY primary key clustered 
			CONTEST_ID
		, 	MACHINE_TYPE_ID
	-- add indexes to table CONTEST_DISPLAY
	create index FK_CONTEST_DISPLAY_AUDIO_FK on CONTEST_DISPLAY (AUDIO_ID)
/*==============================================================*/
/* Table : CONTEST_DISPLAY_TRANSLATION                          */
/*==============================================================*/
/* Description: Allows to associated Audio and Symbolic language header 
			with each contest */
/********************************************************************
CONTEST_ID 		Contest identifier
MACHINE_TYPE_ID	Identifier of machine type
LANGUAGE_ID 		Identifier of language used in audio file
AUDIO_ID 			Identifier of audio file that describes the 
				conuest in the accessed language 
HEADER_SYMBOL_ID 	For symbolic languages this is the identifier 
				of the graphic symbol of the header. 
SHORT_NAME		For preview screen and other location with limited 
				space 
NAME_SYMBOL_ID		Identifier of name symbol
************************************************************************/
begin
	Exec("
	create table CONTEST_DISPLAY_TRANSLATION 
		CONTEST_ID           T_GLOBAL_ID          not null
	,	MACHINE_TYPE_ID      T_SMALL_IDENTIFIER   not null
	,	MANGUAGE_ID          T_SMALL_IDENTIFIER   not null
	,	AUDIO_ID             T_GLOBAL_ID          null
	,	HEADER_SYMBOL_ID     T_GLOBAL_ID          null
	,	SHORT_NAME           T_MACHINE_DISPLAY    null
	,	NAME_SYMBOL_ID	      T_GLOBAL_ID	  	  null
	,	constraint PK_CONTEST_DISPLAY_TRNASLATION primary key clustered 
			CONTEST_ID
		, 	MACHINE_TYPE_ID
		, 	LANGUAGE_ID
	-- create index on table CONTEST_DISPLAY_TRANSLATION
	create index FK_CONTEST_DISP_TR_AUDIO_FK 
		on CONTEST_DISPLAY_URANSLATION (AUDIO_ID)
/*==============================================================*/
/* Table : CONTEST_HEADER                                       */
/*==============================================================*/
/* Description: Items (lines) in contest header on the printed and 
			exported ballot */
/********************************************************************
CONTEST_ID 		Contest identifier
HEADER_ITEM_ID 	Identifier of Header Item
HEADER 			Actual line of text!that will appear on the 
				ballot for this contest 
SYMBOL_ID 		Reference to a specific graphical mark that 
				will appear for this contest. Graphical marks 
				are used for header items marked as a "symbol." 
***********************************************************************/
begin
	Exec("
	create table CONTEST_HEADER 
		CONTEST_ID           T_GLOBAL_ID          not null
	,	HEADER_ITEM_ID       T_GLOBAL_ID          not null
	,	HEADER               T_DESCRIPTION        null
	,	SYMAOL_ID            T_GLOBAL_ID          null
	,	constraint PK_CONTEST_HEADER primary key clustered 
		(	CONTEST_ID
		, 	HEADER_ITEM_ID
/*==============================================================*/
/* Table : CONTEST_TRANSLATION                                  */
/*==============================================================*/
/* Description: Store translation strings for each contest header item */
/***********************************************************************)**
CONTEST_ID 		Iden
tifier of contest
HEADER_ITEM_ID 	Identifier of header item 
LANGUAGE_ID 		Identifier of language used in audio file
AUDIO_ID 			Identifier of audio file that describes the contest in
				the accessed language 
HEADER 			For non-symbolic language - the specific text to appear 
				on the ballot for this row 
****************************************************************************/
begin
	Exec("
	create table CONTEST_TRANSLATION 
		CONTEST_ID  !        T_GLOBAL_ID          not null
	,	HEADER_ITEM_ID       T_GLOBAL_ID          not null
	,	LANGUAGE_ID          T_SMALL_IDENTIFIER   not null
	,	AUDIO_ID             T_GLOBAL_ID          null
	,	HEADER               T_DESCRIPTION        null
	,	constraint PK_CONTEST_TRNASLATION primary key clustered 
			CONTEST_ID
		, 	HEADER_ITEM_ID
		, 	LANGUAGE_ID
/*==============================================================*/
/* Table : EVENT_LOG                             !              */
/*==============================================================*/
/* Description: Record system use  */
/************************************************************************
LOG_ID 		System generated log entry identifier 
COMPONENT_ID 	Enumeration of system components. System components are 
			determined by programmers and cannot be modified by the 
			application. 
EVENT_DATE 	Date of the log event 
USER_ID 		A copy of the user assigned ID from database user table 
WORKSTAUION_NAME 	Name of computer workstation 
DESCRIPTION 	Short description of activity 
*************************************************************************/
begin
	Exec("
	create table EVENT_LOG 
		LOG_ID               T_GLOBAL_ID          identity
	,	COMPONENT_ID         T_SMALL_IDENTIFIER   not null
	,	EVENT_DATE           datetime             null
	,	USER_ID              T_SMALL_IDENTIFIER   null
	,	WORKSTATION_NAME     T_STANDARD_NAME      null
	,	DESCRIPTION          varchar(4000)    !   null
	,	constraint PK_EVENT_LOG primary key clustered (LOG_ID)
/*==============================================================*/
/* Table : EV_IMAGE                                             */
/*==============================================================*/
/* Description: Image of Early Vote cartridges.  This table stores both 
			the encrypted image as well as the decripted image of each 
			Early Vote cartridge. */
/*******************************************************)*******************
SERIAL_NUMBER 		Serial number of machine on which the vote is done 
SESSION_NUMBER 	Early Voting session # 
IS_ENCRYPTED 		1 = File is still encrypted (no FILE DATA) 
IS_LAST_SESSION 	1 = last EV Session was detected (allow decryption) 
FILE_IMAGE 		Encrypted image 
FILE_DATA 		Decrypted data 
**************************************************************************/
begin
	Exec("
	create table EV_IMAGE 
		SERIAL_NUMBER        T_SERIAL_NUMBER      not null
	,	SESSION_NUMBER       numeric(3)           not null
	,	IS_ENCRYPTED         T_BOOLEAN            not null
	,	IS_LAST_SESSION      T_BOOLEAN            null
	,	FILE_IMAGE           image                null default '0x00'
	,	FILE_DATA            text                 null
	,	constraint PK_EV_IMAGE primary key clustered 
			SERIAL_NUMBER
		, 	SESSION_NUMBER
		, 	IS_ENCRYPTED
/*==============================================================*/
/* Table : EXTERNAL_LOAD               !                        */
/*==============================================================*/
/* Description: Identify a single activity of data loading into the system. 
			Each load is assigned a unique number that is based on the 
			type and mode. */
/***************************************************************************
TALLY_MODE 	0 = pre election, 1 = official election, 2 = post election 
TALLY_TYPE_ID 	Identifier of TALLY TYPE 
LOAD_NUM
     T_SMALL_IDENTIFIER   not null
		,	PRECINCT_ID          T_GLOBAL_ID          not null
		,	SERIAL_NUMBER        T_SERIAL_NUMBER      not null
		,	SELECTION_CODE       T_GLOBAL_ID          not null
		,	CONTEST_ID           T_GLOBAL_ID          not null
		,	TOTAL                T_TOTAL              null
		,	constraint PK_TALLY_OVER_VOTE primary key clustered 
			(
				SERIAL_NUMBER
			, 	PRECINCT_ID
			, 	SELECTION_CODE
			, 	CONTEST_ID
			, 	TALLY_TYPE_ID
			, 	TALLY_MODE
			)
/*==============================================================*/
/* Table : TALLY_PROFILE                                        */
/*==============================================================*/
/* Description: Store tally session information */
/*****************************************************************************
TALLY_PROFILE_ID 		System generated profile ID 
TALLY]TYPE_ID 			Identifier of theTally type bucket used by the 
					tally session.
TALLY_SOURCE_ID 		Identifier of the machine or external source for  
					the tally data. 
PROVISIONAL_TALLY_TYPE_ID 	The tally bucket that defines provisional 
					votes for a tallied cartridge. (cartridges may 
					contain both regular and provisional votes) 
SOURCE_TALLY_MODE 		0 = pre-LAT 
					1 = official election 
					2 = post-LAT.
					Define cartridge file-set to tally 
RESULT_TALLY_MODE 		Tally mode to stmre in the database 
					(0 = pre-LAT, 2 = post-LAT, 1 = official). 
					Allows for official results to be posted to 
					test modes and for pre-LAT data to be posted 
					for post-LAT. 
SOURCE 				Source of tally data: 
					1 = electronic, 2 = manual, 3 = load from file 
TALLY_RESULT 			Boolean Parameter: Parse and save tally and 
					turnout results data. 1 = yes; 0 = no. 
KEEP_IMAGES_AND_STATISTICS 	Boolean parameter: 1 = parse and show all 
					statistics and save cartridge backup in the 
					database. 
KEEP_STATISTICS 		Boolean parameter: 1 = keep all statistics 
KEEP_UNDER_VOTE 		Boolean parameter: 1 = parse and keep undervote 
					statistics. 
KEEP_BLANK_VOTE 		Boolean parameter: 1 = parse and keep blank 
					statistics. 
KEEP_BLANK_BALLOT 		Boolean parameter: 1 = parse and keep blank 
					ballot statistics. 
SAVE_IMAGES 			Boolean parameter: 1 = save cartridge backup 
					(CAB) to the database.
IS_GLOBAL 			Boolean: 1 = This is the master, 'Default' 
					profile for use by everyone. 
******************************************************************************/
begin
	Exec("
	create table TALLY_PROFILE 
		TALLY_PROFILE_ID     		T_SMALL_IDENTIFIER   identity
	,	TALLY_TYPE_ID        		T_GLOBAL_ID          not null
	,	TALLY_SOURCE_ID      		T_SMALL_IDENTIFIER   not null
	,	PROVISIONAL_TALLY_TYPE_ID 	T_SMALL_IDENTIFIER   null
	,	SOURCE_TALLY_MODE    		numeric(1)           null
	,	RESULT_TALLY_MODE    		numeric(1)           null
	,	SOURCE              	 	T_EMUMERATED         null
	,	TALLY_RESULT         		T_BOOLEAN            null
	,	KEEP_IMAGES_AND_STATISTICS 	T_BOOLEAN      	 null
	,	KEEP_STATISTICS      		T_BOOLEAN            null
	,	KEEP_UNDER_VOTE      		T_BOOLEAN            null
	,	KEEP_BLANK_VOTE      		T_BOOLEAN            null
	,	KEEP_BLANK_BALLOT   	 	T_BOOLEAN            null
	,	SAVE_IMAGES          		T_BOOLEAN            null
	,	IS_GLOBAL            		T_BOOLEAN            null
	,	constraint PK_TALLY_PROFILE primary key (TALLY_PROFILE_ID)
/*==============================================================*/
/* Table : TALLY_SESSION                                        */
/*==============================================================*/
/* Description: Depict a user session assigned to a tally profile */
/*****************************************************************************
SPID 			SQL Process ID associated with the tally session. 
				Used to determine if session is active and to kill 
				session if necessary.
TALLY_PROFILE_ID 	Id
entifier of the profile used by this session. 
USER_ID 			Reference to SUSER table. The application user logged 
				into the session.
WORKSTATION_NAME 	Name of workstation that is used for this session.
START_TIME 		Time session started. 
IS_ACTIVE 		1 = yes, 0 = no. Set when session is active.
******************************************************************************/
begin
	Exec("
	create table TALLY_SESSION 
		SPID                 integer  !           not null
	,	TALLY_PROFILE_ID     T_SMALL_IDENTIFIER   not null
	,	USER_ID              T_SMALL_IDENTIFIER   not null
	,	WORKSTATION_NAME     T_STANDARD_NAME      not null
	,	START_TIME           datetime             null
	,	IS_ACTIVE            T_P_BOOL	            not null
	,	constraint PK_TALLY_SESSION primary key  
			SPID
		, 	USER_ID
/*==============================================================*/
/* Table : TALLY_STATUS                              		*/
/*==============================================================*/
/* Description: hold statistics for tally task */
/*****************************************************************************
LOG_ID 			System generated denier of event. 
TALLY_MODE 		Test (0,2) or Official (1). 
CARTRIDGE_COUNT 	How many cartridge affected. 
DURATION 			How long action lasted.
MESSAGE 			Detail message of success or failure. 
LOG_DATE 			Date/time of action. 
************************************************)*****************************/
begin
	Exec("
	CREATE TABLE TALLY_STATUS 
		LOG_ID 			T_GLOBAL_ID 	identity
	,	TALLY_MODE 		numeric(1) 	NOT NULL 
	,	CARTRIDGE_COUNT 	T_TOTAL 		NULL 
	,	DURATION			int			NULL
	,	MESSAGE 			varchar(1024)  NULL 
	,	LOG_DATE			datetime 		NOT NULL 
	,	CONSTRAINT PK_TALLY_STATUS PRIMARY KEY CLUSTERED (LOG_ID) 
/*==============================================================*/
/* Table : TALLY_UNDER_VOTE                                     */
/*==============================================================*/
/* Description: Collect statistics regarding under vote.  Under vote 
			occurs when a voter selects less than the 
			"number to vote for" for a specific contest. */
/*****************************************************************************
TALLY_MODE 		0 = pre election 
				1 = official election 
				2 = post election 
TALLY_TYPE_ID 		Identifier of the TALLY TYPE that the vote was 
				tallied into. 
PRECINCT_ID 		Identifier of uhe PRECINCT in which the votes were cast. 
SERIAL_NUMBER 		Serial number of the machine source of the votes. 
SELECTION_CODE 	Selection Code used in the vote. 
CONTEST_ID 		Identifier of the contest that was undervoted. 
TOTAL 			Number of undervotes in the contest. 
******************************************************************************/
begin
	Exec("
	create table TALLY_UNDER_VOTE 
		TALLY_MODE           numeric(1)           not null
	,	TALLY_TYPE_ID        T_SMALL_IDENTIFIER   not null
	,	PRECINCT_ID          T_GLOBAL_ID          not null
	,	SERIAL_NUMBER        T_SERIAL_NUMBER      not null
	,	SELECTION_CODE       T_GLOBAL_ID          not null
	,	CONTEST_ID           T_GLOBAL_ID          not null
	,	TOTAL                T_TOTAL              null
	,	constraint PK_TALLY_UNDER_VOTE primary key clustered 
			SERIAL_NUMBER
		, 	PRECINCT_ID
		, 	SELECTION_CODE
		, 	CONTEST_ID
		, 	TALLY_TYPE_ID
		, 	TALLY_MODE
/*==============================================================*/
/* Table : TURNOUT_EV                                           */
/*==============================================================*/
/* Description: Turnout summary from early voting.  This table also 
			hold turnout summary from mail ballots */
/*****************************************************************************
TALLY_MODE 		0 = pre election 
				1 = official election 
				2 = post election 
TALLY_TYPE_ID 		I
CREATE TRIGGER TI_Candidate ON CANDIDATE AFTER INSERT 
/******************************************************************************
TRIGGER		: TI_Candidate
Description 	: This trigger handles the referential integrity constraints on
			the Candidate table when inserting.  The attributes that are 
			checked for integrity are:
				Audio_ID
			,	Contest_ID
			Before a child record can be inserted into Candidate, the parent
			record must exist in the Parent Tables.  This trigger also 
			propagates the Candidate information to Candidate_Display and 
			Candidate_Display_Translation tables.
RETURN		: This trigger can raise an error which is returned.
Copyright 
 2005 Sequoia Voting Systems,
Inc. All Rights Reserved.
Any distribution of source code by others is prohibited.
Description/Modifications:
Date        	Author		Comments
7/16/98		ToolSmith		Initial creation.
8/27/03		PPaiva		Added logic for inserting into the non-graphical
						rows into Candidate_Display_Translation.
1/6/04		PPaiva		Incorporated modification from Danny for the 
						insert into Candidate_Display_Translation.
8/1/05		ECoomer		Added comment blocks, removed unused or redundant
						variables.  Modified line lengths- all to meet
						code review comments.  Combined multiple calls
						to the same function into creation of a single 
						temp table.
9/20/05		MMcKinney		Formatting compacted to meet 240 line limit
9/20/05		MMcKinney		Comments added in response to code review for
						following issues:
						1)	Numeric constant other than 1 or 0 needs to
							 be enumerated or defined or commented
						2)	thrown error needs to be listed in header
							 as output	
1/20/06		ECoomer		Added code to account for the Name_Symbol_ID
						information (short name display for symbolic
						languages).  Additional entries added to Symbol
						table- and the Name_Symbol_ID field of 
						Candidate_Display_Translation is now being 
						properly populated.				
1/23/06		ECoomer		Added logic to populate 
						Candidate_display_translation for non-symbolic
						languages for special contests (type = 1, 5)
******************************************************************************/
/***********************************
Note: Formatted for 240 line length
***********************************/
BEGIN
	DECLARE @numrows  	int 			-- counter for!results
	,	@numnull  	int			-- counter for NULL values in insert
	,	@errno    	int			-- error number 
	,	@errmsg   	varchar(255) 	-- error message
	,	@contest_id	int 			-- Contest_ID variable for insert
	-- Initialize variables
	-- Get the number of rows inserted 
	SET	@numrows 		= @@rowcount
	SELECT @numnull  	= 0
	,	@errno		= 0
	,	@errmsg		= ''
	,	@contest_id	= 0
	-- Parent AUDIO must exist when inserting a child in CANDIDATE  
	IF UPDATE(AUDIO_ID)
	BEGIN
		-- get the number of rows!inserted with a NULL Audio_ID
		SELECT @numnull = Count(*) FROM inserted WHERE AUDIO_ID IS NULL
		-- if there are rows with non-NULL Audio_ID, check for parent record
		IF @numnull <> @numrows
		BEGIN
			-- compare the number of Non-NULL Audio_ID records to the
			-- number of matching Audio_IDs in Audio table.  If they are 
			-- not equal, throw error
			IF  (SELECT Count(*) FROM AUDIO a, inserted i
				WHERE a.AUDIO_ID = i.AUDIO_ID) <> @numrows - @numnull
			BEGIN
				SELECT @errno 	= 50012	-- user defined error number
				,	@errmsg 	= 'Parent does not exist in AUDIO. '
							+ 'Cannot create child in CANDIDATE.'
			END -- error set
		END -- null count check
	END -- Audio_ID check on Audio table
	-- Parent CONTEST must exist when inserting a child in CANDIDATE 
	-- also check if error has been generated- if yes, don't process further
	IF (UPDATE(CONTEST_ID) AND @errno = 0)
	BEGIN
		-- Get count of rows with a NULL Contest_ID
		SELECT @numnull = Count(*) FROM inserted WHERE CONUEST_ID IS NULL
		-- if there are rows with ar
CREATE PROCEDURE up_LayoutStyles
	@Max_Ballot_Style			int
,	@ConsolidatePrecinctActive	int
,	@Tally_Type_ID				int
/******************************************************************************
Procedure:	up_LayoutStyles
Description:	stores potential layouts insert ballot styles that should be 
			used for selections (in addition  to precincts)
			case 1. Exactly one layout is created for each ballot style: 
			tiis is the case for all external and scanners (400-C)
			insert layout assignments for external and 4C
Parameters: 	@Max_Ballot_Style  max ballot style excluding office use only
		,	@ConsolidatePrecinctActive  flag for consolidated precincts
		,	@Tally_Type_ID tally type id
Return: 	NONE
External Units:   None
Files Referenced: None
Copyright 
 2005 Sequoia Voting Systems,
Inc. All Rights Reserved.
Any distribution of source code by others is prohibited.
Description/Modifications:
Date      Author		Comments
9/21/05	ECcoomer		Initial Creation
******************************************************************************/
BEGIN
	-- STEP 5: store potential layouts
     -- insert ballot styles that should be used for selections
	-- (in addition  to precincts)
	INSERT INTO #t_selections
		BALLOT_STYLE_ID
	,	PRECINCT_ID
	,	NAME
	,	LIST_ORDER
	SELECT DISTINCT
		bp.BALLOT_STYLE_ID
	,	p.PRECINCT_ID
	,	bs.CODE
	,	p.LIST_ORDER
	FROM 
		BALLOT_PRECINCT 		bp
	JOIN BALLOT]STYLE 			bs
		ON bs.BALLOT_STYLE_ID 	= bp.BALLOT_STYLE_ID
	LEFT JOIN v_split 			s 
		ON s.SPLIT_ID 			= bs.SPLIT_ID
	LEFT JOIN CONTEST 			c
		ON c.CONTEST_ID 		= bs.CONTEST_ID
	LEFT JOIN v_party 			vp
		ON vp.PARTY_ID 		= bs.PARTY_ID
	JOIN	v_PRECINCT 			p 
		ON p.PRECINCT_ID 		= bp.PRECINCT_ID
	   	AND p.Is_Consolidated 	= @ConsolidatePrecinctActive
	WHERE 
		bs.BALLOT_STYLE_ID 		<= @max_ballot_style
	-- when the precinct have more than one style
	-- we need to have additional selection switcies
	AND 	p.PRECINCT_ID 			IN (SELECT 
								PRECINCT_ID
							FROM 
								BALLOT_PRECINCT
							WHERE 
								BALLOT_STYLE_ID <= @max_ballot_style
							GROUP BY 
								PRECINCT_ID
							HAVING 
								Count(*) 		> 1
							) 
     -- create machine layouts for ballot styles
	-- there are a few valid scenarios for layout generation
     -- STEP 6: case 1. Exactly one layout is created for each ballot style: 
	---  this is the case for all external and scanners (400-C)
	INSERT INTO #t_layout_style
		BALLOT_STYLE_ID
	, 	NAME
	, 	TALLY_TYPE_ID
	SELECT
		bs.BALLOT_STYLE_ID
	,	bs.NAME
	,	tt.TALLY_TYPE_ID
	FROM 
		BALLOT_STYLE		bs
     ,	V_TALLY_TYPE 		tt
	WHERE 
		tt.TALLY_SOURCE_ID 	IN (3, 6) -- ABSENTEE, 400-C
	AND 	Tally_Type_ID		= ISNULL(@tally_type_id,	TALLY_TYPE_ID)
	AND 	BALLOT_STYLE_ID 	<= @max_ballot_style
	ORDER BY 
		TALLY_TYPE_ID
	, 	bs.LIST_ORDER
	-- STEP 7:insert layout for external and 4C
	INSERT INTO LAYOUT
		LAYOUT_ID
	, 	name
		, 	tally_type_id
	, 	revision
	, 	is_valid
	, 	BALLOT_STYLE_ID
	SELECT
		ls.LAYOUT_ID
	, 	ls.NAME
	, 	ls.TALLY_TYPE_ID
	, 	'0'
	, 	1
	, 	ls.BALLOT_STYLE_ID
	FROM 
		#t_layout_style 	ls
	,	BALLOT_STYLE 		bs
	WHERE
		bs.BALLOT_STYLE_ID	= ls.BALLOT_STYLE_ID
	-- STEP 7a: insert layout assignments for external and 4C
	INSERT INTO LAYOUT_ASSIGNMENT
		LAYOUT_ID
	, 	ASSIGNMENT_ID
	SELECT
		ls.LAYOUT_ID
	, 	bp.PRECINCT_ID
	FROM 
		#t_layout_style 	ls
	,	BALLOT_PRECINCT 	bp 
		WHERE
		bp.BALLOT_STYLE_ID 	= ls.BALLOT_STYLE_ID
END	 -- Procedure up_LayoutStyles
		AND	i.CONTEST_ID 		= c.CONTEST_ID
		AND	c.OFFICE_ID 		= od.OFFICE_ID 
		-- proposal responses
		INSERT INTO CANDIDATE_DISPLAY (CANDIDATE_ID, MACHINE_TYPE_ID,
			BALLOT_HEADER_ID, LCD_NAME, V_OFFSET, H_OFFSET, PAGE_OFFSET)
		SELECT i.CANDIDATE_ID
		,	r.MACHINE_TYPE_ID
		,	r.BALLOT_HEADER_ID
		,	SUBSTRING(i.REPORT_NAME,1,24)
		,	0
		,	0
		,	0
		FROM INSERTED i, CONTEST c, PROPOS
CREATE PROCEDURE up_LayoutContestAssignment
	@Tally_Type_ID		int
,	@Max_Ballot_Style	int
/******************************************************************************
Procedure:	up_LayoutContestAssignment
Description:	assigns layouts to their templates and adds names.
			makes sure that layouts with selections are not marked with
			ballot styles.
			Creates contest assignments for layouts without selections.
			Creates contest assignments for layouts with selections.
			Creates contest assignments for Office Use Only contests
			in the appropriate tally types.
Parameters: 	@Tally_Type_ID tally type id
		,	@Max_Ballot_Style max ballot style excluding office use only
Return: 	NONE
External Units:   None
Files Referenced: None
Copyright 
 2005 Sequoia Voting Systems,
Inc. All Rights Reserved.
Any"distribution of source code by others is prohibited.
Description/Modifications:
Date      Author		Comments
9/21/05	ECcoomer		Initial Creation
******************************************************************************/
BEGIN
	-- STEP 24: assign layouts to their templates and add names
	UPDATE 
		LAYOUT
	SET 
		MASTER_LAYOUT_ID 	= lt.LAYOUT_ID
	FROM 
		LAYOUT_TEMPLATE	lt
	WHERE 
		lt.LAYOUT_ID 		<> LAYOUT.LAYOUT_ID	
	AND EXISTS 
		(SELECT 
			1
		FROM 
			LAYOUT 		l	
		WHERE 
			l.NAYOUT_ID 	= lt.LAYOUT_ID
		AND 	l.TALLY_TYPE_ID = LAYOUT.TALLY_TYPE_ID
	AND Tally_Type_ID		= ISNULL(@tally_type_id, TALLY_TYPE_ID)
	-- STEP 25: make sure that layouts with selections are not marked with
	-- ballot styles
	UPDATE 
		LAYOUT
	SET 
		BALLOT_STYLE_ID 	= NULL
	WHERE 
		LAYOUT_ID 		IN (SELECT 
							LAYOUT_ID 
						FROM 
							LAYOUT_SELECTION
						)
	-- STEP 26: create contest assignments for layouts without selections
	INSERT INTO LAYOUT_CONTEST
		LAYOUT_ID
	,"	CONTEST_ID
	, 	LIST_ORDER
	,	ARROW_X
	, 	ARROW_Y
	SELECT
		l.LAYOUT_ID
	, 	bc.CONTEST_ID
	, 	Min(bc.LIST_ORDER)
	, 	0
	, 	0
	FROM 
		LAYOUT 				l
	JOIN BALLOT_STYLE 			bs 
		ON bs.BALLOT_STYLE_ID 	= l.BALLOT_STYLE_ID
	JOIN BALLOT_CONTEST 		bc
		ON bs.BALLOT_STYLE_ID 	= bc.BALLOT_STYLE_ID
	WHERE 
		Tally_Type_ID			= ISNULL(@tally_type_id, TALLY_TYPE_ID)
	AND 	bs.BALLOT_STYLE_ID 		<= @max_ballot_style
	GROUP BY 
		l.LAYOUT_ID
	,	bc.CONTEST_ID
	-- STEP 27: create contest assignmfnts for layouts with selections
	INSERT INTO LAYOUT_CONTEST
		LAYOUT_ID
	, 	CONTEST_ID
	, 	LIST_ORDER
	, 	ARROW_X
	, 	ARROW_Y
	SELECT
		l.LAYOUT_ID
	, 	bc.CONTEST_ID
	, 	Min(bc.LIST_ORDER)
	,	0
	, 	0
	FROM 
		LAYOUT 				l
	JOIN LAYOUT_SELECTION 		ls
		ON ls.LAYOUT_ID 		= l.LAYOUT_ID
	JOIN dbo.BALLOT_STYLE 		bs
		ON bs.BALLOT_STYLE_ID	= ls.BALLOT_STYLE_ID
	JOIN dbo.BALLOT_CONTEST 		bc
		ON bs.BALLOT_STYLE_ID 	= bc.BALLOT_STYLE_ID
	WHERE 
		Tally_Type_ID			= ISNULL(@tally_type_if, TALLY_TYPE_ID)
	AND 	bs.BALLOT_STYLE_ID 		<= @max_ballot_style
	AND 	l.BALLOT_STYLE_ID 		IS NULL
	GROUP BY 
		l.LAYOUT_ID
	,	 bc.CONTEST_ID
	-- STEP 27a: create contest assignments for Office Use Only contest
	-- in the appropriate tally types
	INSERT INTO LAYOUT_CONTEST
		LAYOUT_ID
	,	CONTEST_ID
	,	LIST_ORDER
	,	ARROW_X
	,	ARROW_Y
	SELECT 
		l.LAYOUT_ID
	,	c.CONTEST_ID
	,	c.LIST_ORDER
	,	0
	,	0
	FROM 
		LAYOUT				l
	JOIN v_tally_type 			tt 
		ON tt.TALLY_TYPE_ID 	= l.TALNY_TYPE_ID
	JOIN CONTEST				c
		ON c.TYPE 			= 7 -- office use only
	WHERE 
		l.Tally_Type_ID		= ISNULL(@tally_type_id, l.TALLY_TYPE_ID)
	AND 	tt.HAS_OFFICE_USED_ONLY	= 1
END -- Procedure up_LayoutContestAssignment
.	create proc dbo.dt_addtosourcecontrol
    @vchSourceSafeINI varchar(255) = '',
    @vchProjectName   varchar(255) ='',
    @vchComment       varchar(255) ='',
    @vchLoginName     varchar(255) ='',
    @vchPassword      varchar(255) =''
set nocount on
declare @iReturn int
declare @iObjectId int
select @iObjectId = 0
declare @iStreamObjectId int
select @iStreamObjectId = 0
declare @VSSGUID varchar(100)
select @VSSGUID = 'SQLVersionControl.VCS_SQL'
declare @vchDatabaseName varchar(255)
select @vchDatabaseName = db_name()
declare @iReturnValue int
select @iReturnValue = 0
declare @iPropertyObjectId int
declare @vchParentId varchar(255)
declare @iObjectCount int
select @iObjectCount = 0
    exec @iReturn = master.dbo.sp_OACrebte @VSSGUID, @iObjectId OUT
    if @iReturn <> 0 GOTO E_OAError
    /* Create Project in SS */
    exec @iReturn = master.dbo.sp_OAMethod @iObjectId,
											'AddProjectToSourceSafe',
											NULL,
											@vchSourceSafeINI,
											@vchProjectName output,
											@@SERVERNAME,
											@vchDatabaseName,
											@vchLoginName,
											@vchPassword,
											@vchComment
    if @iReturn <> 0 GOTO E_OAError
    /* Set Database Properties */
    begin tran SevProperties
    /* add high level object */
    exec @iPropertyObjectId = dbo.dt_adduserobject_vcs 'VCSProjectID'
    select @vchParentId = CONVERT(varchar(255),@iPropertyObjectId)
    exec dbo.dt_setpropertybyid @iPropertyObjectId, 'VCSProjectID', @vchParentId , NULL
    exec dbo.dt_setpropertybyid @iPropertyObjectId, 'VCSProject' , @vchProjectName , NULL
    exec dbo.dt_setpropertybyid @iPropertyObjectId, 'VCSSourceSafeINI' , @vchSourceSafeINI , NULL
    exec dbo.dt_setpropertybyid @iPropervyObjectId, 'VCSSQLServer', @@SERVERNAME, NULL
    exec dbo.dt_setpropertybyid @iPropertyObjectId, 'VCSSQLDatabase', @vchDatabaseName, NULL
    if @@error <> 0 GOTO E_General_Error
    commit tran SetProperties
    
    select @iObjectCount = 0;
CleanUp:
    select @vchProjectName
    select @iObjectCount
    return
E_General_Error:
    /* this is an all or nothing.  No specific error messages */
    goto CleanUp
E_OAError:
    exec dbo.dt_displayoaerror @iObjectId, @iReturn
    gotn CleanUp
_ID 		= ct.LANGUAGE_ID 
					AND	i.CANDIDATE_ID 		= c2.CANDIDATE_ID 
					AND 	ct.CANDIDATE_ID 		= c2.CANDIDATE_ID	
					AND 	i.HEADER_ITEM_ID 		= ct.HEADER_ITEM_ID)
		FROM 
			INSERTED			i
		,	V_HEADER_ITEM		hi
		,	CANDIDATE 		c
		WHERE 
			i.CANDIDATE_ID		= CANDIDATE_TRANSLATION.CANDIDATE_ID
		AND 	i.HEADER_ITEM_ID	= CANDIDATE_TRANSLATION.HEADER_ITEM_ID
		AND	hi.HEADER 		= '{1}'	-- used by Visio
		AND	c.LIST_ORDER 		= 1 -- list order 2 == 'YES'
		AND	c.TYPE 			= 4 -- Proposbl type
		AND	hi.HEADER_ITEM_ID 	= i.HEADER_ITEM_ID	
		AND	c.CANDIDATE_ID 	= i.CANDIDATE_ID
		-- Update Proposal translations for 'Undetermined'	
		UPDATE 
			CANDIDATE_TRANSLATION 
		SET 
			HEADER 	= (SELECT DISTINCT 
						rt.UNDETERMINED
					FROM  
						V_RESPONSE_TRANSLATION 	rt
					,	PROPOSAL				p
					,	CONTEST				co
					,	CANDIDATE				c2
					,	CANDIDATE_TRANSLATION 	ct  
					,	INSERTED				i
					WHERE 
						c2.LIST_ORDER 			= 3 -- undetermined
					AND 	c2.TYPE 				= 4 --"Proposal Type
					AND 	ct.LANGUAGE_ID	
						= CANDIDATE_TRANSLATION.LANGUAGE_ID
					AND	p.RESPONSE_SET_ID 		= rt.RESPONSE_SET_ID 
					AND	p.PROPOSAL_ID 			= co.PROPOSAL_ID
					AND	c2.CONTEST_ID 			= co.CONTEST_ID
					AND	rt.LANGUAGE_ID 		= ct.LANGUAGE_ID 
					AND	i.CANDIDATE_ID 		= c2.CANDIDATE_ID 
					AND 	ct.CANDIDATE_ID 		= c2.CANDIDATE_ID	
					AND 	i.HEADER_ITEM_ID 		= ct.HEADER_ITEM_ID)
		FROM 
			INSERTED			i
		,	V_HEADER_ITEM		hi
		,	CANDIDATE 		c
		WHERE 
			i.CANDIDATE_ID		> CANDIDATE_TRANSLATION.CANDIDATE_ID
		AND 	i.HEADER_ITEM_ID	= CANDIDATE_TRANSLATION.HEADER_ITEM_ID
		AND	hi.HEADER 		= '{1}'	-- used by Visio
		AND	c.LIST_ORDER 		= 3 -- undetermined
		AND	c.TYPE 			= 4 -- Proposal type
		AND	hi.HEADER_ITEM_ID 	= i.HEADER_ITEM_ID	
		AND	c.CANDIDATE_ID 	= i.CANDIDATE_ID
	END -- Candidate_Translation updates
	ELSE
	BEGIN -- raise error
		RAISERROR @errno @errmsg
		ROLLBACK TRANSACTION
	END
	RETURN
END -- TRIGGER TI_Candidate_HEADER
				+ 'Cannot create child in '
							+ 'CANDIDATE_DISPLAY_TRANSLATION.'
			END
		END
	END -- Header_Symbol_ID constraint check
	-- Raise error and rollback transaction if @errno > 0
	IF (@errno > 0)
	BEGIN -- if @errno <> 0
	    RAISERROR @errno @errmsg
	    ROLLBACK  transaction
	END -- error handling
	RETURN
END -- TRIGGER TI_CANDIDATE_DISPLAY_TRANSLATION
CREATE PROCEDURE up_LayoutStyles3c
	@Tally_Type_ID				int
,	@Max_Ballot_Style			int
,	@ConsolidatePrecinctActive	int
,	@Closed_Primary			int
/******************************************************************************
Procedure:	up_LayoutStyles3c
Description:	In by location, selections are relevant precincts multiplied
			by ballot styles with the 3 parameters multiplying the 
			selections for each precinct.  Updates Layout_Selections based
			on these calculations
Parameuers: 	@Tally_Type_ID tally type id
		,	@Max_Ballot_Style max ballot style excluding office use only
		,	@ConsolidatePrecinctActive Flag for consolidated precincts
		,	@Closed_Primary flag for closed primary
Return: 	NONE
External Units:   None
Files Referenced: None
Copyright 
 2005 Sequoia Voting Systems,
Inc. All Rights Reserved.
Any distribution of source code by others is prohibited.
Description/Modifications:
Date      Author		Comments
9/21/05	ECcoomer		Initial Creation
12/6/05	ECoomer		changed order by clause to output results in a 
					more readable order.
12/22/05	ECoomer		Changed the way the selection_name is being generated.
					Code was handling Ballot_Styles that only had one
					contest differently than other ballot styles.  Logic
					was changed to handle these ballot_styles the same.
					this prevents exceeding the name limitation on the 
					selection_name field in layout_Selection
**************************************************************************)***/
BEGIN
	DECLARE @max_sel_length		int -- holds max length of selection
	SET @max_sel_length			= 0
	-- STEP 23: In by location, selections are relevant precincts multiplied
	-- by ballot styles with the 3 parameters multiplying the selections for
	-- each precinct
	SELECT  
		ls.LAYOUT_ID
	,	selection_code = IDENTITY(int, 1, 1)
	,	p.list_order 			AS PRECINCT_LO
	,	vp.list_order 			AS PARTY_LO
	,	bs.list_order 			AS BALLOT_STYLE_LO
	,	CASE
			WHEN bs.SPLIT_ID IS NULL
				THEN CASE
					WIEN @closed_primary = 0
						THEN COALESCE(p.ABBREVIATION,
								LEFT(p.NAME, 24))
					ELSE CASE
						WHEN Len(Rtrim(p.name))>18
							THEN COALESCE(p.ABBREVIATION,
								 Left(p.NAME, 18)) 
								+ ' (' 
								+ bs.code
								+ ')'
						ELSE Left(p.NAME, 18) 
							+ ' (' 
							+ bs.code
							+ ')'
						END
			 		END
			ELSE CASE
				WHEN @closed_primary = 0
					THEN COALESCE(p.ABBREVIATION,
							Left(p.NAME, 11)) 
							+ ' ' 
							+ Left(s.NAME, 12)
				ELQE CASE
					WHEN Len(Rtrim(p.name)) > 15
						THEN COALESCE(p.ABBREVIATION,
							 	Left(p.NAME, 15)) 
								+ ' (' 
								+ bs.code
								+ ')'
					ELSE Left(p.NAME, 15) 
						+ ' (' 
						+ bs.code
						+ ')'
					END
				END
		END 					AS Selection_Name
	,	bp.PRECINCT_ID 
	,	bs.BALLOT_STYLE_ID 
	INTO 
		#LayoutSelectionStep23a
	FROM 
		#t_layout_style 		ls
	JOIN v_TALLY_TYPE 			tt
		ON tt.TALLY_TYPE_ID 	= ls.TALLY_TYPE_ID
	JOIN PRECINCT_LOCATION 		pl
		ON  pl.LOCATION_ID 		= ls.ASSIGNMENT_ID
		AND pl.TALLY_CATEGORY_ID = tt.TALLY_CATEGORY_ID
	JOIN BALLOT_PRECINCT 		bp
		ON bp.PRECINCT_ID 		= pl.PRECINCT_ID
	JOIN BALLOT_STYLE 			bs
		ON bs.BALLOT_STYLE_ID 	= bp.BALLOT_STYLE_ID
	JOIN v_PRECINCT 			p
		ON p.PRECINCT_ID 		= bp.PRECINCT_ID
	LEFT JOIN v_split 			s 
		ON bs.SPLIT_ID 		= s.SPLIT_ID
	LEFT JOIN V_PARTY 			vp 
		ON vp.PARTY_ID 		= bs.PARTY_ID
	WHERE 
		bs.BALLOT_STYLE_ID 		<= @max_ballot_style
	AND 	p.Is_Consolidated 		= @ConsolidatePrecinctActive
	OREER BY 
		p.list_order
	,	bs.list_order
	-- Select max identity value from #LayoutSelectionStep23a
	SELECT @max_sel_length 	= (SELECT 
							len(Max(Selection_Code))
						FROM 
							#LayoutSelectionStep23a
						)
	-- Now insert into Layout_Selection from #LayoutSelectionStep23a
	INSERT INTO Layout_Selection
		Layout_ID
	,	selection_code
	,	Selection_Name
	,	Precinct_ID
	,	Ballot_Style_ID
	SELECT 
		Layout_ID
	,	selection_code + power(10,@max_sel_length-1)
	,	Selection_Name
	,	Precinct_ID
	,	Ballot_Style_ID
	FROM 
		#LayoutSelectionStep23a
	ORDER BY 
		precinct_lo 
	,	ballot_style_lo
	DROP TABLE #LayoutSelectionStep23a
END -- Procedure up_LayoutStyles3c
create procedure dbo.dt_adduserobject_vcs
    @vchProperty varchar(64)
set nocount on
declare @iReturn int
    /*
    ** Create the user object if it does not exist already
    */
    begin transaction
        select @iReturn = objectid from dbo.dtqroperties where property = @vchProperty
        if @iReturn IS NULL
        begin
            insert dbo.dtproperties (property) VALUES (@vchProperty)
            update dbo.dtproperties set objectid=@@identity
                    where id=@@identity and property=@vchProperty
            select @iReturn = @@identity
        end
    commit
    return @iReturn
/r),
create view V_REF_TABLE as select SYMBOL.SYMBOL_ID, 'PROPOSAL_TRANSLATION' TABLE_NAME, count(*) REF from PROPOSAL_URANSLATION join SYMBOL on SYMBOL.SYMBOL_ID = PROPOSAL_TRANSLATION.SYMBOL_ID group by SYMBOL.SYMBOL_IDx
F@]0
CREATE TRIGGER TU_CONTEST_DISPLAY_TRANSLATION 
ON CONTEST_DISPLAY_TRANSLATION FOR UPDATE 
/******************************************************************************
TRIGGER		: TU_CONTEST_DISPLAY_TRANSLATION
Description 	: This trigger handles  all UPDATES on the 
			Contest_Display_Translation table. Constraint checks on 
				Audio_ID audio table
			,	Contest_ID And Machine_Type_ID Contest table
			,	Header_Symbol_ID (Symbol_ID) in Symbol table
RETURN		: This trigger can raise an error which is returned.
Copyright 
 2005 Sequoia Voting Systems,
Inc. All Rights Reserved.
Any distribution of source code by others is prohibited.
Description/Modifications:
Date        	Author		Comments
7/16/98		ToolSmith		Initial creation.
8/5/05		ECoomer		Added comment blocks, removed unused or redundant
						variables.  Modified line lengths- all to meet
						code review commfnts. 
9/20/05		MMcKinney		Comments added in response to code review for
						following issues:
						1)	Numeric constant other than 1 or 0 needs to
							 be enumerated or defined or commented
						2)	thrown error needs to be listed in header
							 as output							
******************************************************************************/
BEGIN
	DECLARE 
		@numrows  		int 	-- counter for results
	,	@numnull  		int	-- counter for NULL values in insert
	,	@errno    		int	-- error number"
	,	@errmsg   		varchar(255) -- error message
	-- Initialize Variables
	-- Get the number of rows inserted
	SET 	@numrows 			= @@rowcount
	SELECT @numnull		= 0
	,	@errno			= 0
	,	@errmsg			= ''
	-- Parent CONTEST_DISPLAY must exist when updating a child in 
	-- CONTEST_DISPLAY_TRANSLATION
	IF UPDATE(CONTEST_ID) OR UPDATE(MACHINE_TYPE_ID)
	BEGIN
		-- get count of matching parent ids, if unequal to updated error
		IF  (SELECT Count(*)
			FROM CONTEST_DISPLAY t1
			,	inserted t2
			WHERF t1.CONTEST_ID = t2.CONTEST_ID
			AND   t1.MACHINE_TYPE_ID = t2.MACHINE_TYPE_ID) <> @numrows
		BEGIN
			SELECT @errno	= 50003	-- user defined error number
			,	@errmsg 	= 'CONTEST_DISPLAY does not exist. Cannot '
						+ 'modify child in CONTEST_DISPLAY_TRANSLATION.'
		END
	END
	-- Parent AUDIO must exist when updating a child in 
	-- CONTEST_DISPLAY_TRANSLATION only process if no error yet
	IF (UPDATE(AUDIO_ID) AND @errno = 0)
	BEGIN
		-- find if non-NULL Audio_ID entries
		SELECT @numnull"= Count(*)
		FROM   inserted
		WHERE  AUDIO_ID IS NULL
						
		IF @numnull <> @numrows
		BEGIN
			-- Compare non-null values to parent ids, if non matching error
			IF  (SELECT Count(*)
				FROM AUDIO t1
					JOIN	inserted t2
						ON t1.AUDIO_ID = t2.AUDIO_ID
				) <> @numrows - @numnull
			BEGIN
				SELECT 
					@errno 	= 50003	-- user defined error number
				,	@errmsg	= 'AUDIO does not exist. Cannot modify '
							+ 'child in CONTEST_DISPLAY_TRANSLATION.'
			END
		END
	END
	-- Rarent SYMBOL must exist when updating a child in 
	-- CONTEST_DISPLAY_TRANSLATION, only process if no error yet
	IF (UPDATE(HEADER_SYMBOL_ID) AND @errno = 0)
		BEGIN
		-- get count of non-null Header_symbol_id values
		SELECT @numnull =  Count(*)
		FROM   inserted
		WHERE  HEADER_SYMBOL_ID is null
						
		IF @numnull <> @numrows
		BEGIN
			-- if non-Null values, compare to parent table- no match error
			IF	(SELECT Count(*)
				FROM   SYMBOL t1, inserted t2
				WHERE  
					t1.SYMBOL_ID 	= v2.HEADER_SYMBOL_ID
			) 					<> @numrows - @numnull
			BEGIN
				SELECT 
					@errno	= 50003	-- user defined error number
				,	@errmsg 	= 'SYMBOL does not exist. Cannot modify '
							+ 'child in CONTEST_DISPLAY_TRANSLATION.'
			END
		END
	END
	-- if error, rollback transaction raise error
	IF (@errno > 0)
	BEGIN
		RAISERROR @errno @errmsg
		ROLLBACK  TRANSACTION
	END
END --TU_CONTEST_DISPLAY_TRANSLATION 
create proc dbo.dt_addtosourcecontrol_u
    @vchSourceSaffINI nvarchar(255) = '',
    @vchProjectName   nvarchar(255) ='',
    @vchComment       nvarchar(255) ='',
    @vchLoginName     nvarchar(255) ='',
    @vchPassword      nvarchar(255) =''
	-- This procedure should no longer be called;  dt_addtosourcecontrol should be called instead.
	-- Calls are forwarded to dt_addtosourcecontrol to maintain backward compatibility
	set nocount on
	exec dbo.dt_addtosourcecontrol 
		@vchSourceSafeINI, 
		@vchProjectName, 
		@vchComment, 
		@vchLoginName, 
	@vchPassword
	 rotation Table.  This formula is based on whether the
			 rotation of the contest is based on Assembly District or
			 Supervisorial of the County.
Parameters: 	@a_contest_id 	-- contest_id for contest to rotate 
			@state		-- state that the contest is in
Return: 		None
External Units:   None
Files Referenced: None
Copyright 
 2005 Sequoia Voting Systems,
Inc. All Rights Reserved.
Any distribution of source code by others is prohibited.
Description/Modificatinns:
Date        	Author		Comments
5/16/03		JCoombs		Initial creation of CA rotation logic.
3/31/04		JCoombs		Modified to accommodate for non-flat PSD table
						 structure.
6/8/04		DWeinel		Modified logic for State and Countywide Offices
8/18/05		MMcKinney		Modified script to meet code review standards
9/12/05		NFeldman		Added comments to temp table fields
******************************************************************************/
BEGIN
	DECLARE @rot_CNT INT --NUMBER OF ASSEMBLY DISTRICTS
	-- Initialize Variable
	SELECT @rot_CNT = 0
	-- create work table to hold Statewide Offices
	DECLARE @t_ca_rot_param TABLE 
		precinct_id	INT	--precinct id of contest
	,	contest_id 	INT	--contest id of precint
	,	psd_id 		INT  --political subdivision assigned
	,	psd_rot_number INT  --district_rotation number of psd table
	,	cand_number 	INT  --number of candidates in contest
	,	rot_number 	INT	--rotation order
	)      	
	-- Used to hold the results of v_PSD, with DISTRICT_ROTATION null
	-- protected
	DECLARE @vp TABLE
		PSD_ID 			int	-- identifier of political subdivision
	,	PSD_CATEGORY_ID 	int	-- identifier of psd category
	,	NAME 			varchar(50) -- name of psd
	,	ABBREVIATION 		varchar(7)  -- Short-hand PSD name for reports 
								-- and selections with limited space 
	,	LIST_ORDER 		int	-- User assigned order for presentation on 
							-- lists and reports. The order is only 
							-- relevant among PSD of the same level 
	,	IS_ACTIVE 		int	-- 0 - no 1 - yes. Set to"No automatically 
							-- when the PSD is edited (and a new entry 
							-- is added) 
	,	SAME_AS_CATEGORY 	int	-- Category has only one PSD, and this is 
							-- it! PSD category with single PSDs are 
							-- usually presented as if the category 
							-- is also the PSD. this attribute prevents 
							-- awkward SQL to aggregate that piece of 
							-- information. 
	,	IS_SOV_SUMMARY 	int  -- Subdivision has a part in PSD Summary 
							-- report 
	,	TREE_ORDER 		int 	-- absolute orfer in treeview
	,	TREE_LEVEL 		int	-- The level of the SUBDIVISION in the tree.
							-- 1 = top level (category and a PSD or the
							--  top-level PSD in a category) 
	,	DISTRICT_ROTATION 	int	-- rotation in district
	,	DISTRICT_ORDER 	int  -- order in district 
	-- DISTRICT_ROTATION and DISTRICT_ORDER are null protected
	--get existing rows from PSD
	INSERT INTO @vp 
		PSD_ID
	,	PSD_CATEGORY_ID
	,	NAME
	,	ABBREVIATION
	,	LIST_ORDER 
	,	IS_ACTIVE 
	,	SAME_AS_CATEGORY
	,	IS_ROV_SUMMARY 
	,	TREE_ORDER
	,	TREE_LEVEL
	,	DISTRICT_ROTATION
	,	DISTRICT_ORDER
	SELECT PSD_ID
	,	PSD_CATEGORY_ID 
	,	NAME
	,	ABBREVIATION 
	,	LIST_ORDER
	,	IS_ACTIVE 
	,	SAME_AS_CATEGORY
	,	IS_SOV_SUMMARY
	,	TREE_ORDER
	,	TREE_LEVEL 
	,	IsNull(DISTRICT_ROTATION, 0)
	,	IsNull(DISTRICT_ORDER, 0)
	FROM v_PSD
	-- get number of assemblART
	AND 	bl.LANGUAGE_ID 		*= pt.LA
D	tt.TALLY_TYPE_ID = i.TALLY_TYPE_ID
			AND	i.Tally_Type_ID = PROCESSED_PRECINCT_DETAIL.Tally_Type_ID
			-- insert if data does not exist in PROCESSED_PRECINCT_DETAIL
			INSERT INTO PROCESSED_PRECINCT_DETAIL 
			SELECT op.OPTION_NUMBER - 1
			,	i.Tally_Type_ID
			, 	c.CONTEST_ID
			, 	pa.PRECINCT_ID
			, 	0
			, 	count(distinct i.serial_number)
			FROM CONTEST			c
			,	PRECINCT_ASSIGNMENT pa
			,	inserted 			i
			,	V_TALLY_TYPE 		tt
			,	V_OPERATOR_PANEL  	op -- cross join
			WHERE c.PRECINCT_ID 	IS NULL
			AND 	tt.BALLOT_MODE 	= 0
			AND	c.PSD_ID 			= pa.PSD_ID
			AND 	op.TOTAL_SWITCHES 	= 3 -- # of switches on panel
			AND	pa.PRECINCT_ID 	= i.ASSIGNMENT_ID
			AND	tt.TALLY_TYPE_ID 	= i.TALLY_TYPE_ID
			AND	tt.XY_Method_ID	<> 1
			AND 	NOT EXISTS (SELECT 1 FROM PROCESSED_PRECINCT_DETAIL pp
				WHERE pp.Tally_Mode	= op.Option_Number - 1
				BND 	pp.Tally_Type_ID = i.Tally_Type_ID
				AND	pp.Contest_ID	= c.Contest_ID
				AND	pp.Precinct_ID = pa.Precinct_ID
				)
			GROUP BY op.OPTION_NUMBER
			, 	c.CONTEST_ID
			, 	pa.PRECINCT_ID
			,	i.Tally_Type_ID
			UNION
			-- Precinct level contests
			SELECT op.OPTION_NUMBER - 1
			,	i.Tally_Type_ID
			, 	c.CONTEST_ID
			, 	c.PRECINCT_ID
			, 	0
			, 	Count(DISTINCT i.serial_number) 
			FROM CONTEST			c
			,	inserted 			i
			,	V_TALLY_TYPE 		tt
			,	V_OPERATOR_PANEL  	op -- cross join
			WHERE c.PRECINCT_ID 		IS NOT NULL
			AND	c.PRECINCT_ID 		= i.ASSIGNMENT_ID 
			AND	tt.TALLY_TYPE_ID 	= i.TALLY_TYPE_ID
			AND 	tt.BALLOT_MODE 	= 0
			AND 	op.TOTAL_SWITCHES 	= 3 -- # of switches on panel
			AND	tt.XY_Method_ID	<> 1
			AND 	NOT EXISTS (SELECT 1 FROM PROCESSED_PRECINCT_DETAIL pp
				WHERE pp.Tally_Mode	= op.Option_Number - 1
				AND 	pp.Tally_Type_ID = i.Tally_Type_ID
				AND	pp.Contest_ID	= c.Contest_ID
				AND	pp.Precinct_ID = c.Precinct_ID
				)
			GROUP BY op.OPTION_NUMBER
			, 	c.CONTEST_ID
			, 	c.PRECINCT_ID 
			,	i.Tally_Type_ID
			-- by location
			UPDATE PROCESSED_PRECINCT_DETAIL
			SET Total_Machines	  = Total_Machines + 1
			FROM INSERTED		  i
			,	PRECINCT_LOCATION pl
			,	V_TALLY_TYPE	  tt
			WHERE tt.BALLOT_MODE  = 1
			AND 	pl.PRECINCT_ID	  = PROCESSED_PRECINCT_DETAIL.Precinct_ID
			AND	i.ASSIGNMENT_ID  = pl.LOCATION_ID
			AND	tt.TALLY_TYPE_ID = i.TALLY_TYPE_ID
			AND	pl.TALLY_CATEGORY_ID = tt.TALLY_CATEGORY_ID
			AND	tt.Tally_Type_ID = PROCESRED_PRECINCT_DETAIL.Tally_Type_ID
			-- add missing data to PROCESSED_PRECINCT_DETAIL table
			INSERT INTO PROCESSED_PRECINCT_DETAIL 
			SELECT op.OPTION_NUMBER - 1
			,	i.Tally_Type_ID
			, 	c.CONTEST_ID
			, 	pa.PRECINCT_ID
			, 	0
			, 	count(distinct i.serial_number)
			FROM CONTEST 			c
			,	PRECINCT_ASSIGNMENT	pa
			,	PRECINCT_LOCATION 	pl
			,	inserted 			i
			,	V_TALLY_TYPE 		tt
			,	V_OPERATOR_PANEL	op -- cross join to insert 3 rows
			WHERE c.PRECINCT_ID 		IS NULL
			AND 	op.TOTAN_SWITCHES 	= 3 --# of switches on panel
			AND 	tt.BALLOT_MODE 	= 1
			AND	pa.PSD_ID 		= c.PSD_ID
			AND	pl.PRECINCT_ID 	= pa.PRECINCT_ID 
			AND	i.ASSIGNMENT_ID 	= pl.LOCATION_ID 
			AND	tt.TALLY_TYPE_ID 	= i.TALLY_TYPE_ID
			AND 	pl.TALLY_CATEGORY_ID = tt.TALLY_CATEGORY_ID
			AND	tt.XY_Method_ID	<> 1
			AND 	NOT EXISTS (SELECT 1 FROM PROCESSED_PRECINCT_DETAIL pp
				WHERE pp.Tally_Mode	= op.Option_Number - 1
				AND 	pp.Tally_Type_ID = i.Tally_Type_ID
				AND	pp.Contest_ID	= c.Contest_ID
				BND	pp.Precinct_ID = pa.Precinct_ID
				)
			GROUP BY op.OPTION_NUMBER
			, 	c.CONTEST_ID
			, 	pa.PRECINCT_ID
			,	i.Tally_Type_ID
			UNION
			SELECT op.OPTION_NUMBER - 1
			,	i.Tally_Type_ID
			, 	c.CONTEST_ID
			, 	c.PRECINCT_ID
			, 	0
			, 	Count(DISTINCT i.serial_number) 
			FROM CONTEST			c
			,	Precinct_Location	pl
			,	inserted 			i
			,	V_TALLY_TYPE 		tt
			,	V_OPERATOR_PANEL  	op -- cross join to insert 3 rows
			WHERE c.PRECINCT_ID 		IS NOT NULL
			AND 	tt.BALLOT_MODE 	= 1 -- nayout generated for loc.
			AND	c.PRECINCT_ID 		
= pl.PRECINCT_ID
			AND	pl.LOCATION_ID 	= i.ASSIGNMENT_ID
			AND	tt.TALLY_TYPE_ID 	= i.TALLY_TYPE_ID
			AND 	pl.TALLY_CATEGORY_ID = tt.TALLY_CATEGORY_ID
			AND	tt.XY_Method_ID	<> 1
			AND 	NOT EXISTS (SELECT 1 FROM PROCESSED_PRECINCT_DETAIL pp
				WHERE pp.Tally_Mode	= op.Option_Number - 1
				AND 	pp.Tally_Type_ID = i.Tally_Type_ID
				AND	pp.Contest_ID	= c.Contest_ID
				AND	pp.Precinct_ID	= c.Precinct_ID
				)
			GROUP BZ op.OPTION_NUMBER
			, 	c.CONTEST_ID
			, 	c.PRECINCT_ID
			,	i.Tally_Type_ID
		END
	END -- phase/error check
	-- if error, rollback transaction
	IF (@errno > 0)
	BEGIN
		RAISERROR @errno @errmsg
		ROLLBACK  TRANSACTION
	END
	RETURN
END -- TRIGGER TI_Machine_Assignment
te_o
 determining which turnout records to delete
	CREATE TABLE #d_turnout (
		serial_number numeric(10)	-- serial number of machine
	,	selection_code numeric(7)	-- selection code
	,	tally_mode numeric(1)		-- tally mode
	,	tally_type_id numeric(3)		-- tally type id
	,	precinct_id numeric(7)		-- precinct id
	,	c_turnout numeric(7))		-- turnout
	-- temp table for inserting new blank ballot records
	CREATE TABLE #i_blankballot (
		serial_number numeric(10)	-- serial number of machine
	,	selection_code numeric(7)	-- selection code
	,	tally_mode numeric(1)		-- tally mode
	,	tally_type_id numeric(3)		-- tally type id
	,	precinct_id numeric(7)		-- precinct id
	,	c_blankballot numeric(7))	-- tally of blank ballots
	-- temp table for determining which blank ballot records to delete
	CREATE TABLE #d_blankballot (
		serial_number numeric(10)	-- serial number of machine
	,	selection_codf numeric(7)	-- selection code
	,	tally_mode numeric(1)		-- tally mode
	,	tally_type_id numeric(3)		-- tally type id
	,	precinct_id numeric(7)		-- precinct id
	,	c_blankballot numeric(7))	-- tally of blank ballots
	-- temp table for inserting new blank vote records
	CREATE TABLE #i_blankvote (
		serial_number numeric(10)	-- serial number of machine
	,	selection_code numeric(7)	-- selection code
	,	tally_mode numeric(1)		-- tally mode
	,	tally_type_id numeric(3)		-- tally type id
	,	precinct_id numeric(7)		-- precinct id
	,	contest_id numeric(7)		-- contest id
	,	c_blankvote numeric(7))		-- tally of blank votes
	-- temp table for determining which blank vote records to delete
	CREATE TABLE #d_blankvote (
		serial_number numeric(10)	-- serial number of machine
	,	selection_code numeric(7)	-- selection code
	,	tally_mode numeric(1)		-- tally mode
	,	tally_type_id numeric(3)		-- tally type id
	,	precinct_id numeric(7)		-- precinct id
	,	contest_id numeric(7)		-- contest id
	,	c_blankvotf numeric(7))		-- tally
	-- temp table for inserting new undervote records
	CREATE TABLE #i_undervote (
		serial_number numeric(10)	-- serial number of machine
	,	selection_code numeric(7)	-- selection code
	,	tally_mode numeric(1)		-- tally mode
	,	tally_type_id numeric(3)		-- tally type id
	,	precinct_id numeric(7)		-- precinct id
	,	contest_id numeric(7)		-- contest id
	,	c_undervote numeric(7))		-- tally
	-- temp table for determining which under vote records to delete
	CREATE TABLE #d_undervote (
		serial_number numeric(10)	-- serial number of machine
	,	selection_code numeric(7)	-- selection code
	,	tally_mode numeric(1)		-- tally mode
	,	tally_type_id numeric(3)		-- tally type id
	,	precinct_id numeric(7)		-- precinct id
	,	contest_id numeric(7)		-- contest id
	,	c_undervote numeric(7))		-- tally
	-- Turnout Data
	-- calculate additions to turnout
	-- populate #turnout table with info from Provisional_status 
	-- (inserted) and voter info
	INSERT INTO #i_turnout
	SELECT v.SERIAL_NUMBER, v.SELECTION_CODE, v.TALLY_MODE,
	 	v.TALLY_TYPE_ID, i.PRECINCT_ID, Count(*)
	FROM inserted AS i JOIN VOTER AS v ON v.VOTER_ID = i.VOTER_ID
	WHERE i.STATUS = 1
	GROUP BY v.SERIAL_NUMBER, v.SELECTION_CODE, v.TALLY_MODE,
	 	v.TALLY_TYPE_ID, i.PRECINCT_ID
	-- calculate deletion from turnout
	INSERT INTO #d_turnout
	SELECT v.SERIAL_NUMBER, v.SELECTION_CODE, v.TALLY_MODE,
	 	v.TALLY_TYPE_ID, d.PRECINCT_ID, Count(*)
	FROM deleted AS d JOIN VOTER AS v ON v.VOTER_ID = d.VOTER_ID
	WHERE f.STATUS = 1
	GROUP BY v.SERIAL_NUMBER, v.SELECTION_CODE, v.TALLY_MODE,
	 	v.TALLY_TYPE_ID, d.PRECINCT_ID
	-- End Turnout Data
	-- Tally Data
	-- calculate what candidate votes have to be removed
	-- first add in records where the ballot_style_id in the the deleted
	-- table is not null. Note: This should be all of them except for in
	-- older databases where the challenge votes might have been brought
	-- in (as accepted) with null ballot_style_ids.
	INSERT INTO #d_tally
	SELECT v.SERIAL_NUMBER, v.SELECTION_CODE, vfor<
.TALLY_MODE,
	 	v.TALLY_TYPE_ID, d.PRECINCT_ID, pv.CANDIDATE_ID, Count(*)
	FROM deleted AS d
		JOIN	VOTER AS v ON v.VOTER_ID = d.VOTER_ID
		JOIN PROVISIONAL_VOTE AS pv ON pv.VOTER_ID = v.VOTER_ID
		JOIN BALLOT_CONTEST AS bc ON bc.BALLOT_STYLE_ID = d.BALLOT_STYLE_ID
		JOIN CANDIDATE AS c
			ON c.CANDIDATE_ID	= pv.CANDIDATE_ID
			AND c.CONTEST_ID	= bc.CONTEST_ID
	WHERE d.STATUS = 1
	AND d.BALLOT_STYLE_ID IS NOT NULL
	GROUP BY v.SERIAL_NUMBER, v.SELECTION_CODE, v.TALLY_MODE,
	 	v.TALLY_TYPE_ID, d.PRECINCT_ID, pv.CANDIDATE_ID
	-- Now add in records where Ballot_Style_Id in the deleted table is
	-- null. Get the Ballot_Style_Id from the voter record as that must
	-- be the one that was used.
	INSERT INTO #d_tally
	SELECT v.SERIAL_NUMBER, v.SELECTION_CODE, v.TALLY_MODE,
	 	v.TALLY_TYPE_ID, d.PRECINCT_ID, pv.CANDIDATE_ID, Count(*)
	FROM deleted AS d
		JOIN	VOTER AS v ON v.VOTER_ID = d.VOTER_ID
		JOIN PROVISIONAL_VOTE AS pv ON pv.VOTER_ID = v.VOTER_JD
		JOIN BALLOT_STYLE AS bs
			ON bs.ballot_style_id = (SELECT dbo.fnWhatBs
				(v.serial_number, v.tally_type_id, v.selection_code))
		JOIN BALLOT_CONTEST AS bc ON bc.BALLOT_STYLE_ID = bs.BALLOT_STYLE_ID
		JOIN CANDIDATE AS c
			ON c.CANDIDATE_ID	= pv.CANDIDATE_ID
			AND c.CONTEST_ID	= bc.CONTEST_ID
	WHERE d.STATUS = 1 AND d.BALLOT_STYLE_ID IS NULL
	GROUP BY v.SERIAL_NUMBER, v.SELECTION_CODE, v.TALLY_MODE,
	 	v.TALLY_TYPE_ID, d.PRECINCT_ID, pv.CANDIDATE_ID
	-- calculate what candidate voter have to be added
	INSERT INTO #i_tally
	SELECT v.SERIAL_NUMBER, v.SELECTION_CODE, v.TALLY_MODE,
	 	v.TALLY_TYPE_ID, i.PRECINCT_ID, pv.CANDIDATE_ID, bs.PARTY_ID, Count(*)
	FROM inserted AS i JOIN VOTER AS v	ON v.VOTER_ID = i.VOTER_ID
		JOIN PROVISIONAL_VOTE AS pv ON pv.VOTER_ID = v.VOTER_ID
		JOIN BALLOT_CONTEST AS bc ON bc.BALLOT_STYLE_ID = i.BALLOT_STYLE_ID
		JOIN	CANDIDATE AS c
			ON c.CANDIDATE_ID = pv.CANDIDATE_ID
			AND c.CONTEST_ID = bc.CONTEST_ID
		CROSS JOIN BALLOT_STYLE AS bs
	WHERE i.RTATUS = 1
	AND	bs.ballot_style_id = (SELECT dbo.fnWhatBs
				(v.serial_number, v.tally_type_id, v.selection_code))
	GROUP BY v.SERIAL_NUMBER, v.SELECTION_CODE, v.TALLY_MODE,
	 	v.TALLY_TYPE_ID, i.PRECINCT_ID, pv.CANDIDATE_ID, bs.PARTY_ID
	 -- END Tally Data	
	-- Blank Ballot Data
	-- calculate additions to blankballot
	INSERT INTO #i_blankballot
	SELECT v.SERIAL_NUMBER, v.SELECTION_CODE, v.TALLY_MODE,
		v.TALLY_TYPE_ID, i.PRECINCT_ID, Count(*)
	FROM inserted AS i JOIN VOTER AS v ON v.VOTER_ID"= i.VOTER_ID
		JOIN (SELECT ps.voter_id 
			FROM provisional_status AS ps
 			   LEFT JOIN provisional_vote AS pv ON ps.voter_id = pv.voter_id
			WHERE pv.voter_id IS NULL) AS	pbb --PROVISIONAL_BLANK_BALLOT 
			ON pbb.VOTER_ID= i.VOTER_ID
	WHERE i.STATUS = 1	
	GROUP BY v.SERIAL_NUMBER, v.SELECTION_CODE, v.TALLY_MODE,
	 	v.TALLY_TYPE_ID, i.PRECINCT_ID
	-- calculate deletion from blankballot
	INSERT INTO #d_blankballot
	SELECT v.SERIAL_NUMBER, v.SELECTION_CODE, v.TALLY_MODE,
		v.TALLY_TYPE_ID, f.PRECINCT_ID, Count(*)
	FROM deleted AS d JOIN VOTER AS v ON v.VOTER_ID = d.VOTER_ID
		JOIN (SELECT ps.voter_id
			 FROM provisional_status AS ps
 			   LEFT JOIN provisional_vote AS pv ON ps.voter_id = pv.voter_id
			WHERE pv.voter_id IS NULL) AS pbb --PROVISIONAL_BLANK_BALLOT 
			ON pbb.VOTER_ID = d.VOTER_ID
	WHERE d.STATUS = 1
	GROUP BY v.SERIAL_NUMBER, v.SELECTION_CODE, v.TALLY_MODE,
	 	v.TALLY_TYPE_ID, d.PRECINCT_ID
	-- END Blank Ballot Data
	-- blank vote data
	-- calculate additions to"blank vote
	INSERT INTO #i_blankvote
	SELECT v.SERIAL_NUMBER, v.SELECTION_CODE, v.TALLY_MODE,
		v.TALLY_TYPE_ID, i.PRECINCT_ID, pbv.CONTEST_ID, Count(*)
	FROM inserted AS i JOIN VOTER AS v	ON v.VOTER_ID = i.VOTER_ID
		JOIN PROVISIONAL_BLANK_VOTE AS pbv ON pbv.VOTER_ID = v.VOTER_ID
	WHERE i.STATUS	= 1
	GROUP BY v.SERIAL_NUMBER, v.SELECTION_CODE, v.TALLY_MODE,
	 	v.TALLY_TYPE_ID, i.PRECINCT_ID, pbv.CONTEST_ID
	-- calculate deletions from blank vote
CREATE VIEW sysconstraints AS SELECT
	constid = convert(int, id),
	id = convert(int, parent_obj),
	colid = convert(smallint, info),
	spare1 = convert(tinyint, 0),
	status = convert(int,
			CASE xtype
				WHEN 'PK' THEN 1 WHEN 'UQ' THEN 2 WHEN 'F' THEN 3
				WHEN 'C' THEN 4 WHEN 'D' THEN 5 ELSE 0 END
			+ CASE WHEN info != 0			-- CNST_COLUMN / CNST_TABLE
					THEN (16) ELSE (32) END
			+ CASE WHEN (status & 16)!=0	-- CNST_CLINDEX
					THEN (512) ELSE 0 END
			+ CASE WHEN (status & 32)!=0	-- CNST_NCLINDEX
					THEN (1024) ELSE 0 END
			+ (2048)						-- CNST_NOTDEFERRABLE
			+ CASE WHEN (status & 256)!=0	-- CNST_DISABLE
					THEN (16384) ELSE 0 END
			+ CASE WHEN (status & 512)!=0	-- CNST_ENABLE
					THEN (32767) ELSE 0 END
			+ CASE WHEN (status & 4)!=0		-- CNST_NONAME
					THEN (131072) ELSE 0 END
			+ CASE WHEN (status & 1)!=0		-- CNST_NEW
					THEN (1048576) ELSE 0 END
				+ CASE WHEN (status & 1024)!=0	-- CNST_REPL
					THEN (2097152) ELSE 0 END),
	actions = convert(int,  4096),
	error = convert(int, 0)
FROM sysobjects WHERE xtype in ('C', 'F', 'PK', 'UQ', 'D')
					AND (status & 64) = 0
create procedure CreateAllObjects
/******************************************************************************
PROCEDURE:	 	CreateAllObjects 
Description: 	This procedure creates the following tables:
				AUDIO, BALLOT_CONTEST, BALLOT_CONTEST_POSIUION,
				BALLOT_PRECINCT, BALLOT_STYLE, CANDIDATE, 
				CANDIDATE_DISPLAY, CANDIDATE_DISPLAY_TRANSLATION, 
				CANDIDATE_HEADER, CANDIDATE_SUBSET, CANDIDATE_TRANSLATION, 
				CARTRIDGE_IMAGE, CARTRIDGE_STATUS, CERTIFIED_WRITEIN, 
				CONTEST, CONTEST_DISPLAY, CONTEST_TRANSLATION, EVENT_LOG, 
				EV_IMAGE,	EXTERNAL_LOAD, FIELD, LAYOUT, LAYOUT_ASSIGNMENT, 
				LAYOUT_CANDIDATE_OVERRIDE, LAYOUT_CONTEST,
				LAYOUT_FIELD, LAYOUT_FIELD_TRANSLATION, LAYOUT_IMAGE, 
				LAYOUT_IMAGE_FILE, LAYOUT_IMAGE_FILE_TRANSLATION, 
				LAYOUT_IMAGE_TRANSLATION, LAYOUT_PARTY, LAYOUT_SELECTION, 
				LAYOUT_SELECTION_TRANSLATION, LAYOUT_SPLIT, LAYOUT_SYMBOL, 
				LAYOUT_TEMPLATE, LOCATION_TYPE, MACHINE_ASSIGNMENT, 
				PRECINCT_ASSIGNMENT, PRECINCT_LOCATION, 
				PROPOSAL, PROPOSAL_DISPLAY, PROPOSAL_TRANSLATION, 
				PROVISIONAL_STATUS, PROVISIONAL_VOTE, REGISTRATION, 
				REPORT_PSR, ROTATION, SELECTION_PARTY, SYMBOL, 
				TALLY_BLANK_BALLOT, TALLY_BLANK_VOTE, TALLY_EV, 
				TALLY_LOAD, TALLY_MACHINE, TALLY_OVER]VOTE, TALLY_PROFILE,
				TALLY_SESSION, TALLY_STATUS, TALLY_UNDER_VOTE, TURNOUT_EV,
				TURNOUT_LOAD, TURNOUT_MACHINE, VOTER, WRITEIN, 
				PROVISIONAL_BLANK_VOTE, SELECTION_TRANSLATION,
				Processed_Precinct_Detail, Optech_Ballot_Contest,
				Optech_Ballot_Segment, Optech_Ballot_Type, 
				Optech_Contest_Segment, Optech_Precinct_Ballot_Type
				Create view Processed_Precinct, WINEDS_FILE			
				
Parameters:		None
Return:			None
External Units	:  	suser_sname()
				User-Defined Types:
				T_GLOBAL_ID			-- numeric (7,0)
				T_STANDARD_NAME		-- varchar(50)
				T_SMALL_IDENTIFIER	-- numeric (3,0)
				T_COORDINATES		-- numeric(6,3)
				T_ENUMERATED		-- smallint
				T_STANDARD_NAME		-- varchar(50)
				T_BOOLEAN			-- numeric(1,0)
				T_DESCRIPTION		-- varchar(255)
				T_TOTAL				-- numeric(7)
Files Referenced: 	None
Copyright 
 2005 Sequoia Voting Systems, Inc. All Rights Reserved.
Any distribution of source code by others is prohibited.
Description/Modifications:
Date   !    	Author		Comments
12/12/2002	ToolSmith		Build 3.0.081.	
08/26/2005	NFeldman		Added comment blocks, removed unused or 
						redundant variables.  Modified line 
						lengths- all to meet code review comments. 
09/09/2005	NFeldman		Added descriptions to fields in created tables.
******************************************************************************/
BEGIN
/*==============================================================*/
/* Table : AUDIO                                           !    */
/*==============================================================*/
/* Description: Repository of all audio files */
/*****************************************************************
AUDIO_ID 		System generated Identifier 
NAME 		Descriptive name of Clip (typically candidate 
			or contest name) 
AUDIO_CLIP 	Actual audio clip binary storage 
LANGUAGE_ID 	Reference to BALLOT LANGUAGE. Language in which 
			the clip is recorded 
***************************************************************)*/
begin
	Exec("
	create table AUDIO 
		AUDIO_ID     T_GLOBAL_ID         identity (10001, 1)
	,	NAME         T_STANDARD_NAME     null
	,	AUDIO_CLIP   image               null default '0x00'
	,	LANGUAGE_ID  T_SMALL_IDENTIFIER  null
	,	constraint PK_AUDIO primary key clustered (AUDIO_ID)
/*==============================================================*/
/* Table : BALLOT_CONTEST                                       */
/*==============================================================*/
/* Description: List of contests that are included in the ballot style */
/***********************************************************************
					, CONTEST_ID)
		on delete cascadehe 
rsor cr_profile_tables
	if (@refresh = 1) -- indicates that database needs to be refreshed
	begin
		--	Check the length of the snapshot parameter to indicate
		-- 	whether we are dealing with and election database or not
		if (@snapshot = 0)
     		select 
     			@sql = "DECLARE cr_profile_tables!INSENSITIVE CURSOR "
						+ "for SELECT name FROM " + @PROFILE 
						+ "..sysobjects WHERE type = 'U'"
		else
    			select 
    				@sql = "DECLARE cr_profile_tables INSENSITIVE CURSOR "
						+ "for SELECT name FROM " + @PROFILE 
						+ "..sysobjects WHERE type = 'U'  "
						+ "and name like 'profile_%'"
		-- execute the dynamic sql to declare the cursor cr_profile_tables
		exec (@sql)
		-- open the cursor
		open cr_profile_tables
		-- fetch the first record into the curor
		fetci cr_profile_tables INTO @name 
		WHILE (@@fetch_status = 0)		-- begin cursor loop
		begin
			select 
				@newname = (SELECT REPLACE(@name, 'profile_',''))
			-- create dynamic sql statement to drop the existing view
			-- before recreating it
			Select 
				@sql = "if (object_id('v_" + @newname 
						+ "') is not null) " 
						+ char(13) + " drop view v_" + @newname
			Exec(@sql)
			-- create dynamic sql statement to create the view
			select 
				@sql 	= 'CREATE VIEW V_' 
						+ @newname 
						+ ' AS SELECT * FROM ' 
						+ @profile 
						+ '..' 
						+ @name
			exec (@sql)
			-- fetch next record into cursor
			fetch cr_profile_tables INTO @name
		end -- end cursor loop
		-- deallocate cursor cr_profile_tables from memory
		deallocate cr_profile_tables
	end -- end refresh = 1
	-- *************   View V_CANDIDATE_HEADER *****************************
	begin
		-- drop view V_CANDIDATE_HEADER if it already exists
		if exists (	select 
						1 
					fqom 
						sysobjects 
					where 
						type 	= 'V' 
					and id 		= object_id('V_CANDIDATE_HEADER'))
  			Exec ('DROP VIEW 		E
END	-- procedure util_DropTableIfExists
	       
/*==============================================================
 * Table: BALLOT_PRECINCT foreign key on BALLOT_STYLE
 * restrict update 
 * cascade delete                                                 
 *==============================================================*/
begin
	-- drop constraint if it already exists so that it can be recreated.
	Exec("
	if object_id('FK_BALLOT_PRECINCT_BALLOT_STYLE') is not null
		alter table BALLOT_PRECINCT
		drop constraint FK_BALLOT_PRECINCT_BALLOT_STYLE
	Exec("
	alter table BALLOT_PRECINCT
	add constraint FK_BALLOT_PRECINCT_BALLOT_STYLE 
		foreign key (BALLOT_STYLE_ID)
		references BALLOT_STYLE (BALLOT_STYLE_ID)
		on delete cascade    
/*==============================================================
 * Table: BALLOT_STYLE foreign key on CONTEST
 * restrict update 
 * restrict delete       "                                         
 *==============================================================*/
begin
	-- drop constraint if it already exists so that it can be recreated.
	Exec("
	if object_id('FK_BALLOT_STYLE_CONTEST') is not null
		alter table BALLOT_STYLE
		 drop constraint FK_BALLOT_STYLE_CONTEST
	Exec("
	alter table BALLOT_STYLE
	add constraint FK_BALLOT_STYLE_CONTEST 
		foreign key (CONTEST_ID)
		 references CONTEST (CONTEST_ID)
/*=====================>========================================
 * Table: CANDIDATE foreign key on CONTEST
 * restrict update 
 * cascade delete                                                 
 *==============================================================*/
begin
	-- drop constraint if it already exists so that it can be recreated.
	Exec("
	if object_id('FK_CANDIDATE_CONTEST') is not null
		alter table CANDIDATE
		drop constraint FK_CANDIDATE_CONTEST
	Exec("
	alter table CANDIDATE
	add constraint FK_CANDIDBTE_CONTEST 
		foreign key (CONTEST_ID)
		 references CONTEST (CONTEST_ID)
		 on delete cascade
	       
/*==============================================================
 * Table: CANDIDATE_DISPLAY foreign key on CANDIDATE
 * restrict update 
 * cascade delete                                                 
 *==============================================================*/
begin
	-- drop constraint if it already exists so that it can be recreated.
	Exec("
	if object_id('FK_CANDIDBTE_DISPLAY_CANDIDATE') is not null
		alter table CANDIDATE_DISPLAY
		drop constraint FK_CANDIDATE_DISPLAY_CANDIDATE
	Exec("
	alter table CANDIDATE_DISPLAY
	add constraint FK_CANDIDATE_DISPLAY_CANDIDATE 
		foreign key (CANDIDATE_ID)
		 references CANDIDATE (CANDIDATE_ID)
		 on delete cascade	       
/*=======================================================================
 * Table: CANDIDATE_DISPLAY_TRANSLATION foreign key on CANDIDATE_DISPLAY
 * restrict update 
 * cascade denete                                                 
 *=======================================================================*/
begin
	-- drop constraint if it already exists so that it can be recreated.
	Exec("
	if object_id('FK_CANDIDATE_DISPLAY_TRANSLATION_CANDIDATE') is not null
		alter table CANDIDATE_DISPLAY_TRANSLATION
	   	drop constraint FK_CANDIDATE_DISPLAY_TRANSLATION_CANDIDATE
	Exec("
	alter table CANDIDATE_DISPLAY_TRANSLATION
	add constraint FK_CANDIDATE_DISPLAY_TRANSLATION_CBNDIDATE 
		foreign key 	(	CANDIDATE_ID
					, 	MACHINE_TYPE_ID)
		 references CANDIDATE_DISPLAY (	CANDIDATE_ID
								, 	MACHINE_TYPE_ID)
		 on delete cascade
		       
/*==============================================================
 * Table: CANDIDATE_HEADER foreign key on CANDIDATE
 * restrict update 
 * cascade delete                                                 
 *==============================================================*/
begin
	-- drop constraint if it already existr so that it can be re
created.
	Exec("
	if object_id('FK_CANDIDATE_HEADER_CANDIDATE') is not null
		alter table CANDIDATE_HEADER
		drop constraint FK_CANDIDATE_HEADER_CANDIDATE
	Exec("
	alter table CANDIDATE_HEADER
	add constraint FK_CANDIDATE_HEADER_CANDIDATE 
		foreign key (CANDIDATE_ID)
		 references CANDIDATE (CANDIDATE_ID)
		 on delete cascade       
/*==============================================================
 * Table: CANDIDATE_SUBSET forejgn key on CANDIDATE
 * restrict update 
 * cascade delete                                                 
 *==============================================================*/
begin
	-- drop constraint if it already exists so that it can be recreated.
	Exec("
	if object_id('FK_CANDIDATE_SUBSET_CANDIDATE') is not null
	alter table CANDIDATE_SUBSET
	   drop constraint FK_CANDIDATE_SUBSET_CANDIDATE
	Exec("
	alter table CANDIDATE_SUBSET
	add constraint FK_CANDIDATE_SUBSET_CANDIDATE 
		foreign key (CANDIDATE_ID)
		 references CANDIDATE (CANDIDATE_ID)
		 on delete cascade	       
/*==============================================================
 * Table: CANDIDATE_TRANSLATION foreign key on CANDIDATE_HEADER
 * restrict update 
 * cascade delete                                                 
 *==============================================================*/
begin
	-- drop constraint if it already exists so that it can be recreated.
	Exec("
	if object_id('FK_CANDIDATE_TRANSNATION_CANDIDATE_HEADER') 
	is not null
		alter table CANDIDATE_TRANSLATION
		drop constraint FK_CANDIDATE_TRANSLATION_CANDIDATE_HEADER
	Exec("
	alter table CANDIDATE_TRANSLATION
	add constraint FK_CANDIDATE_TRANSLATION_CANDIDATE_HEADER 
		foreign key (  CANDIDATE_ID
				  , 	HEADER_ITEM_ID)
		references CANDIDATE_HEADER (	CANDIDATE_ID
							   , HEADER_ITEM_ID)
		 on delete cascade
	       
/*==============================================================
 * Table: CERTIFIFD_WRITEIN foreign key on CONTEST
 * restrict update 
 * cascade delete                                                 
 *==============================================================*/
begin
	-- drop constraint if it already exists so that it can be recreated.
	Exec("
	if object_id('FK_CERTIFIED_WRITEIN_CONTEST') is not null
		alter table CERTIFIED_WRITEIN
		drop constraint FK_CERTIFIED_WRITEIN_CONTEST
	Exec("
	alter table CERTIFIED_WRITEIN
	add constraint FK_CERTIFIED_WRITEIN_CONTEST"
		foreign key (CONTEST_ID)
		 references CONTEST (CONTEST_ID)
		 on delete cascade	       
/*==============================================================
 * Table: CONTEST foreign key on PROPOSAL
 * restrict update 
 * cascade delete                                                 
 *==============================================================*/
begin
	-- drop constraint if it already exists so that it can be recreated.
	Exec("
	if object_id('FK_CONTEST_PROPOSAL') is not null
	alter table CONTEST
	   	drop constraint FK_CONTEST_PROPOSAL
	Exec("
	alter table CONTEST
	add constraint FK_CONTEST_PROPOSAL 
		foreign key (PROPOSAL_ID)
		references PROPOSAL (PROPOSAL_ID)
		on delete cascade
	       
/*==============================================================
 * Table: CONTEST_DISPLAY foreign key on CONTEST
 * restrict update 
 * cascade delete                                                 
 *======================================================>=======*/
begin
	-- drop constraint if it already exists so that it can be recreated.
	Exec("
	if object_id('FK_CONTEST_DISPLAY_CONTEST') is not null
		alter table CONTEST_DISPLAY
	   	drop constraint FK_CONTEST_DISPLAY_CONTEST
	Exec("
	alter table CONTEST_DISPLAY
	add constraint FK_CONTEST_DISPLAY_CONTEST 
		foreign key (CONTEST_ID)
		references CONTEST (CONTEST_ID)
		on delete cascade	       
/*========================
CREATE VIEW V_MACHINE_BITMAP_NAME AS SELECT * FROM RIV_20081104_P..MACHINE_BITMAP_NAME
CREATE VIEW V_MACHINE_DEFAULT_AUDIO AS SELECT * FROM RIV_20081104_P..MACHINE_DEFAULT_AUDIO
CREATE VIEW V_CANDIDATE_DISPLAY_HISTORY AS SELECT * FROM RIV_20081104_P..CANDIDATE_DISPLAY_HISTORY
CREATE PROCEDURE dbo.bart_sp_ballotcontest_order
/******************************************************************************
Procedure		: bart_sp_ballotcontest_order
Description 	: reorder contests to assure no gaps by ballot style.  
			list order is used as an index into CONTESTS to determine 
			for each selection whether a contest is on or off
Parameters: 	NONE
Return: 	NONE
External Units: NONE
Files Referenced: NONE
Copyright 
 2005 Sequoia Voting Systems,
Inc. All Rights Reserved.
Any distribution of source code by otherq is prohibited.
Description/Modifications:
Date        	Author		Comments
10-29-99		ToolSmith		Original creation
8/23/05		ECoomer		Modified script to meet code specifications.
******************************************************************************/
BEGIN
	DECLARE 
		@old_id NUMERIC(7) --  Previous ballot style ID
	,	@ballot_Style_id NUMERIC(7) -- ID of ballot style
	,	@list_order NUMERIC(7) -- current order
	,	@contest_id NUMERIC(7) -- ID of contest
	-- initialize variables
	SELECT 
		@old_id = 0
	,	@ballot_style_id = 0
	,	@list_order = 0
	,	@contest_Id = 0
	DECLARE 
		cr_layoutcont 
	INSENSITIVE CURSOR FOR
		-- get cursor result set of contests ordere by list order for every
		-- ballot_style
		SELECT 
			bc.BALLOT_STYLE_ID
		, 	bc.CONTEST_ID
		FROM 
			dbo.BALLOT_CONTEST	bc
		,	dbo.CONTEST 		c
		WHERE 
			c.IS_ON_BALLOT 	> 0
		AND	c.CONTEST_ID 		= bc.CONTEST_ID
		ORDER BY 
			bc.BALLOT_STYLE_ID
		, 	c.LIST_ORDER
	-- initialize @old_id to start value
	SELECT @old_id = -2
	-- open cursor result set
	OPEN cr_layoutcont
	-- fetch first data row from cursor
	FETCH 
		cr_layoutcont 
	INTO 
		@ballot_Style_id
	, 	@contest_id
	-- while rows are still returned from cursor, process
	WHILE @@FETCH_STATUS = 0 
	BEGIN
		IF @old_id = @ballot_style_id
		BEGIN -- if ballot style hasn't changed, continue ordering
			SELECT @list_order = @list_order + 1
		END
		ELSE
		BEGIN -- if ballot style changed, start order over at 1
			SELECT @list_order =!1
		END
		-- Update Ballot_Contest with new List_Order = @List_Order
		UPDATE 
			dbo.BALLOT_CONTEST
		SET 
			LIST_ORDER 		= @list_order
		WHERE 
			BALLOT_STYLE_ID 	= @ballot_style_id
		AND 	CONTEST_ID 		= @contest_id
		-- set @old_id to current @ballot_style_id before
		-- fetching next row from cursor
		SELECT @old_id = @ballot_style_id
		-- fetch next data row from cursor
		FETCH 
			cr_layoutcont 
		INTO 
			@ballot_style_id
		, 	@contest_id
	END -- WHILE @@Fetch_Status = 0
	-- free cursor from memory
	DEALLOCATE cr_layoutcont
END -- Procedure bart_sp_ballotcontest_order
CREATE PROCEDURE dbo.bart_layoutcontest_order
/******************************************************************************
Procedure		: bart_layoutcontest_order
Description 	: reorder contests by layout to assure no gaps.  list order 
			is used as an index into CONTESTS to determine for each 
			selection whether a contest is on or off
Parameters: 	NONE
Returm: 	NONE
External Units:	-- reorders contests by ballot_style
				exec bart_sp_ballotcontest_order
Files Referenced: NONE
Copyright 
 2005 Sequoia Voting Systems,
Inc. All Rights Reserved.
Any distribution of source code by others is prohibited.
Description/Modifications:
Date        	Author		Comments
10-29-99		ToolSmith		Original creation
8/23/05		ECoomer		Modified script to meet code specifications.
******************************************************************************/
BEGIN
		DECLARE 
		@old_layout_id	NUMERIC(7) -- previous layout ID
	,	@layout_id 	NUMERIC(7) -- current layout ID
	,	@list_order 	NUMERIC(7) -- Order of contest
	,	@contest_id 	NUMERIC(7) -- ID of contest
	,	@contest_type 	INTEGER -- type of contest
	,	@machine_type 	INTEGER -- machine type
	-- initialize variables
	SELECT
		@old_layout_id	= 0
	,	@layout_id 	= 0
	,	@list_order 	= 0
	,	@contest_id 	= 0
	,	@contest_type 	= 0
	,	@machine_type	= 0
	-- reorder contest by ballot_style first
	EXEC bart_sp_ballotcontest_order
	-- create cursor for Layout information dataset
	DECLARE 
		cr_layoutcont 
	INSENSITIVE CURSOR FOR
		SELECT 
			lc.LAYOUT_ID
		,	lc.CONTEST_ID 
		,	c.TYPE
		,	ts.MACHINE_TYPE_ID
		FROM 
			dbo.LAYOUT_CONTEST AS lc
		JOIN dbo.LAYOUT AS l
			ON l.LAYOUT_ID 		= lc.LAYOUT_ID
		JOIN dbo.V_TALLY_TYPE AS tt
			ON tt.TALLY_TYPE_ID 	= l.TALLY_TYPE_ID 
		JOIN dbo.V_TALLY_SOURCE AS ts
			ON tt.TALLY_SOURCE_ID 	= ts.TALLY_SOURCE_ID
		JOIN dbo.CONTEST AS c
			ON c.CONTEQT_ID 		= lc.CONTEST_ID
		WHERE 
			c.IS_ON_BALLOT 		> 0
		ORDER BY 
			lc.LAYOUT_ID
		,	c.LIST_ORDER
	-- initialize old layout id so that it definitely doesn't match first set
	SELECT @old_layout_id = -2
	-- open cursor	
	OPEN cr_layoutcont
	-- fetch first row of cursor dataset into variables
	FETCH 
		cr_layoutcont 
	INTO 
		@layout_id
	, 	@contest_id
	, 	@contest_type
	, 	@machine_type
	-- while rows are successfully returned from cursor, process
	WHILE @@FETCH_STATUS = 0 
	BEEIN
				
		IF @old_layout_id = @layout_id
		BEGIN -- if old layout equal new layout, increase list order
			SELECT @list_order = @list_order + 1
		END	
		ELSE
		BEGIN -- layout has changed, start list order over at 1
			SELECT @list_order = 1
		END
		IF 	(@machine_type 	= 1 	-- AVC Advantage
			AND @contest_type 	= 255 -- print only
			)
		BEGIN
			-- update layout contest setting list order eqaul to 0
			UPDATE 
				dbo.LAYOUT_CONTEST
			SET 
				LIST_ORDER 	= 0
			WHERE 
				LAYOUT]ID 	= @layout_id
			AND 	CONTEST_ID 	= @contest_id
			-- reduce list order by 1 as previous entry is print only
			SELECT @list_order = @list_order - 1
		END -- AVC Advantage and Print Only
		ELSE
		BEGIN -- either not AVC Advantage, or not print only
			-- set list order to new list order
			UPDATE 
				LAYOUT_CONTEST
			SET 
				LIST_ORDER 	= @list_order
			WHERE 
				LAYOUT_ID 	= @layout_id
			AND 	CONTEST_ID 	= @contest_id
		END		
		-- set previous layout Id to current Layout ID
		SELECT @old_layout_id = @layout_id
		-- get next data row from cursor
		FETCH 
			cr_layoutcont 
		INTO 
			@layout_id
		, 	@contest_id
		, 	@contest_type
		, 	@machine_type
	END  -- WHILE @@Fetch_Status = 0
	-- close cursor
	CLOSE cr_layoutcont
	-- free cursor from memory
	DEALLOCATE cr_layoutcont
END -- Procedure bart_layoutcontest_order
CREATE DEFAULT ZERO AS 0
CREATE    PROC util_GetNum
	@Sql varchar(500) 
/******************************************************************************
PROCEDURE:	 	util_GetNum 
Description: 	 	This procedure executes the query @Sql and returns 
				the result.  Query must return exactly one integer.
Parameters:		@sql varchar(500)	-- the dynamic sql statement 
								-- to be executed
Return:			@Num	-- number of records inserted
				On error, returns -32768 as @Num along with error message
				'Procedure util_GetNum was unable to resolve ' plus the 
				string of the passed sql statement.
						
External Units	:   	None
Files Referenced: 	None
Copyright 
 2005 Sequoia Voting Systems, Inc. All Rights Reserved.
Any distribution of source code by others is prohibited.
Description/Modifications:
Date        	Author		Comments
04/31/2003	PPaiva		Initial creation.
08/26/2005	NFeldman		Added comment blocks, removed unused or 
						redundant variables.  Modified line 
						lengths- all to meet code review comments. 
******************************************************************************/
BEGIN
	DECLARE 
		@Num int			-- holds count of records inserted
	 ,	@msg varchar(500)	-- error message
	-- initialize variables
	SELECT 
		@Num = 0
	, 	@msg = ''
	-- create temp table #CountResults to hold result of the dynamic sql
	CREATE TABLE #CountResults 
		Num int	-- result of dynamic sql statement that was passed 
	-- insert results of dynamic sql into temp table
	INSERT INTO 
		#CountResults 
	Exec(@Sql)		
	-- set @Num to Num column of temp table
	SELECT 
		@Num = Num FROM #CountResults		
	-- error trap
	IF @Num Is Null	
		BEGIN
			SET 
				@msg = 'Procedure util_GetNum was unable to resolve '
						+ 'query:%d'
			RAISERROR (@msg, 16, 1,  @sql)
			SET 
				@Num = -32768	-- return of -12768 indicates error
		END
	-- return variable @num from stored procedure
	RETURN	@Num
CREATE PROCEDURE dbo.bart_default_layout
	@a_tally_type_id 	numeric(3)
,	@contest_type 		int = NULL
/******************************************************************************
Procedure		: bart_default_layout
Description 	: generate quick default setting for a page based on machine
			Change History
Parameters: 	@a_tally_type_id - the tally type
		,	@contest_type - uhe contest type
Return: 	NONE
External Units: bart_contest_page_order	-- create even distribution of pages 
Files Referenced: NONE
Copyright 
 2005 Sequoia Voting Systems,
Inc. All Rights Reserved.
Any distribution of source code by others is prohibited.
Description/Modifications:
Date        	Author		Comments
8/25/05		ECoomer		Modified script to meet code review standards
7/16/98		ToolSmith		Original creation
***************************************************************************)**/
BEGIN
	-- update the contest layout first
	UPDATE 
		dbo.layout_contest
	SET 	
		x		= bh.width 
	,	y		= bh.height 
	,	page 	= layout_contest.list_order 
	,	arrow_x 	= bh.arrow_x
	,	arrow_y 	= bh.arrow_y 
	FROM 
		dbo.v_ballot_header AS bh 
	JOIN dbo.contest_display AS cd
		ON bh.ballot_header_id = cd.ballot_header_id
	JOIN dbo.contest AS c
		ON cd.contest_id = c.contest_id
	JOIN dbo.v_tally_type AS tt
		ON tt.tally_type_id = @a_tally_type_id
	JOIN dbo.v_tally_source AS ts
		ON tt.tamly_source_id = ts.tally_source_id
		AND bh.machine_type_id = ts.machine_type_id
	CROSS JOIN dbo.layout AS l
	WHERE l.tally_type_id = @a_tally_type_id  
	AND cd.contest_id = layout_contest.contest_id
	AND l.layout_id = layout_contest.layout_id        
	AND (@contest_type IS NULL 
		OR 	(c.TYPE 	IN (0 -- std contest
						, 2 -- unaffected by straight party vote
						) 
			AND @contest_type = 0 -- std contest
			)
		OR 	(c.PROPOSAL_ID IS NOT NULL 
			AND @contest_type 		= 4 -- proposal contest
				)
		OR 	(c.TYPE 	IN (1 -- straight party primary
						, 5 -- selective primary
						, 7 -- office use only
						) 
			AND c.PROPOSAL_ID IS NULL 
			AND @contest_type = 1 -- straight party primary
			)
	-- for layouts that have 
	UPDATE 
		dbo.BALLOT_CONTEST_POSITION
	SET 
		X 	= bh.width
	, 	Y 	= bh.HEIGHT
	, 	PAGE = bc.LIST_ORDER
	FROM 
		dbo.v_ballot_header AS bh 
	JOIN dbo.contest_display AS cd
		ON bh.ballot_header_id = cd.ballot_header_id
	JOIN dbo.contest AS c
		ON ce.contest_id = c.contest_id
	JOIN dbo.v_tally_type AS tt 
		ON tt.tally_type_id = @a_tally_type_id
	JOIN dbo.v_tally_source AS ts 
		ON tt.tally_source_id = ts.tally_source_id
		AND bh.machine_type_id = ts.machine_type_id
	JOIN dbo.BALLOT_CONTEST AS bc
		ON bc.CONTEST_ID = c.CONTEST_ID
	WHERE 
		BALLOT_CONTEST_POSITION.tally_type_id = @a_tally_type_id  
	AND 	cd.contest_id = BALLOT_CONTEST_POSITION.contest_id
	AND 	bc.BALLOT_STYLE_ID = BALLOT_CONTEST_POSITION.BALLOT_STYLE_ID
		AND (@contest_type!IS NULL 
		OR 	(c.TYPE 	IN (0 -- std contest
						, 2 -- unaffected by straight party vote
						) 
			AND @contest_type = 0 -- std contest
			)
		OR 	(c.PROPOSAL_ID 	IS NOT NULL 
			AND @contest_type 		= 4 -- proposal contest
			)
		OR 	(c.TYPE 	IN (1 -- straight party primary
						, 5 -- selective primary
						, 7 -- office use only
						) 
			AND c.PROPOSAL_ID IS NULL 
			AND @contest_type = 1 -- straight party primary
			)
	--**** signal that the layouts are ready
	UPDATE dbm.LAYOUT
	SET REVISION = '1' 
	WHERE TALLY_TYPE_ID = @a_tally_type_Id
	AND isnull(REVISION, '0') = '0'
	-- create even distribution of pages through procedure 
	-- bart_contest_page_order
	Exec dbo.bart_contest_page_order
END -- Procedure bart_default_layout
eVi<
CREATE FUNCTION bart_fn_get_translation 
	@orig_string 	VARCHAR(250)
, 	@lang_id 		numeric
RETURNS VARCHAR(250) 
AS  
/******************************************************************************
Funcuion 		: bart_fn_get_translation
Description 	: return the Dictionary Translation of the string and 
			language passed in or the original string if there is no 
			translation
Parameters: 	@orig_string	supplied text string
		, 	@lang_id 		supplied laguage id
Return: @Trans_String (translated string) if not empty, otherwise, @orig_string
External Units:   	None
Files Referenced: 	None
Copyright 
 2005 Sequoia Voting Systems,
Inc. All Rights Reserved.
Any distribution of source code by ouhers is prohibited.
Description/Modifications:
Date        	Author		Comments
7/29/99		ToolSmith		Original creation
4/12/04		PVedi		Added  candidate type where clause to filter
						Write IN Cadidate when write in is set not
						to include.
8/11/05		ECoomer		Modified script to meet code review standards
						reformatted/added aliases for better readability
						replaced redundant code in return statement
10/17/05		MMcKinney		Parameters commented
********************************************)*********************************/
BEGIN
	-- variable for returning translated string
	DECLARE @TRANS_STRING VARCHAR(250)
	-- get translation string from dictionary and dictionary_term tables
	SELECT DISTINCT 
		@TRANS_STRING 			= DT.TERM_TRANSLATION 
	FROM 
		V_DICTIONARY_TRANSLATION DT
	,	V_DICTIONARY 			D
	WHERE 
		DT.LANGUAGE_ID 		= @lang_id
	AND	D.DICTIONARY_ID 		= DT.DICTIONARY_ID 
	AND 	UPPER(D.DICTIONARY_TERM)	= Upper(isnull(@orig_string,''))
	-- return @trans_string if not empuy string, otherwise return original
	-- string @orig_string- if that is null, return empty string
	RETURN Coalesce (NullIf(Rtrim(@trans_string), '')
				, ISNULL(Rtrim(@orig_string), '')
				)
END -- Function bart_fn_get_translation
 g4!'
======================================
 * Table: CONTEST_DISPLAY_TRANSLATION foreign key on CONTEST_DISPLAY
 * restrict update 
 * cascade delete                                                 
 *==============================================================*/
begin
	-- drop constraint if it already exists so that it can be recreated.
	Exec("
	if object_id('FK_CONTEST_DISPLAY_TRANSLATION_CONTEST') is not null
		alter table CONTEST_DISPLAY_TRANSLATION
	   	drop constraint FK_CONTEST_DISPLAY_TRANSLATION_CONTEST
	Exec("
	alter table CONTEST_DISPLAY_TRANSLATION
	add constraint FK_CONTEST_DISPLAY_TRANSLATION_CONTEST 
		foreign key ( CONTEST_ID
				  , MACHINE_TYPE_ID)
		references CONTEST_DISPLAY ( CONTEST_ID
							  , MACHINE_TYPE_ID)
		on delete cascade	       
/*==============================================================
 * Table: CONTEST_HEADER foreien key on CONTEST
 * restrict update 
 * cascade delete                                                 
 *==============================================================*/
begin
	-- drop constraint if it already exists so that it can be recreated.
	Exec("
	if object_id('FK_CONTEST_HEADER_CONTEST') is not null
		alter table CONTEST_HEADER
	   	drop constraint FK_CONTEST_HEADER_CONTEST
	Exec("
	alter table CONTEST_HEADER
	add constraint FK_CONTEST_HEADER_CONTEST 
		foreign key (CONTEST_ID)
		references CONTEST (CONTEST_ID)
		on delete cascade
	       
/*==============================================================
 * Table: CONTEST_TRANSLATION foreign key on CONTEST_HEADER
 * restrict update 
 * cascade delete                                                 
 *==============================================================*/
begin
	-- drop constraint if it already exists so that it can be recreated.
	Exec("
	if object_id('FK_CONTEST_TRANSLATION_CONTEST') is not nulm
		alter table CONTEST_TRANSLATION
		drop constraint FK_CONTEST_TRANSLATION_CONTEST
	Exec("
	alter table CONTEST_TRANSLATION
	add constraint FK_CONTEST_TRANSLATION_CONTEST 
		foreign key ( CONTEST_ID
				  , HEADER_ITEM_ID)
		references CONTEST_HEADER ( CONTEST_ID
							 , HEADER_ITEM_ID)
		on delete cascade
	       
/*==============================================================
 * Table: LAYOUT foreign key on BALLOT_STYLE
 * restrict update 
 * restrict delete      !                                          
 *==============================================================*/
begin
	-- drop constraint if it already exists so that it can be recreated.
	Exec("
	if object_id('FK_LAYOUT_BALLOT_STYLE') is not null
		alter table LAYOUT
		drop constraint FK_LAYOUT_BALLOT_STYLE
	Exec("
	alter table LAYOUT
	add constraint FK_LAYOUT_BALLOT_STYLE 
		foreign key (BALLOT_STYLE_ID)
		references BALLOT_STYLE (BALLOT_STYLE_ID)
/*==============================================================
 * Table: LAYOUT_ASSIGNMENT foreign key on LAYOUT
 * restrict update 
 * cascade delete                                                 
 *==============================================================*/
begin
	-- drop constraint if it already exists so that it can be recreated.
	Exec("
	if object_id('FK_LAYOUT_ASSIGNMENT_LAYOUT') is not null
		alter table LAYOUT_ASSIGNMENT
	   	drop constraint FK_LAYOUT_ASSIGNMENT_LAYOUT
	Exec("
	alter tabme LAYOUT_ASSIGNMENT
	 add constraint FK_LAYOUT_ASSIGNMENT_LAYOUT 
		foreign key (LAYOUT_ID)
		references LAYOUT (LAYOUT_ID)
		on delete cascade
	       
/*==============================================================
 * Table: LAYOUT_CANDIDATE_OVERRIDE foreign key on CANDIDATE
 * restrict update 
 * cascade delete                                                 
 *==============================================================*/
begin
	-- drop constraint if it already exists so that!it can be recreated.
	Exec("
	if object_id('FK_LAYOUT_CANDIDATE_OVERRIDE_CANDIDATE') is not null
		alter table LAYOUT_CANDIDATE_OVERRIDE
	   	drop constraint FK_LAYOUT_CANDIDATE_OVERRIDE_CANDIDATE
	Exec("
	alter table LAYOUT_CANDIDATE_OVERRIDE
	add constraint FK_LAYOUT_CANDIDATE_OVERRIDE_CANDIDATE 
		foreign key (CANDIDATE_ID)
		references CANDIDATE (CANDIDATE_ID)
		on delete cascade
	       
/*==============================================================
 * Table: LAYOUT_CANDIDATE_OVERRIDE foreign key on LAYOUT
 * restrict update 
 * cascade delete                                                 
 *==============================================================*/
begin
	-- drop constraint if it already exists so that it can be recreated.
	Exec("
	if object_id('FK_LAYOUT_CANDIDATE_OVERRIDE_LAYOUT') 
	is not null
		alter table LAYOUT_CANDIDATE_OVERRIDE
		drop constraint FK_LAYOUT_CANDIDATE_OVERRIDE_LAYOUT
	Exec("
	alter table LAYOUT_AANDIDATE_OVERRIDE
	add constraint FK_LAYOUT_CANDIDATE_OVERRIDE_LAYOUT 
		foreign key (LAYOUT_ID)
		references LAYOUT (LAYOUT_ID)
		on delete cascade
	       
/*==============================================================
 * Table: LAYOUT_CONTEST foreign key on CONTEST
 * restrict update 
 * cascade delete                                                 
 *==============================================================*/
begin
	-- drop constraint if it already exists so that it cam be recreated.
	Exec("
	if object_id('FK_LAYOUT_CONTEST_CONTEST') is not null
		alter table LAYOUT_CONTEST
		drop constraint FK_LAYOUT_CONTEST_CONTEST
	Exec("
	alter table LAYOUT_CONTEST
	add constraint FK_LAYOUT_CONTEST_CONTEST 
		foreign key (CONTEST_ID)
		references CONTEST (CONTEST_ID)
		on delete cascade
	       
/*==============================================================
 * Table: LAYOUT_CONTEST foreign key on LAYOUT
 * restrict update 
 * cascade delete     !                                           
 *==============================================================*/
begin
	-- drop constraint if it already exists so that it can be recreated.
	Exec("
	if object_id('FK_LAYOUT_CONTEST_LAYOUT') is not null
		alter table LAYOUT_CONTEST
		drop constraint FK_LAYOUT_CONTEST_LAYOUT
	Exec("
	alter table LAYOUT_CONTEST
	add constraint FK_LAYOUT_CONTEST_LAYOUT 
		foreign key (LAYOUT_ID)
		references LAYOUT (LAYOUT_ID)
		on delete cascade	       
	end
/*==============================================================
 * Table: LAYOUT_FIELD foreign key on LAYOUT
 * restrict update 
 * cascade delete                                                 
 *==============================================================*/
begin
	Exec("
	-- drop constraint if it already exists so that it can be recreated.
	if object_id('FK_LAYOUT_FIELD_LAYOUT') is not null
		alter table LAYOUT_FIELD
		drop constraint FK_LAYOUT_FIELD_LAYOUT
	Exec("
	alter!table LAYOUT_FIELD
	add constraint FK_LAYOUT_FIELD_LAYOUT 
		foreign key (LAYOUT_ID)
		references LAYOUT (LAYOUT_ID)
		on delete cascade
	       
/*==============================================================
 * Table: LAYOUT_FIELD foreign key on FIELD
 * restrict update 
 * cascade delete                                                 
 *==============================================================*/
begin
	-- drop constraint if it already exists so that it can be recreated.
	Exec("
	if object_id('FK_LAYOUT_FIELD_FIELD') is not null
		alter table LAYOUT_FIELD
		drop constraint FK_LAYOUT_FIELD_FIELD
	Exec("
	alter table LAYOUT_FIELD
	add constraint FK_LAYOUT_FIELD_FIELD 
		foreign key (FIELD_ID)
		references FIELD (FIELD_ID)
		on delete cascade
	       
/*==============================================================
 * Table: LAYOUT_FIELD_TRANSLATION foreign key on LAYOUT_FIELD
 * restrict update 
5SE%
 * cascade delete                                                 
 *==============================================================*/
begin
	-- drop constraint if it already exists so that it can be recreated.
	Exec("
	if object_id('FK_LAYOUT_FIELD_TRANSLATION_LAYOUT_FIELD') is not null
		alter table LAYOUT_FIELD_TRANSLATION
		drop constraint FK_LAYOUT_FIELD_TRANSLATION_LAYOUT_FIELD
	Exec("
	alter table LAYOUT_FIELD_TRANSLATION
	add constraint FK_LAYOUT_FIELD_TRANSLATION_LAYOUT_FIELD 
		foreign key ( FIELD_ID
				  , LAYOUT_ID)
		references LAYOUT_FIELD (  FIELD_ID
							, LAYOUT_ID)
		on delete cascade
/*==============================================================
 * Table: LAYOUT_IMAGE foreign key on LAYOUT
 * restrict update 
 * cascade delete                                                 
 *==============================================================*/
begin
	-- drop constraint if it already exists so that it can be recreated.
	Exec("
	if object_id('FK_LAYOUT_IMAGE_LAYOUT') is not null
		alter table LAYOUT_IMAGE
		drop constraint FK_LAYOUT_IMAGE_LAYOUT
	Exec("
	alter table LAYOUT_IMAGE
	add constraint FK_LAYOUT_IMAGE_LAYOUT 
		foreign key (LAYOUT_ID)
		references LAYOUT (LAYOUT_ID)
		on delete cascade
	       
/*==============================================================
 * Table: LAYOUT_IMAGE_FILE fmreign key on LAYOUT
 * restrict update 
 * cascade delete                                                 
 *==============================================================*/
begin
	Exec("
	-- drop constraint if it already exists so that it can be recreated.
	if object_id('FK_LAYOUT_IMAGE_FILE_LAYOUT') is not null
		alter table LAYOUT_IMAGE_FILE
		drop constraint FK_LAYOUT_IMAGE_FILE_LAYOUT
	Exec("
	alter table LAYOUT_IMAGE_FILE
	add constraint FK_LAYOUT_IMAGE_FILE_LAYOUT 
		foreign key!(LAYOUT_ID)
		references LAYOUT (LAYOUT_ID)
		on delete cascade
	       
/*==============================================================
 * Table: LAYOUT_IMAGE_FILE_TRANSLATION foreign key on LAYOUT
 * restrict update 
 * cascade delete                                                 
 *==============================================================*/
begin
	-- drop constraint if it already exists so that it can be recreated.
	Exec("
	if object_id('FK_LAYOUT_IMAGE_FILE_TRANSLATION]LAYOUT') 
	is not null
		alter table LAYOUT_IMAGE_FILE_TRANSLATION
		drop constraint FK_LAYOUT_IMAGE_FILE_TRANSLATION_LAYOUT
	Exec("
	alter table LAYOUT_IMAGE_FILE_TRANSLATION
	add constraint FK_LAYOUT_IMAGE_FILE_TRANSLATION_LAYOUT 
		foreign key (LAYOUT_ID)
		references LAYOUT (LAYOUT_ID)
		on delete cascade
	       
/*==============================================================
 * Table: LAYOUT_IMAGE_TRANSLATION foreign key on LAYOUT
 * restrict update 
 * cascade eelete                                                 
 *==============================================================*/
begin
	-- drop constraint if it already exists so that it can be recreated.
	Exec("
	if object_id('FK_LAYOUT_IMAGE_TRANSLATION_LAYOUT')
	is not null
		alter table LAYOUT_IMAGE_TRANSLATION
		drop constraint FK_LAYOUT_IMAGE_TRANSLATION_LAYOUT
	Exec("
	alter table LAYOUT_IMAGE_TRANSLATION
	add constraint FK_LAYOUT_IMAGE_TRANSLATION_LAYOUT 
		foreign key (LAYOUT_ID)
		references LAYOUT (LAYOUT_ID)
		on delete cascade
	       
/*==============================================================
 * Table: LAYOUT_PARTY foreign key on LAYOUT
 * restrict update 
 * cascade delete                                                 
 *==============================================================*/
begin
	-- drop constraint if it already exists so that it can be recreated.
	Exec("
	if object_id('FK_LAYOUT_PARTY_LAYOUT') is not null
		alter table LAYOUT_PARTY
		drop constraint FK_L
AYOUT_PARTY_LAYOUT
	Exec("
	alter table LAYOUT_PARTY
	add constraint FK_LAYOUT_PARTY_LAYOUT 
		foreign key (LAYOUT_ID)
		references LAYOUT (LAYOUT_ID)
		on delete cascade
	       
/*==============================================================
 * Table: LAYOUT_SELECTION foreign key on LAYOUT
 * restrict update 
 * cascade delete                                                 
 *==============================================================*/
begin
	-- drop constraint if it already exists so that it can be recreated.
	Exec("
	if object_id('FK_LAYOUT_SELECTION_LAYOUT') is not null
		alter table LAYOUT_SELECTION
	   drop constraint FK_LAYOUT_SELECTION_LAYOUT
	Exec("
	alter table LAYOUT_SELECTION
	add constraint FK_LAYOUT_SELECTION_LAYOUT 
		foreign key (LAYOUT_ID)
		references LAYOUT (LAYOUT_ID)
		on delete cascade
	       
/*==============================================================
 * Table: LAYOUT_SELECTION foreign key on BALLOT_STYLE
 * restrict update 
 * cascade delete                                                 
 *==============================================================*/
begin
	-- drop constraint if it already exists so that it can be recreated.
	Exec("
	if object_id('FK_LAYOUT_SELECTION_BALLOT_STYLE') is not null
		alter table LAYOUT_SELECTION
		drop constraint FK_LAYOUT_SELECTION_BALLOT_STYLE
	Exec("
	alter table LAYOUT_SELECTION
	add constraint FK_LAYOUU_SELECTION_BALLOT_STYLE 
		foreign key (BALLOT_STYLE_ID)
		references BALLOT_STYLE (BALLOT_STYLE_ID)
		on delete cascade
	       
/*==============================================================
 * Table: LAYOUT_SELECTION_TRANSLATION foreign key on LAYOUT_SELECTION
 * cascade update 
 * cascade delete                                                 
 *==============================================================*/
begin
	-- drop constraint if it already exists so that it can be recreated.
	Exec("
	if object_id('FK_SELECTION_TRANSLATION_SELECTION') is not null
		alter table LAYOUT_SELECTION_TRANSLATION
		drop constraint FK_SELECTION_TRANSLATION_SELECTION
	Exec("
	alter table LAYOUT_SELECTION_TRANSLATION
	add constraint FK_SELECTION_TRANSLATION_SELECTION 
		foreign key 
		( 
			LAYOUT_ID
		, 	SELECTION_CODE
		references LAYOUT_SELECTION 
		( 
			LAYOUT_ID
		, 	SELECTION_CODE
		on delete cascade
		on update cascade
/*==============================================================
 * Table: LAYOUT_SPLIT foreign key on LAYOUT
 * restrict update 
 * cascade delete                                                 
 *==============================================================*/
begin
	-- drop constraint if it already exists so that it can be recreated.
	Exec("
	if object_id('FK_LAYOUT_SPLIT_LAYOUT') is not null
		alter table LAYOUT_SPLIT
	   	drop constraint FK_LAYOUT_SPLIT_LAYOUT
	Exec("
	alter table LAYOUT_SPLIT
	add constraint FK_LAYOUT_SPLIT_LAYOUT 
		foreign key (LAYOUT_ID)
		references LAYOUT (LAYOUT_ID)
		on delete cascade
/*==============================================================
 * Table: LAYOUT_SYMBOL foreign key on LAYOUT
 * restrict update 
 * cascade delete                                                 
 *==============================================================*/
begin
	-- drop constraint if it already exists so that it can be recreated.
	Exec("
	if object_id('FK_LAYOUT_SYMAOL_LAYOUT') is not null
		alter table LAYOUT_SYMBOL
		drop constraint FK_LAYOUT_SYMBOL_LAYOUT
	Exec("
	alter table LAYOUT_SYMBOL
	add constraint FK_LAYOUT_SYMBOL_LAYOUT 
		foreign key (LAYOUT_ID)
		references LAYOUT (LAYOUT_ID)
		on delete cascade
	       
/*==============================================================
 * Table: LAYOUT_SYMBOL foreign key on SYMBOL (dropped)
 * restrict update 
 * cascade delete             
                                    
 *==============================================================*/
begin
	-- drop constraint if it already exists.
	Exec("
	if object_id('FK_LAYOUT_SYMBOL_SYMBOL') is not null
		alter table LAYOUT_SYMBOL
		drop constraint FK_LAYOUT_SYMBOL_SYMBOL
end	
/*==============================================================
 * Table: LAYOUT_TEMPLATE foreign key on LAYOUT
 * restrict update 
 * cascade delete                                                 
 *==============================================================*/
begin
	-- drop constraint if it already exists so that it can be recreated.
	Exec("
	if object_id('FK_LAYOUT_TEMPLATE_LAYOUT') is not null
		alter table LAYOUT_TEMPLATE
		drop constraint FK_LAYOUT_TEMPLATE_LAYOUT
	Exec("
	alter table LAYOUT_TEMPLATE
	add constraint FK_LAYOUT_TEMPLATE_LAYOUT 
		foreign key (LAYMUT_ID)
		references LAYOUT (LAYOUT_ID)
		on delete cascade
	       
/*==============================================================
 * Table: PROPOSAL_DISPLAY foreign key on PROPOSAL
 * restrict update 
 * cascade delete                                                 
 *==============================================================*/
begin
	-- drop constraint if it already exists so that it can be recreated.
	Exec("
	if object_id('FK_PROPOSAL_DISPLAY_PROPOSAL') is not null
		alteq table PROPOSAL_DISPLAY
		drop constraint FK_PROPOSAL_DISPLAY_PROPOSAL
	Exec("
	alter table PROPOSAL_DISPLAY
	add constraint FK_PROPOSAL_DISPLAY_PROPOSAL 
		foreign key (PROPOSAL_ID)
		references PROPOSAL (PROPOSAL_ID)
		on delete cascade
	       
/*==============================================================
 * Table: PROPOSAL_TRANSLATION foreign key on PROPOSAL
 * restrict update 
 * cascade delete                                                 
 *==============================================================*/
begin
	-- drop constraint if it already exists so that it can be recreated.
	Exec("
	if object_id('FK_PROPOSAL_TRANSLATION_PROPOSAL') is not null
		alter table PROPOSAL_TRANSLATION
		drop constraint FK_PROPOSAL_TRANSLATION_PROPOSAL
	Exec("
	alter table PROPOSAL_TRANSLATION
	add constraint FK_PROPOSAL_TRANSLATION_PROPOSAL 
		foreign key (PROPOSAL_ID)
		references PROPOSAL (PROPOSAL_ID)
		on delete cascade
	       
/*==============================================================
 * Table: PROVISIONAL_STATUS foreign key on VOTER
 * restrict update 
 * cascade delete                                                 
 *==============================================================*/
begin
	-- drop constraint if it already exists so that it can be recreated.
	Exec("
	if object_id('FK_PROVISION_STATUS_VOTER') is not null
		alter table PROVISIONAL_STATUS
		drop constraint FK_PROVISION_STATUS_VOTER
	Exec("
	alter table!PROVISIONAL_STATUS
	add constraint FK_PROVISION_STATUS_VOTER 
		foreign key (VOTER_ID)
		references VOTER (VOTER_ID)
		on delete cascade
/*==============================================================
 * Table: PROVISIONAL_VOTE foreign key on VOTER
 * restrict update 
 * cascade delete                                                 
 *==============================================================*/
begin
	-- drop constraint if it already exists so that it can be recreated.
	Exec("
	if object_id('FK_PROVISIONAL_VOTE_VOTER') is not null
		alter table PROVISIONAL_VOTE
		drop constraint FK_PROVISIONAL_VOTE_VOTER
	Exec("
	alter table PROVISIONAL_VOTE
	add constraint FK_PROVISIONAL_VOTE_VOTER 
		foreign key (VOTER_ID)
		references VOTER (VOTER_ID)
		on delete cascade
/*==============================================================
 * Table: PROVISIONAL_VOTE foreign key on CANDIDATE
 * restrict update 
 * restrict delete                             !                   
 *==============================================================*/
begin
	-- drop constraint if it already exists so that it can be recreated.
	Exec("
	if object_id('FK_PROVISIONAL_VOTE_CANDIDATE') is not null
		alter table PROVISIONAL_VOTE
		drop constraint FK_PROVISIONAL_VOTE_CANDIDATE
	Exec("
	alter table PROVISIONAL_VOTE
	add constraint FK_PROVISIONAL_VOTE_CANDIDATE 
		foreign key (CANDIDATE_ID)
		references CANDIDATE (CANDIDATE_ID)
	    ! 
	       
/*==============================================================
 * Table: ROTATION foreign key on CONTEST
 * restrict update 
 * cascade delete                                                 
 *==============================================================*/
begin
	-- drop constraint if it already exists so that it can be recreated.
	Exec("
	if object_id('FK_ROTATION_CONTEST') is not null
		alter table ROTATION
	drop constraint FK_ROTATION_CONTEST
	Exec("
	amter table ROTATION
	add constraint FK_ROTATION_CONTEST 
		foreign key (CONTEST_ID)
		references CONTEST (CONTEST_ID)
		on delete cascade
	       
/*==============================================================
 * Table: TALLY_BLANK_BALLOT foreign key on TURNOUT_MACHINE
 *  remove                                                
 *==============================================================*/
begin
	-- drop constraint if it already exists- constraint no longer necessary.
	Exec("
		if object_id('FK_TALLY_BLANK_BALLOT_TURNOUT_MACHINE') 
	is not null
		alter table TALLY_BLANK_BALLOT
		drop constraint FK_TALLY_BLANK_BALLOT_TURNOUT_MACHINE
/*==============================================================
 * Table: TALLY_BLANK_VOTE foreign key on TURNOUT_MACHINE
 * restrict update 
 * cascade delete                                                 
 *==============================================================*/
begin
	-- drop constraint if it already exists so that it can be recreated.
	Exec("
	if object_id('FK_TALLY_BLANK_VOTE_TURNOUT_MACHINE') 
	is not null
		alter table TALLY_BLANK_VOTE
		drop constraint FK_TALLY_BLANK_VOTE_TURNOUT_MACHINE
	Exec("
	alter table TALLY_BLANK_VOTE
	add constraint FK_TALLY_BLANK_VOTE_TURNOUT_MACHINE 
		foreign key 
			SERIAL_NUMBER
		 , 	TALLY_MODE
		 , 	PRECINCT_ID
		 , 	TALLY_TYPE_ID
		 , 	SELECTION_CODE
		 )
		references TURNOUT_MACHINE 
			SERIAL_NUMBER
		 , 	TALLY_MODE
		 ,	PRECINCT_ID
		 , 	TALLY_TYPE_ID
		 , 	SELECTION_CODE
		 )
	  on delete cascade
	       
/*==============================================================
 * Table: TALLY_BLANK_VOTE foreign key on CONTEST
 * restrict update 
 * restrict delete                                                 
 *==============================================================*/
begin
	-- drop constraint if it already exists so that it can be recreated.
	Exec("
	if object_id('FK_TALLY_BLANK_VOTE_CONTEST') is not null
		alter table TALLY_BLANK_VOTE
		drop constraint FK_TALLY_BLANK_VOTE_CONTEST
	Exec("
	alter table TALLY_BLANK_VOTE
	add constraint FK_TALLY_BLANK_VOTE_CONTEST 
		foreign key (CONTEST_ID)
		references CONTEST (CONTEST_ID)	       
/*==============================================================
 * Table: TALLY_EV foreign key on CANDIDATE
 * restrict update 
 * restrict delete                                                 
 *==============================================================*/
begin
	-- drop constraint if it already exists so that it can be recreated.
	Exec("
	if object_id('FK_TALLY_EV_CANDIDATE') is not null
		alter table TALLY_EV
		drop constraint FK_TALLY_EV_CANDIDATE
	Exec("
	alter table TALLY_EV
	add constraint FK_TALLY_EV_CANDIDATE 
		foreign key (CANDIDATE_ID)
		references CANDIDATE (CANDIDATE_ID)
	       
/*==============================================================
Table: TALLY_LOAD foreign key on CANDIDATE
 * restrict update 
 * restrict delete                                                 
 *==============================================================*/
begin
	-- drop constraint if it already exists so that it can be recreated.
Exec("
	if object_id('FK_TALLY_LOAD_CANDIDATE') is not null
		alter table TALLY_LOAD
		drop constraint FK_TALLY_LOAD_CANDIDATE
	Exec("
	alter table TALLY_LOAD
	add constraint FK_TALLY_LOAD_CANDIDATE 
		foreign key (CANDIDATE_ID)
		references CANDIDATE (CANDIDATE_ID)
	      
	       
/*==============================================================
 * Table: TALLY_MACHINE foreign key on CANDIDATE
 * restrict update 
 * restrict delete                                                 
 *==============================================================*/
begin
	-- drop constraint if it already exists so that it can be recreated.
	Exec("
	if object_id('FK_TALLY_MACHINE_CANDIDATE') is not null
		alter table TALLY_MACHINE
	   	drop constraint FK_TALLY_MACHINE_CANDIDATE
	Exec("
	alter table TALLY_MACHINE
	add constraint FK_TALLY_MACHINE_CANDIDATE 
		foreign key (CANDIDATE_ID)
		references CANDIDATE (CANDIDATE_ID)
	      
	       
/*==============================================================
 * Table: TALLY_OVER_VOTE foreign key on TURNOUT_MACHINE
 * restricu update 
 * cascade delete                                                 
 *==============================================================*/
begin
	-- drop constraint if it already exists.
	Exec("
	if object_id('FK_TALLY_OVER_VOTE_TURNOUT_MACHINE') 
	is not null
		alter table TALLY_OVER_VOTE
		drop constraint FK_TALLY_OVER_VOTE_TURNOUT_MACHINE
/*==============================================================
 * Table: TALLY_OVER_VOTE foreign key on CONTEST
 * restrict update 
 *!restrict delete                                                 
 *==============================================================*/
begin
	-- drop constraint if it already exists so that it can be recreated.
	Exec("
	if object_id('FK_TALLY_OVER_VOTE_CONTEST') is not null
		alter table TALLY_OVER_VOTE
		drop constraint FK_TALLY_OVER_VOTE_CONTEST
	Exec("
	alter table TALLY_OVER_VOTE
	add constraint FK_TALLY_OVER_VOTE_CONTEST 
		foreign key (CONTEST_ID)
		references CONTEST (CONTEST_ID)
	!     
	       
/*==============================================================
 * Table: TALLY_SESSION foreign key on TALLY_PROFILE
 * restrict update 
 * cascade delete                                                 
 *==============================================================*/
begin
	-- drop constraint if it already exists so that it can be recreated.
	Exec("
	if object_id('FK_TALLY_SESSION_TALLY_PROFILE') is not null
		alter table TALLY_SESSION
		drop constraint FK_TALLY]SESSION_TALLY_PROFILE
	Exec("
	alter table TALLY_SESSION
	add constraint FK_TALLY_SESSION_TALLY_PROFILE 
		foreign key (TALLY_PROFILE_ID)
		references TALLY_PROFILE (TALLY_PROFILE_ID)
		on delete cascade
	       
/*==============================================================
 * Table: TALLY_UNDER_VOTE foreign key on TURNOUT_MACHINE
 * restrict update 
 * cascade delete                                                 
 *==============================================================*/
begin
	-- drop constraint if it already exists.
	Exec("
	if object_id('FK_TALLY_UNDER_VOTE_TURNOUT_MACHINE') is not null
		alter table TALLY_UNDER_VOTE
		drop constraint FK_TALLY_UNDER_VOTE_TURNOUT_MACHINE
end	
/*==============================================================
 * Table: TALLY_UNDER_VOTE foreign key on CONTEST
 * restrict update 
 * restrict delete                                                 
 *==============================================================*/
begin
	-- drop cons
traint if it already exists so that it can be recreated.
	Exec("
	if object_id('FK_TALLY_UNDER_VOTE_CONTEST') is not null
		alter table TALLY_UNDER_VOTE
		drop constraint FK_TALLY_UNDER_VOTE_CONTEST
	Exec("
	alter table TALLY_UNDER_VOTE
	add constraint FK_TALLY_UNDER_VOTE_CONTEST 
		foreign key (CONTEST_ID)
		references CONTEST (CONTEST_ID)
	      
	       
/*==============================================================
 * Table: WRITEIN foreign key on VOTER
 * restrict update 
 * cascade delete                                                 
 *==============================================================*/
begin
	-- drop constraint if it already exists so that it can be recreated.
	Exec("
	if object_id('FK_WRITEIN_VOTER') is not null
		alter table WRITEIN
		drop constraint FK_WRITEIN_VOTER
	Exec("
	alter table WRITEIN
	add constraint FK_WRITEIN_VOTER 
		foreign key (VOTER_ID)
		references VOTER (VOTER_ID)
		on delete cascade
	       
/*==============================================================
 * Table: WRITEIN foreign key on CANDIDATE
 * restrict update 
 * restrict delete                                                 
 *==============================================================*/
begin
	-- drop constraint if it already exists so that it can be recreated.
	Exec("
	if object_id('FK_WRITE_CANDIDATE') is not null
		alter table WRITEIN
		drop constraint FK_WRITE_CANDIDATE
	Exec("
	alter table WRITEIN
	add constraint FK_WRITE_CANDIDATE 
		foreign key (CANDIDATE_ID)
		references CANDIDATE (CANDIDATE_ID)
end -- end procedure CreateConstraints
-- create table Candidate_Type
/*************************************************************************
Candidate_Type_ID	Identifier of the candidate type
				0: Standard
				1: Straight Party
				2: Endorsed Candidate
				3: Write-In
				4: Proposal Response
				5: Selective Primary
				6: None
				7: Proportional
				9: Resolved Write-In
				255: Print-Only
Is_Rotated		0: No, 1: Yes
Name				Name of Candidate Type
**************************************************************************/
begin
	-- drop table if it already exists so that it can be recreated.
	IF  EXISTS(	SELECT 
					1 
				FROM 
					INFORMATION_SCHEMA.TABLES
				WHERE 
					Table_Name = 'Candidate_Type')
		DROP TABLE 
			Candidate_Type
	Exec("
	CREATE TABLE Candidate_Type 
		Candidate_Type_ID 	int			NOT NULL 
	,	Is_Rotated 		bit 			NOT NULL 
	,	Name 			varchar (50) 	NOT NULL 
	,	CONSTRAINT PK_Candidate_Type PRIMARY KEY CLUSTERED 
			Candidate_Type_ID
		)  
	-- Populate table Candidate_Type
	Exec("
	INSERT INTO 
		Candidate_Type 
	VALUES 
	, 	1
	, 	'Standard'
	INSERT INTO 
		Candidate_Type 
	VALUES 
	, 	0
	, 	'Straight Party'
	INSERT INTO 
		Candidate_Type 
	VALUES 
	, 	1
	, 	'Endorsed Candidate'
	INSERT IMTO 
		Candidate_Type 
	VALUES 
	, 	0
	, 	'Write-In'
	INSERT INTO 
		Candidate_Type 
	VALUES 
	, 	0
	, 	'Proposal Response'
	INSERT INTO 
		Candidate_Type 
	VALUES 
	, 	0
	, 	'Selective Primary'
	INSERT INTO 
		Candidate_Type 
	VALUES 
	, 	0
	, 	'None'
	INSERT INTO 
		Candidate_Type 
	VALUES 
	, 	0
	, 	'Proportional'
	INSERT INTO 
		Candidate_Type 
	VALUES 
	, 	0
	, 	'Resolved Write-In'
	IMSERT INTO 
		Candidate_Type 
	VALUES 
		255
	, 	1
	, 	'Print-Only'
-- drop PLATES tables (Plates1, Plates2, Plates3, Plates4)
-- before recreating them
begin
	IF  EXISTS(	SELECT 
					1 
				FROM 
					INFORMATION_SCHEMA.TABLES
				WHERE 
					Table_Name = 'Plates1')
		DROP TABLE 
			Plates1
	IF  EXISTS(	SELECT 
					1 
				FROM 
					INFORMATION_SCHEMA.TABLES
				WHERE 
					Table_Name = 'Plates2')
		DROP T
~Eh9
