You are trying to build a complex query/plpgsql function and keep getting parse errors referring to an error near ' or similar.
Build your query/function in a text editor and execute using
psql -f (file) (database)
|
This gives you line numbers with the error message, and lets you run through the test/debug cycle quickly ref.