Index: modules/uoa-search/branches/newAPI/src/main/java/eu/dnetlib/data/search/solr/SolrResultSet.java
===================================================================
--- modules/uoa-search/branches/newAPI/src/main/java/eu/dnetlib/data/search/solr/SolrResultSet.java	(revision 44662)
+++ modules/uoa-search/branches/newAPI/src/main/java/eu/dnetlib/data/search/solr/SolrResultSet.java	(revision 44663)
@@ -181,10 +181,10 @@
         QueryResponse rsp = null;
         HashMap<String, List<String>> map = new HashMap<String, List<String>>();
 
-        logger.debug("from: " + from);
+        logger.debug("from: " + from*to);
         logger.debug("to: " + to);
 
-        queryOpts.add("start", from + "");
+        queryOpts.add("start", from*to + "");
         queryOpts.add("rows", to +"");
 
         try {
Index: modules/uoa-search/branches/newAPI/src/main/java/eu/dnetlib/data/search/app/SearchServiceImpl.java
===================================================================
--- modules/uoa-search/branches/newAPI/src/main/java/eu/dnetlib/data/search/app/SearchServiceImpl.java	(revision 44662)
+++ modules/uoa-search/branches/newAPI/src/main/java/eu/dnetlib/data/search/app/SearchServiceImpl.java	(revision 44663)
@@ -221,15 +221,15 @@
 
         } catch (IndexServiceException ise) {
             logger.error("Error calling index.", ise);
-            throw new SearchServiceException("Error calling index.");
+            throw new SearchServiceException("Error calling index.", ise);
 
         } catch (CQLParseException cqle) {
             logger.error("Bad CQL query.", cqle);
-            throw new SearchServiceException("Error calling index.");
+            throw new SearchServiceException("Error calling index.", cqle);
 
         } catch (IOException ioe) {
             logger.error("Bad CQL query.", ioe);
-            throw new SearchServiceException("Error calling index.");
+            throw new SearchServiceException("Error calling index.", ioe);
         }
 
         if (epr == null) {
@@ -444,15 +444,15 @@
 
         } catch (IndexServiceException ise) {
             logger.error("Error calling index.", ise);
-            throw new SearchServiceException("Error calling index.");
+            throw new SearchServiceException("Error calling index.", ise);
 
         } catch (CQLParseException cqle) {
             logger.error("Bad CQL query.", cqle);
-            throw new SearchServiceException("Error calling index.");
+            throw new SearchServiceException("Error calling index.", cqle);
 
         } catch (IOException ioe) {
             logger.error("Bad CQL query.", ioe);
-            throw new SearchServiceException("Error calling index.");
+            throw new SearchServiceException("Error calling index.", ioe);
         }
 
         if (epr == null) {
@@ -526,10 +526,10 @@
 
         } catch (CQLParseException cqle) {
             logger.error("Bad CQL query.", cqle);
-            throw new SearchServiceException("Error calling index.");
+            throw new SearchServiceException("Error calling index.", cqle);
         } catch (IOException ioe) {
             logger.error("Bad CQL query.", ioe);
-            throw new SearchServiceException("Error calling index.");
+            throw new SearchServiceException("Error calling index.", ioe);
         } catch (IndexServiceException ise) {
             logger.error("Error getting refine results.", ise);
             throw new SearchServiceException("Error getting refine results.", ise);
Index: modules/uoa-search/branches/newAPI/src/main/java/eu/dnetlib/data/search/transform/config/SearchRegistry.java
===================================================================
--- modules/uoa-search/branches/newAPI/src/main/java/eu/dnetlib/data/search/transform/config/SearchRegistry.java	(revision 44662)
+++ modules/uoa-search/branches/newAPI/src/main/java/eu/dnetlib/data/search/transform/config/SearchRegistry.java	(revision 44663)
@@ -108,7 +108,7 @@
 				}
 				catch (Exception e) {
 					logger.warn("Error creating a transformer with name: "+name+" and locale: "+locale.getDisplayName(), e);
-					throw new SearchFactoryException();
+					throw new SearchFactoryException("Error creating a transformer with name: "+name+" and locale: "+locale.getDisplayName(), e);
 				}
 			}
 			else {
@@ -121,7 +121,7 @@
 			}
 			catch (Exception e) {
 				logger.warn("Error creating a transformer with name: " + name + " and locale: "+locale.getDisplayName(), e);
-				throw new SearchFactoryException();
+				throw new SearchFactoryException("Error creating a transformer with name: " + name + " and locale: "+locale.getDisplayName(), e);
 			}
 		}
 		return new ChainTransformer(name, forChaining);
Index: modules/uoa-search/branches/newAPI/src/main/java/eu/dnetlib/data/search/web/api/SearchApiService.java
===================================================================
--- modules/uoa-search/branches/newAPI/src/main/java/eu/dnetlib/data/search/web/api/SearchApiService.java	(revision 44662)
+++ modules/uoa-search/branches/newAPI/src/main/java/eu/dnetlib/data/search/web/api/SearchApiService.java	(revision 44663)
@@ -4,12 +4,9 @@
 import eu.dnetlib.data.search.app.SearchServiceImpl;
 import eu.dnetlib.data.search.web.utils.RequestResponseHandler;
 import eu.dnetlib.domain.data.SearchResult;
-import eu.dnetlib.functionality.index.cql.CqlTranslator;
-import eu.dnetlib.functionality.index.cql.CqlTranslatorImpl;
 import org.apache.log4j.Logger;
 import org.springframework.beans.factory.annotation.Autowired;
 import org.springframework.stereotype.Component;
-import org.z3950.zing.cql.CQLParseException;
 
 import javax.servlet.http.HttpServletRequest;
 import javax.ws.rs.*;
@@ -16,7 +13,6 @@
 import javax.ws.rs.core.Context;
 import javax.ws.rs.core.MediaType;
 import javax.ws.rs.core.Response;
-import java.io.IOException;
 import java.util.List;
 import java.util.Locale;
 
@@ -74,12 +70,12 @@
                                       @QueryParam("format") final String format,
                                       @Context final HttpServletRequest request) {
         String responseType = extractResponseFormat(format);
-        String simpleQuery = createSimpleSearchQuery(RequestResponseHandler.Entity.PUBLICATION, keywords);
+        String simpleQuery = buildSimpleSearchQuery(RequestResponseHandler.Entity.PUBLICATION, keywords);
             return getResponseByEntity(simpleQuery, RequestResponseHandler.Entity.PUBLICATION, offset, limit, responseType, request, refine, fields, fieldQueries, responseType);
 
     }
 
-    private String createSimpleSearchQuery(RequestResponseHandler.Entity entity, String keywords) {
+    private String buildSimpleSearchQuery(RequestResponseHandler.Entity entity, String keywords) {
         StringBuilder queryBuilder = new StringBuilder();
         enhanceQueryWithEntityType(queryBuilder,entity);
         enhanceQueryWithKeywords(queryBuilder, keywords);
@@ -147,7 +143,7 @@
         }
         return fq.toString();
     }
-
+*/
     @GET
     @Path("/api/publications/count")
     @Produces({MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML})
@@ -155,8 +151,8 @@
         String fullQuery = builtQueryByEntity(query, RequestResponseHandler.Entity.PUBLICATION);
         return getCount(fullQuery);
     }
-*/
 
+
     @GET
     @Path("/api/publications/{publicationid}")
     @Produces({MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML})
@@ -486,102 +482,37 @@
 */
 
     private void enhanceQueryWithKeywords(StringBuilder queryBuilder, String keywords) {
-        if (keywords != null && !keywords.trim().isEmpty()) {
-            queryBuilder.append(" and (").append(keywords).append(")");
-        }
+        CQLQueryGeneration.appendKeywords(queryBuilder,keywords);
     }
 
-    //@Deprecated
-    /*private void enhanceQueryWithKeywords(StringBuilder queryBuilder, List<String> keywordOperators, List<String> keywords) {
-        if (keywordOperators != null && !keywordOperators.isEmpty()) {
-            if (keywords != null && !keywords.isEmpty()) {
-                if (keywordOperators.size() != keywords.size()) {
-                    throw new IllegalArgumentException("Keywords and Operators are not matched");
-                }
-            } else {
-                throw new IllegalArgumentException("Keywords and Operators are not matched");
-            }
-        }
-
-        for(int i = 0; i < keywords.size(); i++) {
-            queryBuilder.append(' ').append(keywordOperators.get(i)).append(' ').append('(').append(keywords.get(i)).append(")");
-        }
-    }*/
-
-    /*
-    private void enhanceQueryWithParameters(StringBuilder queryBuilder, Map<String, String[]> operators, Map<String, String[]> parameters, Map<String, String> parameterIndexMap, Map<String, String> parameterOperatorMap) {
-        if (parameterIndexMap != null && !parameterIndexMap.isEmpty()) {
-            if (parameterOperatorMap != null && !parameterOperatorMap.isEmpty()) {
-                for(String operatorType:operators.keySet()) {
-                    //enhance messages with >, < ?? or maybe move all checks in the beginning?
-                    if (operators.get(operatorType).length != parameters.get(parameterOperatorMap.get(operatorType)).length ) {
-                        throw new IllegalArgumentException("Parameters and Operators are not matched");
-                    }
-
-                    String parameterName = parameterOperatorMap.get(operatorType);
-
-                    for(int i = 0; i < operators.get(operatorType).length; i++) {
-                        String indexField = parameterIndexMap.get(parameterOperatorMap.get(operatorType));
-
-                        /*logger.debug("operator " + operatorType);
-                        logger.debug("operator map get" + parameterOperatorMap.get(operatorType));
-
-                        logger.debug("index map" + parameterIndexMap.keySet());
-                        logger.debug("index map values" + parameterIndexMap.values());
-
-                        logger.debug("index field " + indexField);*/
-/*
-                        if (indexField != null) {
-//                          logger.debug(indexField + " " + operators.get(operatorType)[i] + " " + parameters.get(parameterName)[i]);
-                            queryBuilder.append(' ').append(operators.get(operatorType)[i]).append('(').append(indexField).append(" = ").append(parameters.get(parameterName)[i]).append(")");
-
-                        } else { //TODO check if needed
-                            logger.debug("and here!");
-                            logger.debug(" " + operators.get(operatorType)[i] + " " + parameters.get(operatorType)[i]);
-                            queryBuilder.append(" " + operators.get(operatorType)[i] + " " + parameters.get(operatorType)[i]);
-                        }
-                    }
-                }
-            } else  {
-                throw new IllegalArgumentException("Keywords and Operators are not matched");
-            }
-
-        }
-    }
-*/
-    /*
-    private boolean isFirstTerm(StringBuilder queryBuilder) {
-        return queryBuilder.toString().trim().equals("");
-    }*/
-
-    public void builtEntityIdQuery(StringBuilder queryBuilder, RequestResponseHandler.Entity entity, String entityId){
+    private void builtEntityIdQuery(StringBuilder queryBuilder, RequestResponseHandler.Entity entity, String entityId){
         enhanceQueryWithEntityType(queryBuilder, entity);
         enhanceQueryWithEntityId(queryBuilder, entityId);
     }
 
-    public String builtEntity2EntityRelationQuery(RequestResponseHandler.Entity entity, String relationfield, String entityId){
+    private String builtEntity2EntityRelationQuery(RequestResponseHandler.Entity entity, String relationfield, String entityId){
         StringBuilder queryBuilder = new StringBuilder();
         enhanceQueryWithEntityType(queryBuilder, entity);
-        enhanceQueryWithEntity2EntityId(queryBuilder, relationfield, entityId);
+        enhanceQueryWithRelationId(queryBuilder, relationfield, entityId);
         return queryBuilder.toString();
     }
 
-    private void enhanceQueryWithEntity2EntityId(StringBuilder queryBuilder, String relationfield, String entityId) {
+    private void enhanceQueryWithRelationId(StringBuilder queryBuilder, String relationfield, String entityId) {
         CQLQueryGeneration.appendTerm(queryBuilder, CQLQueryGeneration.Operator.AND, " " + relationfield + " ", CQLQueryGeneration.Operator.EXACT, entityId);
     }
 
 
-    public void enhanceQueryWithEntityType(StringBuilder queryBuilder, RequestResponseHandler.Entity entity) {
+    private void enhanceQueryWithEntityType(StringBuilder queryBuilder, RequestResponseHandler.Entity entity) {
         queryBuilder.append(entity.getQueryPrefix());
     }
 
-    public void enhanceQueryWithEntityId(StringBuilder queryBuilder, String entityId) {
+    private void enhanceQueryWithEntityId(StringBuilder queryBuilder, String entityId) {
         CQLQueryGeneration.appendTerm(queryBuilder, CQLQueryGeneration.Operator.AND, "objidentifier", CQLQueryGeneration.Operator.EXACT, entityId);
     }
 
-    public String builtQueryByEntity(String query, RequestResponseHandler.Entity entity) {
+    private String builtQueryByEntity(String query, RequestResponseHandler.Entity entity) {
         StringBuilder queryBuilder = new StringBuilder();
-        queryBuilder.append(entity.getQueryPrefix());
+        enhanceQueryWithEntityType(queryBuilder, entity);
 
         if (query != null && !query.trim().isEmpty()) {
             CQLQueryGeneration.appendSimpleTerm(queryBuilder, CQLQueryGeneration.Operator.AND, "(" + query + ")");
@@ -589,72 +520,7 @@
 
         return queryBuilder.toString();
     }
-/*
-    public void extractParameterNOperatorsValues(Map<String, String[]> parameterMap, Map<String, String[]> operatorTypeValues, Map<String, String[]> parameterTypeValues, RequestResponseHandler.Entity entity) {
-        for (String parameter:parameterMap.keySet()) {
-            Map<String, String> parameterIndexMap = entity.getParameterIndexMap();
-            Map<String, String> parameterOperatorMap = entity.getParameterOperatorMap();
 
-            if (parameterOperatorMap.get(parameter) != null) {
-                operatorTypeValues.put(parameter, parameterMap.get(parameter));
-
-            } else if (parameterIndexMap.get(parameter) != null) {
-                parameterTypeValues.put(parameter, parameterMap.get(parameter));
-
-            } else if (!parameter.equals("q") && !parameter.equals("op") && !parameter.equals("size") && !parameter.equals("page") && !parameter.equals("fields") && !parameter.equals("refine")){
-                throw new IllegalArgumentException("The parameter " + parameter + " is not supported.");
-            }
-
-            if (parameterTypeValues.get(parameter) == null) {
-                logger.debug("parameterTypeValues is null");
-            } else {
-                logger.debug("parameterTypeValues " + Arrays.asList(parameterTypeValues.get(parameter)));
-            }
-
-        }
-
-        //TODO make checks per type????
-        if (operatorTypeValues.size() != parameterTypeValues.size()) {
-            throw new IllegalArgumentException("Parameters and Operators do not match.");
-        }
-    }
-/*
-    *//* For each parameter get the values and the operators *//*
-    public void extractParameterOperatorsNValues(Map<String, String[]> requestParameterMap, Map<String, String[]> keywordOperatorValueMap, Map<String, String[]> keywordValuesMap,
-                                                 Map<String, String[]> operatorValueMap, Map<String, String[]> parameterValuesMap, RequestResponseHandler.Entity entity) {
-
-        for (String parameter:requestParameterMap.keySet()) {
-            Map<String, String> parameterIndexMap = entity.getParameterIndexMap();
-            Map<String, String> parameterOperatoMap = entity.getParameterOperatorMap();
-
-            if (parameterOperatoMap.get(parameter) != null) {
-                operatorValueMap.put(parameter, requestParameterMap.get(parameter));
-
-            } else if (parameterIndexMap.get(parameter) != null) {
-                parameterValuesMap.put(parameter, requestParameterMap.get(parameter));
-
-            } else if (parameter.equals("q")) {
-                keywordValuesMap.put("q", requestParameterMap.get("q"));
-
-            } else if (parameter.equals("op")) {
-                keywordOperatorValueMap.put("op", requestParameterMap.get("op"));
-
-            } else if (!parameter.equals("size") && !parameter.equals("page") && !parameter.equals("fields") && !parameter.equals("refine")){
-                throw new IllegalArgumentException("The parameter " + parameter + " is not supported.");
-            }
-
-            if (parameterValuesMap.get(parameter) == null) {
-                logger.debug("parameterTypeValues is null");
-            } else {
-                logger.debug("parameterTypeValues " + Arrays.asList(parameterValuesMap.get(parameter)));
-            }
-        }
-
-        if ((operatorValueMap.size() != parameterValuesMap.size()) || (keywordOperatorValueMap.size() != keywordValuesMap.size())) {
-            throw new IllegalArgumentException("Operators do not match parameters.");
-        }
-    }*/
-
     private Response getCount(String query) {
         try {
             SearchResult searchResult = searchService.search(query, null, Locale.getDefault().toString(), 0, 0);
@@ -665,19 +531,6 @@
         }
     }
 
-    /* TODO remove?
-    private Response getCountByEntity2EntityRelation(String query, RequestResponseHandler.Entity entity, String relationfield, String entityId) {
-        String fullQuery =  builtEntity2EntityRelationQuery(entity, relationfield, entityId);
-
-        try {
-            SearchResult searchResult = searchService.search(fullQuery, null, Locale.getDefault().toString(), 0, 0);
-            return Response.status(Response.Status.OK).entity(ResponseFormatter.createCountMeta(fullQuery.replace("\"", "\\\""), searchResult.getTotal())).build();
-
-        } catch (SearchServiceException sse) {
-            return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(ResponseFormatter.compose500Message("Fail to fetch count for query " + fullQuery.replace("\"", "\\\"") + ".", sse.getMessage())).build();
-        }
-    } */
-
     private Response getResponseByEntityId(HttpServletRequest request, RequestResponseHandler.Entity entity, String entityId, String responseType) {
         try {
             StringBuilder queryBuilder = new StringBuilder();
@@ -712,17 +565,19 @@
         }
     }
 
-    private void formatRefineResults(StringBuilder refineBuilder, SearchResult refineResults) {
-        int i = 0;
-        for (String json: refineResults.getBrowseResults()) {
-            if (i == (refineResults.getBrowseResults().size() - 1)) {
-                refineBuilder.append(json);
-            } else {
-                refineBuilder.append(json).append(",");
-            }
-            i++;
+
+    /* TODO remove?
+    private Response getCountByEntity2EntityRelation(String query, RequestResponseHandler.Entity entity, String relationfield, String entityId) {
+        String fullQuery =  builtEntity2EntityRelationQuery(entity, relationfield, entityId);
+
+        try {
+            SearchResult searchResult = searchService.search(fullQuery, null, Locale.getDefault().toString(), 0, 0);
+            return Response.status(Response.Status.OK).entity(ResponseFormatter.createCountMeta(fullQuery.replace("\"", "\\\""), searchResult.getTotal())).build();
+
+        } catch (SearchServiceException sse) {
+            return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(ResponseFormatter.compose500Message("Fail to fetch count for query " + fullQuery.replace("\"", "\\\"") + ".", sse.getMessage())).build();
         }
-    }
+    } */
 
 
 /*
@@ -797,10 +652,12 @@
 
     }
 */
+    /*
 
     public static void main(String[] args) throws IOException, CQLParseException {
         CqlTranslator translator = new CqlTranslatorImpl();
         System.out.println(translator.toLucene("relfundinglevel0_id = ec__________::EC::FP7"));
     }
+    */
 
 }
\ No newline at end of file
Index: modules/uoa-search/branches/newAPI/src/main/java/eu/dnetlib/data/search/web/api/CQLQueryGeneration.java
===================================================================
--- modules/uoa-search/branches/newAPI/src/main/java/eu/dnetlib/data/search/web/api/CQLQueryGeneration.java	(revision 44662)
+++ modules/uoa-search/branches/newAPI/src/main/java/eu/dnetlib/data/search/web/api/CQLQueryGeneration.java	(revision 44663)
@@ -30,6 +30,12 @@
 
     }
 
+    public static void appendKeywords(StringBuilder stringBuilder, String keywords) {
+        if (keywords != null && !keywords.trim().isEmpty()) {
+            stringBuilder.append(" ").append(Operator.AND).append(" (").append(keywords).append(")");
+        }
+    }
+
     public static void appendSimpleTerm(StringBuilder stringBuilder, Operator queryOperator, String termValue) {
         stringBuilder.append(' ').append(queryOperator).append(" (").append(termValue).append(')');
     }
Index: modules/uoa-search/branches/newAPI/src/main/java/eu/dnetlib/data/search/web/api/JSONResponseFormat.java
===================================================================
--- modules/uoa-search/branches/newAPI/src/main/java/eu/dnetlib/data/search/web/api/JSONResponseFormat.java	(revision 44662)
+++ modules/uoa-search/branches/newAPI/src/main/java/eu/dnetlib/data/search/web/api/JSONResponseFormat.java	(revision 44663)
@@ -9,6 +9,7 @@
     public static final String error400Message = "{ \"status\" : \"error\", \"code\" : \"400\", \"message\" : \"%s\"}";
     public static final String error500Message = "{ \"status\" : \"fail\", \"code\" : \"500\", \"message\" : \"%s\", \"description\" : \"%s\" }";
 
+    public static final String countSearch = "{\"status\": \"success\", \"code\":\"200\", \"query\":\"%s\", \"total\":\"%s\", \"_links\": {%s}}";
 
     public static final String singleValueResponse = "{\"meta\": %s, %s }";
     public static final String response = "{\"meta\": %s, \"results\" : [%s] %s}";
Index: modules/uoa-search/branches/newAPI/src/main/java/eu/dnetlib/data/search/web/api/XMLResponseFormat.java
===================================================================
--- modules/uoa-search/branches/newAPI/src/main/java/eu/dnetlib/data/search/web/api/XMLResponseFormat.java	(revision 44662)
+++ modules/uoa-search/branches/newAPI/src/main/java/eu/dnetlib/data/search/web/api/XMLResponseFormat.java	(revision 44663)
@@ -9,6 +9,8 @@
     public static final String error400Message = "<response><status>error</status><code>400</code><message>%s</message></response>";
     public static final String error500Message = "<response><status>fail</status><code>500</code><message>%s</message><description>%s</description></response>";
 
+    public static final String countSearch = "<response><status>success/status><code>200</code><query>%s</query><total>%s</total><links>%s</links></response>";
+
     public static final String singleValueResponse = "<response><meta>%s</meta>%s</response>";
     public static final String response = "<response><meta>%s</meta><results>%s</results>%s</response>";
 
Index: modules/uoa-search/branches/newAPI/src/main/java/eu/dnetlib/data/search/web/api/QueryEnhancer.java
===================================================================
--- modules/uoa-search/branches/newAPI/src/main/java/eu/dnetlib/data/search/web/api/QueryEnhancer.java	(revision 44662)
+++ modules/uoa-search/branches/newAPI/src/main/java/eu/dnetlib/data/search/web/api/QueryEnhancer.java	(revision 44663)
@@ -174,7 +174,7 @@
                 sYear = Integer.parseInt(startYear);
 
             } catch(NumberFormatException e) {
-                throw new IllegalArgumentException("startYear parameter must be a numeric value.");
+                throw new IllegalArgumentException("startYear parameter must be a numeric value.", e);
             }
         }
 
@@ -184,14 +184,12 @@
                 eYear = Integer.parseInt(endYear);
 
             } catch(NumberFormatException e) {
-                throw new IllegalArgumentException("endYear parameter must be a numeric value.");
+                throw new IllegalArgumentException("endYear parameter must be a numeric value.",e);
             }
         }
 
-        if (eYear != -1 && sYear != -1) {
-            if (eYear < sYear) {
-                throw new IllegalArgumentException("endYear must be greater than startYear.");
-            }
+        if (eYear != -1 && sYear != -1 && eYear < sYear) {
+            throw new IllegalArgumentException("endYear must be greater than startYear.");
         }
 
         addExactQueryTerm("projectstartyear", startYear, queryBuilder);
Index: modules/uoa-search/branches/newAPI/src/main/java/eu/dnetlib/data/search/web/api/APIResponseFormatter.java
===================================================================
--- modules/uoa-search/branches/newAPI/src/main/java/eu/dnetlib/data/search/web/api/APIResponseFormatter.java	(revision 44662)
+++ modules/uoa-search/branches/newAPI/src/main/java/eu/dnetlib/data/search/web/api/APIResponseFormatter.java	(revision 44663)
@@ -38,6 +38,16 @@
         return String.format(XMLResponseFormat.error500Message, message, description);
     }
 
+    public static String createCountMeta(HttpServletRequest request, String query, int total, String type) {
+        String selfPageUrl = pageUrlCreation(request);
+
+        if  (type.equals(MediaType.APPLICATION_JSON)) {
+            return String.format(JSONResponseFormat.countSearch, StringEscapeUtils.escapeJson(query), formatSelfPaging(type, selfPageUrl));
+        }
+
+        return String.format(XMLResponseFormat.countSearch, StringEscapeUtils.escapeXml10(query), formatSelfPaging(type, selfPageUrl));
+    }
+
     public static String createEntityResponse(HttpServletRequest request, RequestResponseHandler.Entity entityType, String entity, String type) {
         if (type.equals(MediaType.APPLICATION_JSON)) {
             String cleanEntity = null;
@@ -63,7 +73,6 @@
                 return String.format(JSONResponseFormat.response, createMeta(request, type, query, filters, searchResult.getTotal(), searchResult.getPage(), searchResult.getSize()), formatSearchResults(type, searchResult.getSearchResults()), "");
         }
         return String.format(XMLResponseFormat.response, createMeta(request, type, query, filters, searchResult.getTotal(), searchResult.getPage(), searchResult.getSize()), formatSearchResults(type, searchResult.getSearchResults()), "");
-
     }
 
     private static String formatRefineResults(String type, List<String> refineResults) {
@@ -114,24 +123,6 @@
         return stringBuilder.toString();
     }
 
-    /*
-    public static String createEntitiesResponse(HttpServletRequest request, RequestResponseHandler.Entity entityType,
-                                                String query, String entities, List<String> filters, int total, int currentOffset, int limit, boolean refine, List<String> refineResults, String type) {
-        if (refine) {
-            if (type.equals(MediaType.APPLICATION_JSON)) {
-                return String.format(JSONResponseFormat.response, createMeta(request, type, query, filters, total, currentOffset, limit), entities, ", refine", new Gson().toJson(refineResults));
-            }
-            return String.format(XMLResponseFormat.response, createMeta(request, type, query, filters, total, currentOffset, limit), entities, "", "");
-        }
-
-        if  (type.equals(MediaType.APPLICATION_JSON)) {
-            return String.format(JSONResponseFormat.response, createMeta(request, type, query, filters, total, currentOffset, limit), entities, "", "");
-        }
-
-        return String.format(XMLResponseFormat.response, createMeta(request, type, query, filters, total, currentOffset, limit));
-
-    }*/
-
     public static String createMetaBasic(HttpServletRequest request, String type) {
         String selfPageUrl = pageUrlCreation(request);
         if  (type.equals(MediaType.APPLICATION_JSON)) {
@@ -235,16 +226,13 @@
             return 0;
         }
 
-        return currentOffset-1;
+        int lastPage = calculateLastPage(total, limit);
+        return (currentOffset-1 < lastPage) ? (currentOffset-1) : lastPage;
     }
 
     private static int calculateNextPage(int total, int currentOffset, int limit) {
         int lastPage = calculateLastPage(total, limit);
-
-        if (currentOffset + 1 >= lastPage) {
-            return lastPage;
-        }
-        return currentOffset + 1;
+        return (currentOffset + 1 >= lastPage) ? lastPage:(currentOffset+1);
     }
 
     private static String pageUrlCreation(String urlPrefix, int offset, int limit) {
